Merge git://git.kernel.org/pub/scm/linux/kernel/git/mason/btrfs-unstable
[cascardo/linux.git] / drivers / platform / x86 / 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-2009 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.23"
25 #define TPACPI_SYSFS_VERSION 0x020400
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/sched.h>
58 #include <linux/kthread.h>
59 #include <linux/freezer.h>
60 #include <linux/delay.h>
61
62 #include <linux/nvram.h>
63 #include <linux/proc_fs.h>
64 #include <linux/sysfs.h>
65 #include <linux/backlight.h>
66 #include <linux/fb.h>
67 #include <linux/platform_device.h>
68 #include <linux/hwmon.h>
69 #include <linux/hwmon-sysfs.h>
70 #include <linux/input.h>
71 #include <linux/leds.h>
72 #include <linux/rfkill.h>
73 #include <asm/uaccess.h>
74
75 #include <linux/dmi.h>
76 #include <linux/jiffies.h>
77 #include <linux/workqueue.h>
78
79 #include <acpi/acpi_drivers.h>
80
81 #include <linux/pci_ids.h>
82
83
84 /* ThinkPad CMOS commands */
85 #define TP_CMOS_VOLUME_DOWN     0
86 #define TP_CMOS_VOLUME_UP       1
87 #define TP_CMOS_VOLUME_MUTE     2
88 #define TP_CMOS_BRIGHTNESS_UP   4
89 #define TP_CMOS_BRIGHTNESS_DOWN 5
90 #define TP_CMOS_THINKLIGHT_ON   12
91 #define TP_CMOS_THINKLIGHT_OFF  13
92
93 /* NVRAM Addresses */
94 enum tp_nvram_addr {
95         TP_NVRAM_ADDR_HK2               = 0x57,
96         TP_NVRAM_ADDR_THINKLIGHT        = 0x58,
97         TP_NVRAM_ADDR_VIDEO             = 0x59,
98         TP_NVRAM_ADDR_BRIGHTNESS        = 0x5e,
99         TP_NVRAM_ADDR_MIXER             = 0x60,
100 };
101
102 /* NVRAM bit masks */
103 enum {
104         TP_NVRAM_MASK_HKT_THINKPAD      = 0x08,
105         TP_NVRAM_MASK_HKT_ZOOM          = 0x20,
106         TP_NVRAM_MASK_HKT_DISPLAY       = 0x40,
107         TP_NVRAM_MASK_HKT_HIBERNATE     = 0x80,
108         TP_NVRAM_MASK_THINKLIGHT        = 0x10,
109         TP_NVRAM_MASK_HKT_DISPEXPND     = 0x30,
110         TP_NVRAM_MASK_HKT_BRIGHTNESS    = 0x20,
111         TP_NVRAM_MASK_LEVEL_BRIGHTNESS  = 0x0f,
112         TP_NVRAM_POS_LEVEL_BRIGHTNESS   = 0,
113         TP_NVRAM_MASK_MUTE              = 0x40,
114         TP_NVRAM_MASK_HKT_VOLUME        = 0x80,
115         TP_NVRAM_MASK_LEVEL_VOLUME      = 0x0f,
116         TP_NVRAM_POS_LEVEL_VOLUME       = 0,
117 };
118
119 /* ACPI HIDs */
120 #define TPACPI_ACPI_HKEY_HID            "IBM0068"
121
122 /* Input IDs */
123 #define TPACPI_HKEY_INPUT_PRODUCT       0x5054 /* "TP" */
124 #define TPACPI_HKEY_INPUT_VERSION       0x4101
125
126 /* ACPI \WGSV commands */
127 enum {
128         TP_ACPI_WGSV_GET_STATE          = 0x01, /* Get state information */
129         TP_ACPI_WGSV_PWR_ON_ON_RESUME   = 0x02, /* Resume WWAN powered on */
130         TP_ACPI_WGSV_PWR_OFF_ON_RESUME  = 0x03, /* Resume WWAN powered off */
131         TP_ACPI_WGSV_SAVE_STATE         = 0x04, /* Save state for S4/S5 */
132 };
133
134 /* TP_ACPI_WGSV_GET_STATE bits */
135 enum {
136         TP_ACPI_WGSV_STATE_WWANEXIST    = 0x0001, /* WWAN hw available */
137         TP_ACPI_WGSV_STATE_WWANPWR      = 0x0002, /* WWAN radio enabled */
138         TP_ACPI_WGSV_STATE_WWANPWRRES   = 0x0004, /* WWAN state at resume */
139         TP_ACPI_WGSV_STATE_WWANBIOSOFF  = 0x0008, /* WWAN disabled in BIOS */
140         TP_ACPI_WGSV_STATE_BLTHEXIST    = 0x0001, /* BLTH hw available */
141         TP_ACPI_WGSV_STATE_BLTHPWR      = 0x0002, /* BLTH radio enabled */
142         TP_ACPI_WGSV_STATE_BLTHPWRRES   = 0x0004, /* BLTH state at resume */
143         TP_ACPI_WGSV_STATE_BLTHBIOSOFF  = 0x0008, /* BLTH disabled in BIOS */
144         TP_ACPI_WGSV_STATE_UWBEXIST     = 0x0010, /* UWB hw available */
145         TP_ACPI_WGSV_STATE_UWBPWR       = 0x0020, /* UWB radio enabled */
146 };
147
148 /****************************************************************************
149  * Main driver
150  */
151
152 #define TPACPI_NAME "thinkpad"
153 #define TPACPI_DESC "ThinkPad ACPI Extras"
154 #define TPACPI_FILE TPACPI_NAME "_acpi"
155 #define TPACPI_URL "http://ibm-acpi.sf.net/"
156 #define TPACPI_MAIL "ibm-acpi-devel@lists.sourceforge.net"
157
158 #define TPACPI_PROC_DIR "ibm"
159 #define TPACPI_ACPI_EVENT_PREFIX "ibm"
160 #define TPACPI_DRVR_NAME TPACPI_FILE
161 #define TPACPI_DRVR_SHORTNAME "tpacpi"
162 #define TPACPI_HWMON_DRVR_NAME TPACPI_NAME "_hwmon"
163
164 #define TPACPI_NVRAM_KTHREAD_NAME "ktpacpi_nvramd"
165 #define TPACPI_WORKQUEUE_NAME "ktpacpid"
166
167 #define TPACPI_MAX_ACPI_ARGS 3
168
169 /* printk headers */
170 #define TPACPI_LOG TPACPI_FILE ": "
171 #define TPACPI_EMERG    KERN_EMERG      TPACPI_LOG
172 #define TPACPI_ALERT    KERN_ALERT      TPACPI_LOG
173 #define TPACPI_CRIT     KERN_CRIT       TPACPI_LOG
174 #define TPACPI_ERR      KERN_ERR        TPACPI_LOG
175 #define TPACPI_WARN     KERN_WARNING    TPACPI_LOG
176 #define TPACPI_NOTICE   KERN_NOTICE     TPACPI_LOG
177 #define TPACPI_INFO     KERN_INFO       TPACPI_LOG
178 #define TPACPI_DEBUG    KERN_DEBUG      TPACPI_LOG
179
180 /* Debugging printk groups */
181 #define TPACPI_DBG_ALL          0xffff
182 #define TPACPI_DBG_DISCLOSETASK 0x8000
183 #define TPACPI_DBG_INIT         0x0001
184 #define TPACPI_DBG_EXIT         0x0002
185 #define TPACPI_DBG_RFKILL       0x0004
186 #define TPACPI_DBG_HKEY         0x0008
187 #define TPACPI_DBG_FAN          0x0010
188 #define TPACPI_DBG_BRGHT        0x0020
189
190 #define onoff(status, bit) ((status) & (1 << (bit)) ? "on" : "off")
191 #define enabled(status, bit) ((status) & (1 << (bit)) ? "enabled" : "disabled")
192 #define strlencmp(a, b) (strncmp((a), (b), strlen(b)))
193
194
195 /****************************************************************************
196  * Driver-wide structs and misc. variables
197  */
198
199 struct ibm_struct;
200
201 struct tp_acpi_drv_struct {
202         const struct acpi_device_id *hid;
203         struct acpi_driver *driver;
204
205         void (*notify) (struct ibm_struct *, u32);
206         acpi_handle *handle;
207         u32 type;
208         struct acpi_device *device;
209 };
210
211 struct ibm_struct {
212         char *name;
213
214         int (*read) (char *);
215         int (*write) (char *);
216         void (*exit) (void);
217         void (*resume) (void);
218         void (*suspend) (pm_message_t state);
219         void (*shutdown) (void);
220
221         struct list_head all_drivers;
222
223         struct tp_acpi_drv_struct *acpi;
224
225         struct {
226                 u8 acpi_driver_registered:1;
227                 u8 acpi_notify_installed:1;
228                 u8 proc_created:1;
229                 u8 init_called:1;
230                 u8 experimental:1;
231         } flags;
232 };
233
234 struct ibm_init_struct {
235         char param[32];
236
237         int (*init) (struct ibm_init_struct *);
238         struct ibm_struct *data;
239 };
240
241 static struct {
242 #ifdef CONFIG_THINKPAD_ACPI_BAY
243         u32 bay_status:1;
244         u32 bay_eject:1;
245         u32 bay_status2:1;
246         u32 bay_eject2:1;
247 #endif
248         u32 bluetooth:1;
249         u32 hotkey:1;
250         u32 hotkey_mask:1;
251         u32 hotkey_wlsw:1;
252         u32 hotkey_tablet:1;
253         u32 light:1;
254         u32 light_status:1;
255         u32 bright_16levels:1;
256         u32 bright_acpimode:1;
257         u32 wan:1;
258         u32 uwb:1;
259         u32 fan_ctrl_status_undef:1;
260         u32 second_fan:1;
261         u32 beep_needs_two_args:1;
262         u32 input_device_registered:1;
263         u32 platform_drv_registered:1;
264         u32 platform_drv_attrs_registered:1;
265         u32 sensors_pdrv_registered:1;
266         u32 sensors_pdrv_attrs_registered:1;
267         u32 sensors_pdev_attrs_registered:1;
268         u32 hotkey_poll_active:1;
269 } tp_features;
270
271 static struct {
272         u16 hotkey_mask_ff:1;
273 } tp_warned;
274
275 struct thinkpad_id_data {
276         unsigned int vendor;    /* ThinkPad vendor:
277                                  * PCI_VENDOR_ID_IBM/PCI_VENDOR_ID_LENOVO */
278
279         char *bios_version_str; /* Something like 1ZET51WW (1.03z) */
280         char *ec_version_str;   /* Something like 1ZHT51WW-1.04a */
281
282         u16 bios_model;         /* 1Y = 0x5931, 0 = unknown */
283         u16 ec_model;
284         u16 bios_release;       /* 1ZETK1WW = 0x314b, 0 = unknown */
285         u16 ec_release;
286
287         char *model_str;        /* ThinkPad T43 */
288         char *nummodel_str;     /* 9384A9C for a 9384-A9C model */
289 };
290 static struct thinkpad_id_data thinkpad_id;
291
292 static enum {
293         TPACPI_LIFE_INIT = 0,
294         TPACPI_LIFE_RUNNING,
295         TPACPI_LIFE_EXITING,
296 } tpacpi_lifecycle;
297
298 static int experimental;
299 static u32 dbg_level;
300
301 static struct workqueue_struct *tpacpi_wq;
302
303 enum led_status_t {
304         TPACPI_LED_OFF = 0,
305         TPACPI_LED_ON,
306         TPACPI_LED_BLINK,
307 };
308
309 /* Special LED class that can defer work */
310 struct tpacpi_led_classdev {
311         struct led_classdev led_classdev;
312         struct work_struct work;
313         enum led_status_t new_state;
314         unsigned int led;
315 };
316
317 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
318 static int dbg_wlswemul;
319 static int tpacpi_wlsw_emulstate;
320 static int dbg_bluetoothemul;
321 static int tpacpi_bluetooth_emulstate;
322 static int dbg_wwanemul;
323 static int tpacpi_wwan_emulstate;
324 static int dbg_uwbemul;
325 static int tpacpi_uwb_emulstate;
326 #endif
327
328
329 /*************************************************************************
330  *  Debugging helpers
331  */
332
333 #define dbg_printk(a_dbg_level, format, arg...) \
334         do { if (dbg_level & (a_dbg_level)) \
335                 printk(TPACPI_DEBUG "%s: " format, __func__ , ## arg); \
336         } while (0)
337
338 #ifdef CONFIG_THINKPAD_ACPI_DEBUG
339 #define vdbg_printk dbg_printk
340 static const char *str_supported(int is_supported);
341 #else
342 #define vdbg_printk(a_dbg_level, format, arg...) \
343         do { } while (0)
344 #endif
345
346 static void tpacpi_log_usertask(const char * const what)
347 {
348         printk(TPACPI_DEBUG "%s: access by process with PID %d\n",
349                 what, task_tgid_vnr(current));
350 }
351
352 #define tpacpi_disclose_usertask(what, format, arg...) \
353         do { \
354                 if (unlikely( \
355                     (dbg_level & TPACPI_DBG_DISCLOSETASK) && \
356                     (tpacpi_lifecycle == TPACPI_LIFE_RUNNING))) { \
357                         printk(TPACPI_DEBUG "%s: PID %d: " format, \
358                                 what, task_tgid_vnr(current), ## arg); \
359                 } \
360         } while (0)
361
362 /*
363  * Quirk handling helpers
364  *
365  * ThinkPad IDs and versions seen in the field so far
366  * are two-characters from the set [0-9A-Z], i.e. base 36.
367  *
368  * We use values well outside that range as specials.
369  */
370
371 #define TPACPI_MATCH_ANY                0xffffU
372 #define TPACPI_MATCH_UNKNOWN            0U
373
374 /* TPID('1', 'Y') == 0x5931 */
375 #define TPID(__c1, __c2) (((__c2) << 8) | (__c1))
376
377 #define TPACPI_Q_IBM(__id1, __id2, __quirk)     \
378         { .vendor = PCI_VENDOR_ID_IBM,          \
379           .bios = TPID(__id1, __id2),           \
380           .ec = TPACPI_MATCH_ANY,               \
381           .quirks = (__quirk) }
382
383 #define TPACPI_Q_LNV(__id1, __id2, __quirk)     \
384         { .vendor = PCI_VENDOR_ID_LENOVO,       \
385           .bios = TPID(__id1, __id2),           \
386           .ec = TPACPI_MATCH_ANY,               \
387           .quirks = (__quirk) }
388
389 struct tpacpi_quirk {
390         unsigned int vendor;
391         u16 bios;
392         u16 ec;
393         unsigned long quirks;
394 };
395
396 /**
397  * tpacpi_check_quirks() - search BIOS/EC version on a list
398  * @qlist:              array of &struct tpacpi_quirk
399  * @qlist_size:         number of elements in @qlist
400  *
401  * Iterates over a quirks list until one is found that matches the
402  * ThinkPad's vendor, BIOS and EC model.
403  *
404  * Returns 0 if nothing matches, otherwise returns the quirks field of
405  * the matching &struct tpacpi_quirk entry.
406  *
407  * The match criteria is: vendor, ec and bios much match.
408  */
409 static unsigned long __init tpacpi_check_quirks(
410                         const struct tpacpi_quirk *qlist,
411                         unsigned int qlist_size)
412 {
413         while (qlist_size) {
414                 if ((qlist->vendor == thinkpad_id.vendor ||
415                                 qlist->vendor == TPACPI_MATCH_ANY) &&
416                     (qlist->bios == thinkpad_id.bios_model ||
417                                 qlist->bios == TPACPI_MATCH_ANY) &&
418                     (qlist->ec == thinkpad_id.ec_model ||
419                                 qlist->ec == TPACPI_MATCH_ANY))
420                         return qlist->quirks;
421
422                 qlist_size--;
423                 qlist++;
424         }
425         return 0;
426 }
427
428
429 /****************************************************************************
430  ****************************************************************************
431  *
432  * ACPI Helpers and device model
433  *
434  ****************************************************************************
435  ****************************************************************************/
436
437 /*************************************************************************
438  * ACPI basic handles
439  */
440
441 static acpi_handle root_handle;
442
443 #define TPACPI_HANDLE(object, parent, paths...)                 \
444         static acpi_handle  object##_handle;                    \
445         static acpi_handle *object##_parent = &parent##_handle; \
446         static char        *object##_path;                      \
447         static char        *object##_paths[] = { paths }
448
449 TPACPI_HANDLE(ec, root, "\\_SB.PCI0.ISA.EC0",   /* 240, 240x */
450            "\\_SB.PCI.ISA.EC",  /* 570 */
451            "\\_SB.PCI0.ISA0.EC0",       /* 600e/x, 770e, 770x */
452            "\\_SB.PCI0.ISA.EC", /* A21e, A2xm/p, T20-22, X20-21 */
453            "\\_SB.PCI0.AD4S.EC0",       /* i1400, R30 */
454            "\\_SB.PCI0.ICH3.EC0",       /* R31 */
455            "\\_SB.PCI0.LPC.EC", /* all others */
456            );
457
458 TPACPI_HANDLE(ecrd, ec, "ECRD");        /* 570 */
459 TPACPI_HANDLE(ecwr, ec, "ECWR");        /* 570 */
460
461 TPACPI_HANDLE(cmos, root, "\\UCMS",     /* R50, R50e, R50p, R51, */
462                                         /* T4x, X31, X40 */
463            "\\CMOS",            /* A3x, G4x, R32, T23, T30, X22-24, X30 */
464            "\\CMS",             /* R40, R40e */
465            );                   /* all others */
466
467 TPACPI_HANDLE(hkey, ec, "\\_SB.HKEY",   /* 600e/x, 770e, 770x */
468            "^HKEY",             /* R30, R31 */
469            "HKEY",              /* all others */
470            );                   /* 570 */
471
472 TPACPI_HANDLE(vid, root, "\\_SB.PCI.AGP.VGA",   /* 570 */
473            "\\_SB.PCI0.AGP0.VID0",      /* 600e/x, 770x */
474            "\\_SB.PCI0.VID0",   /* 770e */
475            "\\_SB.PCI0.VID",    /* A21e, G4x, R50e, X30, X40 */
476            "\\_SB.PCI0.AGP.VID",        /* all others */
477            );                           /* R30, R31 */
478
479
480 /*************************************************************************
481  * ACPI helpers
482  */
483
484 static int acpi_evalf(acpi_handle handle,
485                       void *res, char *method, char *fmt, ...)
486 {
487         char *fmt0 = fmt;
488         struct acpi_object_list params;
489         union acpi_object in_objs[TPACPI_MAX_ACPI_ARGS];
490         struct acpi_buffer result, *resultp;
491         union acpi_object out_obj;
492         acpi_status status;
493         va_list ap;
494         char res_type;
495         int success;
496         int quiet;
497
498         if (!*fmt) {
499                 printk(TPACPI_ERR "acpi_evalf() called with empty format\n");
500                 return 0;
501         }
502
503         if (*fmt == 'q') {
504                 quiet = 1;
505                 fmt++;
506         } else
507                 quiet = 0;
508
509         res_type = *(fmt++);
510
511         params.count = 0;
512         params.pointer = &in_objs[0];
513
514         va_start(ap, fmt);
515         while (*fmt) {
516                 char c = *(fmt++);
517                 switch (c) {
518                 case 'd':       /* int */
519                         in_objs[params.count].integer.value = va_arg(ap, int);
520                         in_objs[params.count++].type = ACPI_TYPE_INTEGER;
521                         break;
522                         /* add more types as needed */
523                 default:
524                         printk(TPACPI_ERR "acpi_evalf() called "
525                                "with invalid format character '%c'\n", c);
526                         return 0;
527                 }
528         }
529         va_end(ap);
530
531         if (res_type != 'v') {
532                 result.length = sizeof(out_obj);
533                 result.pointer = &out_obj;
534                 resultp = &result;
535         } else
536                 resultp = NULL;
537
538         status = acpi_evaluate_object(handle, method, &params, resultp);
539
540         switch (res_type) {
541         case 'd':               /* int */
542                 if (res)
543                         *(int *)res = out_obj.integer.value;
544                 success = status == AE_OK && out_obj.type == ACPI_TYPE_INTEGER;
545                 break;
546         case 'v':               /* void */
547                 success = status == AE_OK;
548                 break;
549                 /* add more types as needed */
550         default:
551                 printk(TPACPI_ERR "acpi_evalf() called "
552                        "with invalid format character '%c'\n", res_type);
553                 return 0;
554         }
555
556         if (!success && !quiet)
557                 printk(TPACPI_ERR "acpi_evalf(%s, %s, ...) failed: %d\n",
558                        method, fmt0, status);
559
560         return success;
561 }
562
563 static int acpi_ec_read(int i, u8 *p)
564 {
565         int v;
566
567         if (ecrd_handle) {
568                 if (!acpi_evalf(ecrd_handle, &v, NULL, "dd", i))
569                         return 0;
570                 *p = v;
571         } else {
572                 if (ec_read(i, p) < 0)
573                         return 0;
574         }
575
576         return 1;
577 }
578
579 static int acpi_ec_write(int i, u8 v)
580 {
581         if (ecwr_handle) {
582                 if (!acpi_evalf(ecwr_handle, NULL, NULL, "vdd", i, v))
583                         return 0;
584         } else {
585                 if (ec_write(i, v) < 0)
586                         return 0;
587         }
588
589         return 1;
590 }
591
592 #if defined(CONFIG_THINKPAD_ACPI_DOCK) || defined(CONFIG_THINKPAD_ACPI_BAY)
593 static int _sta(acpi_handle handle)
594 {
595         int status;
596
597         if (!handle || !acpi_evalf(handle, &status, "_STA", "d"))
598                 status = 0;
599
600         return status;
601 }
602 #endif
603
604 static int issue_thinkpad_cmos_command(int cmos_cmd)
605 {
606         if (!cmos_handle)
607                 return -ENXIO;
608
609         if (!acpi_evalf(cmos_handle, NULL, NULL, "vd", cmos_cmd))
610                 return -EIO;
611
612         return 0;
613 }
614
615 /*************************************************************************
616  * ACPI device model
617  */
618
619 #define TPACPI_ACPIHANDLE_INIT(object) \
620         drv_acpi_handle_init(#object, &object##_handle, *object##_parent, \
621                 object##_paths, ARRAY_SIZE(object##_paths), &object##_path)
622
623 static void drv_acpi_handle_init(char *name,
624                            acpi_handle *handle, acpi_handle parent,
625                            char **paths, int num_paths, char **path)
626 {
627         int i;
628         acpi_status status;
629
630         vdbg_printk(TPACPI_DBG_INIT, "trying to locate ACPI handle for %s\n",
631                 name);
632
633         for (i = 0; i < num_paths; i++) {
634                 status = acpi_get_handle(parent, paths[i], handle);
635                 if (ACPI_SUCCESS(status)) {
636                         *path = paths[i];
637                         dbg_printk(TPACPI_DBG_INIT,
638                                    "Found ACPI handle %s for %s\n",
639                                    *path, name);
640                         return;
641                 }
642         }
643
644         vdbg_printk(TPACPI_DBG_INIT, "ACPI handle for %s not found\n",
645                     name);
646         *handle = NULL;
647 }
648
649 static void dispatch_acpi_notify(acpi_handle handle, u32 event, void *data)
650 {
651         struct ibm_struct *ibm = data;
652
653         if (tpacpi_lifecycle != TPACPI_LIFE_RUNNING)
654                 return;
655
656         if (!ibm || !ibm->acpi || !ibm->acpi->notify)
657                 return;
658
659         ibm->acpi->notify(ibm, event);
660 }
661
662 static int __init setup_acpi_notify(struct ibm_struct *ibm)
663 {
664         acpi_status status;
665         int rc;
666
667         BUG_ON(!ibm->acpi);
668
669         if (!*ibm->acpi->handle)
670                 return 0;
671
672         vdbg_printk(TPACPI_DBG_INIT,
673                 "setting up ACPI notify for %s\n", ibm->name);
674
675         rc = acpi_bus_get_device(*ibm->acpi->handle, &ibm->acpi->device);
676         if (rc < 0) {
677                 printk(TPACPI_ERR "acpi_bus_get_device(%s) failed: %d\n",
678                         ibm->name, rc);
679                 return -ENODEV;
680         }
681
682         ibm->acpi->device->driver_data = ibm;
683         sprintf(acpi_device_class(ibm->acpi->device), "%s/%s",
684                 TPACPI_ACPI_EVENT_PREFIX,
685                 ibm->name);
686
687         status = acpi_install_notify_handler(*ibm->acpi->handle,
688                         ibm->acpi->type, dispatch_acpi_notify, ibm);
689         if (ACPI_FAILURE(status)) {
690                 if (status == AE_ALREADY_EXISTS) {
691                         printk(TPACPI_NOTICE
692                                "another device driver is already "
693                                "handling %s events\n", ibm->name);
694                 } else {
695                         printk(TPACPI_ERR
696                                "acpi_install_notify_handler(%s) failed: %d\n",
697                                ibm->name, status);
698                 }
699                 return -ENODEV;
700         }
701         ibm->flags.acpi_notify_installed = 1;
702         return 0;
703 }
704
705 static int __init tpacpi_device_add(struct acpi_device *device)
706 {
707         return 0;
708 }
709
710 static int __init register_tpacpi_subdriver(struct ibm_struct *ibm)
711 {
712         int rc;
713
714         dbg_printk(TPACPI_DBG_INIT,
715                 "registering %s as an ACPI driver\n", ibm->name);
716
717         BUG_ON(!ibm->acpi);
718
719         ibm->acpi->driver = kzalloc(sizeof(struct acpi_driver), GFP_KERNEL);
720         if (!ibm->acpi->driver) {
721                 printk(TPACPI_ERR
722                        "failed to allocate memory for ibm->acpi->driver\n");
723                 return -ENOMEM;
724         }
725
726         sprintf(ibm->acpi->driver->name, "%s_%s", TPACPI_NAME, ibm->name);
727         ibm->acpi->driver->ids = ibm->acpi->hid;
728
729         ibm->acpi->driver->ops.add = &tpacpi_device_add;
730
731         rc = acpi_bus_register_driver(ibm->acpi->driver);
732         if (rc < 0) {
733                 printk(TPACPI_ERR "acpi_bus_register_driver(%s) failed: %d\n",
734                        ibm->name, rc);
735                 kfree(ibm->acpi->driver);
736                 ibm->acpi->driver = NULL;
737         } else if (!rc)
738                 ibm->flags.acpi_driver_registered = 1;
739
740         return rc;
741 }
742
743
744 /****************************************************************************
745  ****************************************************************************
746  *
747  * Procfs Helpers
748  *
749  ****************************************************************************
750  ****************************************************************************/
751
752 static int dispatch_procfs_read(char *page, char **start, off_t off,
753                         int count, int *eof, void *data)
754 {
755         struct ibm_struct *ibm = data;
756         int len;
757
758         if (!ibm || !ibm->read)
759                 return -EINVAL;
760
761         len = ibm->read(page);
762         if (len < 0)
763                 return len;
764
765         if (len <= off + count)
766                 *eof = 1;
767         *start = page + off;
768         len -= off;
769         if (len > count)
770                 len = count;
771         if (len < 0)
772                 len = 0;
773
774         return len;
775 }
776
777 static int dispatch_procfs_write(struct file *file,
778                         const char __user *userbuf,
779                         unsigned long count, void *data)
780 {
781         struct ibm_struct *ibm = data;
782         char *kernbuf;
783         int ret;
784
785         if (!ibm || !ibm->write)
786                 return -EINVAL;
787
788         kernbuf = kmalloc(count + 2, GFP_KERNEL);
789         if (!kernbuf)
790                 return -ENOMEM;
791
792         if (copy_from_user(kernbuf, userbuf, count)) {
793                 kfree(kernbuf);
794                 return -EFAULT;
795         }
796
797         kernbuf[count] = 0;
798         strcat(kernbuf, ",");
799         ret = ibm->write(kernbuf);
800         if (ret == 0)
801                 ret = count;
802
803         kfree(kernbuf);
804
805         return ret;
806 }
807
808 static char *next_cmd(char **cmds)
809 {
810         char *start = *cmds;
811         char *end;
812
813         while ((end = strchr(start, ',')) && end == start)
814                 start = end + 1;
815
816         if (!end)
817                 return NULL;
818
819         *end = 0;
820         *cmds = end + 1;
821         return start;
822 }
823
824
825 /****************************************************************************
826  ****************************************************************************
827  *
828  * Device model: input, hwmon and platform
829  *
830  ****************************************************************************
831  ****************************************************************************/
832
833 static struct platform_device *tpacpi_pdev;
834 static struct platform_device *tpacpi_sensors_pdev;
835 static struct device *tpacpi_hwmon;
836 static struct input_dev *tpacpi_inputdev;
837 static struct mutex tpacpi_inputdev_send_mutex;
838 static LIST_HEAD(tpacpi_all_drivers);
839
840 static int tpacpi_suspend_handler(struct platform_device *pdev,
841                                   pm_message_t state)
842 {
843         struct ibm_struct *ibm, *itmp;
844
845         list_for_each_entry_safe(ibm, itmp,
846                                  &tpacpi_all_drivers,
847                                  all_drivers) {
848                 if (ibm->suspend)
849                         (ibm->suspend)(state);
850         }
851
852         return 0;
853 }
854
855 static int tpacpi_resume_handler(struct platform_device *pdev)
856 {
857         struct ibm_struct *ibm, *itmp;
858
859         list_for_each_entry_safe(ibm, itmp,
860                                  &tpacpi_all_drivers,
861                                  all_drivers) {
862                 if (ibm->resume)
863                         (ibm->resume)();
864         }
865
866         return 0;
867 }
868
869 static void tpacpi_shutdown_handler(struct platform_device *pdev)
870 {
871         struct ibm_struct *ibm, *itmp;
872
873         list_for_each_entry_safe(ibm, itmp,
874                                  &tpacpi_all_drivers,
875                                  all_drivers) {
876                 if (ibm->shutdown)
877                         (ibm->shutdown)();
878         }
879 }
880
881 static struct platform_driver tpacpi_pdriver = {
882         .driver = {
883                 .name = TPACPI_DRVR_NAME,
884                 .owner = THIS_MODULE,
885         },
886         .suspend = tpacpi_suspend_handler,
887         .resume = tpacpi_resume_handler,
888         .shutdown = tpacpi_shutdown_handler,
889 };
890
891 static struct platform_driver tpacpi_hwmon_pdriver = {
892         .driver = {
893                 .name = TPACPI_HWMON_DRVR_NAME,
894                 .owner = THIS_MODULE,
895         },
896 };
897
898 /*************************************************************************
899  * sysfs support helpers
900  */
901
902 struct attribute_set {
903         unsigned int members, max_members;
904         struct attribute_group group;
905 };
906
907 struct attribute_set_obj {
908         struct attribute_set s;
909         struct attribute *a;
910 } __attribute__((packed));
911
912 static struct attribute_set *create_attr_set(unsigned int max_members,
913                                                 const char *name)
914 {
915         struct attribute_set_obj *sobj;
916
917         if (max_members == 0)
918                 return NULL;
919
920         /* Allocates space for implicit NULL at the end too */
921         sobj = kzalloc(sizeof(struct attribute_set_obj) +
922                     max_members * sizeof(struct attribute *),
923                     GFP_KERNEL);
924         if (!sobj)
925                 return NULL;
926         sobj->s.max_members = max_members;
927         sobj->s.group.attrs = &sobj->a;
928         sobj->s.group.name = name;
929
930         return &sobj->s;
931 }
932
933 #define destroy_attr_set(_set) \
934         kfree(_set);
935
936 /* not multi-threaded safe, use it in a single thread per set */
937 static int add_to_attr_set(struct attribute_set *s, struct attribute *attr)
938 {
939         if (!s || !attr)
940                 return -EINVAL;
941
942         if (s->members >= s->max_members)
943                 return -ENOMEM;
944
945         s->group.attrs[s->members] = attr;
946         s->members++;
947
948         return 0;
949 }
950
951 static int add_many_to_attr_set(struct attribute_set *s,
952                         struct attribute **attr,
953                         unsigned int count)
954 {
955         int i, res;
956
957         for (i = 0; i < count; i++) {
958                 res = add_to_attr_set(s, attr[i]);
959                 if (res)
960                         return res;
961         }
962
963         return 0;
964 }
965
966 static void delete_attr_set(struct attribute_set *s, struct kobject *kobj)
967 {
968         sysfs_remove_group(kobj, &s->group);
969         destroy_attr_set(s);
970 }
971
972 #define register_attr_set_with_sysfs(_attr_set, _kobj) \
973         sysfs_create_group(_kobj, &_attr_set->group)
974
975 static int parse_strtoul(const char *buf,
976                 unsigned long max, unsigned long *value)
977 {
978         char *endp;
979
980         while (*buf && isspace(*buf))
981                 buf++;
982         *value = simple_strtoul(buf, &endp, 0);
983         while (*endp && isspace(*endp))
984                 endp++;
985         if (*endp || *value > max)
986                 return -EINVAL;
987
988         return 0;
989 }
990
991 static void tpacpi_disable_brightness_delay(void)
992 {
993         if (acpi_evalf(hkey_handle, NULL, "PWMS", "qvd", 0))
994                 printk(TPACPI_NOTICE
995                         "ACPI backlight control delay disabled\n");
996 }
997
998 static int __init tpacpi_query_bcl_levels(acpi_handle handle)
999 {
1000         struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
1001         union acpi_object *obj;
1002         int rc;
1003
1004         if (ACPI_SUCCESS(acpi_evaluate_object(handle, NULL, NULL, &buffer))) {
1005                 obj = (union acpi_object *)buffer.pointer;
1006                 if (!obj || (obj->type != ACPI_TYPE_PACKAGE)) {
1007                         printk(TPACPI_ERR "Unknown _BCL data, "
1008                                "please report this to %s\n", TPACPI_MAIL);
1009                         rc = 0;
1010                 } else {
1011                         rc = obj->package.count;
1012                 }
1013         } else {
1014                 return 0;
1015         }
1016
1017         kfree(buffer.pointer);
1018         return rc;
1019 }
1020
1021 static acpi_status __init tpacpi_acpi_walk_find_bcl(acpi_handle handle,
1022                                         u32 lvl, void *context, void **rv)
1023 {
1024         char name[ACPI_PATH_SEGMENT_LENGTH];
1025         struct acpi_buffer buffer = { sizeof(name), &name };
1026
1027         if (ACPI_SUCCESS(acpi_get_name(handle, ACPI_SINGLE_NAME, &buffer)) &&
1028             !strncmp("_BCL", name, sizeof(name) - 1)) {
1029                 BUG_ON(!rv || !*rv);
1030                 **(int **)rv = tpacpi_query_bcl_levels(handle);
1031                 return AE_CTRL_TERMINATE;
1032         } else {
1033                 return AE_OK;
1034         }
1035 }
1036
1037 /*
1038  * Returns 0 (no ACPI _BCL or _BCL invalid), or size of brightness map
1039  */
1040 static int __init tpacpi_check_std_acpi_brightness_support(void)
1041 {
1042         int status;
1043         int bcl_levels = 0;
1044         void *bcl_ptr = &bcl_levels;
1045
1046         if (!vid_handle) {
1047                 TPACPI_ACPIHANDLE_INIT(vid);
1048         }
1049         if (!vid_handle)
1050                 return 0;
1051
1052         /*
1053          * Search for a _BCL method, and execute it.  This is safe on all
1054          * ThinkPads, and as a side-effect, _BCL will place a Lenovo Vista
1055          * BIOS in ACPI backlight control mode.  We do NOT have to care
1056          * about calling the _BCL method in an enabled video device, any
1057          * will do for our purposes.
1058          */
1059
1060         status = acpi_walk_namespace(ACPI_TYPE_METHOD, vid_handle, 3,
1061                                      tpacpi_acpi_walk_find_bcl, NULL,
1062                                      &bcl_ptr);
1063
1064         if (ACPI_SUCCESS(status) && bcl_levels > 2) {
1065                 tp_features.bright_acpimode = 1;
1066                 return (bcl_levels - 2);
1067         }
1068
1069         return 0;
1070 }
1071
1072 static void printk_deprecated_attribute(const char * const what,
1073                                         const char * const details)
1074 {
1075         tpacpi_log_usertask("deprecated sysfs attribute");
1076         printk(TPACPI_WARN "WARNING: sysfs attribute %s is deprecated and "
1077                 "will be removed. %s\n",
1078                 what, details);
1079 }
1080
1081 /*************************************************************************
1082  * rfkill and radio control support helpers
1083  */
1084
1085 /*
1086  * ThinkPad-ACPI firmware handling model:
1087  *
1088  * WLSW (master wireless switch) is event-driven, and is common to all
1089  * firmware-controlled radios.  It cannot be controlled, just monitored,
1090  * as expected.  It overrides all radio state in firmware
1091  *
1092  * The kernel, a masked-off hotkey, and WLSW can change the radio state
1093  * (TODO: verify how WLSW interacts with the returned radio state).
1094  *
1095  * The only time there are shadow radio state changes, is when
1096  * masked-off hotkeys are used.
1097  */
1098
1099 /*
1100  * Internal driver API for radio state:
1101  *
1102  * int: < 0 = error, otherwise enum tpacpi_rfkill_state
1103  * bool: true means radio blocked (off)
1104  */
1105 enum tpacpi_rfkill_state {
1106         TPACPI_RFK_RADIO_OFF = 0,
1107         TPACPI_RFK_RADIO_ON
1108 };
1109
1110 /* rfkill switches */
1111 enum tpacpi_rfk_id {
1112         TPACPI_RFK_BLUETOOTH_SW_ID = 0,
1113         TPACPI_RFK_WWAN_SW_ID,
1114         TPACPI_RFK_UWB_SW_ID,
1115         TPACPI_RFK_SW_MAX
1116 };
1117
1118 static const char *tpacpi_rfkill_names[] = {
1119         [TPACPI_RFK_BLUETOOTH_SW_ID] = "bluetooth",
1120         [TPACPI_RFK_WWAN_SW_ID] = "wwan",
1121         [TPACPI_RFK_UWB_SW_ID] = "uwb",
1122         [TPACPI_RFK_SW_MAX] = NULL
1123 };
1124
1125 /* ThinkPad-ACPI rfkill subdriver */
1126 struct tpacpi_rfk {
1127         struct rfkill *rfkill;
1128         enum tpacpi_rfk_id id;
1129         const struct tpacpi_rfk_ops *ops;
1130 };
1131
1132 struct tpacpi_rfk_ops {
1133         /* firmware interface */
1134         int (*get_status)(void);
1135         int (*set_status)(const enum tpacpi_rfkill_state);
1136 };
1137
1138 static struct tpacpi_rfk *tpacpi_rfkill_switches[TPACPI_RFK_SW_MAX];
1139
1140 /* Query FW and update rfkill sw state for a given rfkill switch */
1141 static int tpacpi_rfk_update_swstate(const struct tpacpi_rfk *tp_rfk)
1142 {
1143         int status;
1144
1145         if (!tp_rfk)
1146                 return -ENODEV;
1147
1148         status = (tp_rfk->ops->get_status)();
1149         if (status < 0)
1150                 return status;
1151
1152         rfkill_set_sw_state(tp_rfk->rfkill,
1153                             (status == TPACPI_RFK_RADIO_OFF));
1154
1155         return status;
1156 }
1157
1158 /* Query FW and update rfkill sw state for all rfkill switches */
1159 static void tpacpi_rfk_update_swstate_all(void)
1160 {
1161         unsigned int i;
1162
1163         for (i = 0; i < TPACPI_RFK_SW_MAX; i++)
1164                 tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[i]);
1165 }
1166
1167 /*
1168  * Sync the HW-blocking state of all rfkill switches,
1169  * do notice it causes the rfkill core to schedule uevents
1170  */
1171 static void tpacpi_rfk_update_hwblock_state(bool blocked)
1172 {
1173         unsigned int i;
1174         struct tpacpi_rfk *tp_rfk;
1175
1176         for (i = 0; i < TPACPI_RFK_SW_MAX; i++) {
1177                 tp_rfk = tpacpi_rfkill_switches[i];
1178                 if (tp_rfk) {
1179                         if (rfkill_set_hw_state(tp_rfk->rfkill,
1180                                                 blocked)) {
1181                                 /* ignore -- we track sw block */
1182                         }
1183                 }
1184         }
1185 }
1186
1187 /* Call to get the WLSW state from the firmware */
1188 static int hotkey_get_wlsw(void);
1189
1190 /* Call to query WLSW state and update all rfkill switches */
1191 static bool tpacpi_rfk_check_hwblock_state(void)
1192 {
1193         int res = hotkey_get_wlsw();
1194         int hw_blocked;
1195
1196         /* When unknown or unsupported, we have to assume it is unblocked */
1197         if (res < 0)
1198                 return false;
1199
1200         hw_blocked = (res == TPACPI_RFK_RADIO_OFF);
1201         tpacpi_rfk_update_hwblock_state(hw_blocked);
1202
1203         return hw_blocked;
1204 }
1205
1206 static int tpacpi_rfk_hook_set_block(void *data, bool blocked)
1207 {
1208         struct tpacpi_rfk *tp_rfk = data;
1209         int res;
1210
1211         dbg_printk(TPACPI_DBG_RFKILL,
1212                    "request to change radio state to %s\n",
1213                    blocked ? "blocked" : "unblocked");
1214
1215         /* try to set radio state */
1216         res = (tp_rfk->ops->set_status)(blocked ?
1217                                 TPACPI_RFK_RADIO_OFF : TPACPI_RFK_RADIO_ON);
1218
1219         /* and update the rfkill core with whatever the FW really did */
1220         tpacpi_rfk_update_swstate(tp_rfk);
1221
1222         return (res < 0) ? res : 0;
1223 }
1224
1225 static const struct rfkill_ops tpacpi_rfk_rfkill_ops = {
1226         .set_block = tpacpi_rfk_hook_set_block,
1227 };
1228
1229 static int __init tpacpi_new_rfkill(const enum tpacpi_rfk_id id,
1230                         const struct tpacpi_rfk_ops *tp_rfkops,
1231                         const enum rfkill_type rfktype,
1232                         const char *name,
1233                         const bool set_default)
1234 {
1235         struct tpacpi_rfk *atp_rfk;
1236         int res;
1237         bool sw_state = false;
1238         int sw_status;
1239
1240         BUG_ON(id >= TPACPI_RFK_SW_MAX || tpacpi_rfkill_switches[id]);
1241
1242         atp_rfk = kzalloc(sizeof(struct tpacpi_rfk), GFP_KERNEL);
1243         if (atp_rfk)
1244                 atp_rfk->rfkill = rfkill_alloc(name,
1245                                                 &tpacpi_pdev->dev,
1246                                                 rfktype,
1247                                                 &tpacpi_rfk_rfkill_ops,
1248                                                 atp_rfk);
1249         if (!atp_rfk || !atp_rfk->rfkill) {
1250                 printk(TPACPI_ERR
1251                         "failed to allocate memory for rfkill class\n");
1252                 kfree(atp_rfk);
1253                 return -ENOMEM;
1254         }
1255
1256         atp_rfk->id = id;
1257         atp_rfk->ops = tp_rfkops;
1258
1259         sw_status = (tp_rfkops->get_status)();
1260         if (sw_status < 0) {
1261                 printk(TPACPI_ERR
1262                         "failed to read initial state for %s, error %d\n",
1263                         name, sw_status);
1264         } else {
1265                 sw_state = (sw_status == TPACPI_RFK_RADIO_OFF);
1266                 if (set_default) {
1267                         /* try to keep the initial state, since we ask the
1268                          * firmware to preserve it across S5 in NVRAM */
1269                         rfkill_init_sw_state(atp_rfk->rfkill, sw_state);
1270                 }
1271         }
1272         rfkill_set_hw_state(atp_rfk->rfkill, tpacpi_rfk_check_hwblock_state());
1273
1274         res = rfkill_register(atp_rfk->rfkill);
1275         if (res < 0) {
1276                 printk(TPACPI_ERR
1277                         "failed to register %s rfkill switch: %d\n",
1278                         name, res);
1279                 rfkill_destroy(atp_rfk->rfkill);
1280                 kfree(atp_rfk);
1281                 return res;
1282         }
1283
1284         tpacpi_rfkill_switches[id] = atp_rfk;
1285         return 0;
1286 }
1287
1288 static void tpacpi_destroy_rfkill(const enum tpacpi_rfk_id id)
1289 {
1290         struct tpacpi_rfk *tp_rfk;
1291
1292         BUG_ON(id >= TPACPI_RFK_SW_MAX);
1293
1294         tp_rfk = tpacpi_rfkill_switches[id];
1295         if (tp_rfk) {
1296                 rfkill_unregister(tp_rfk->rfkill);
1297                 tpacpi_rfkill_switches[id] = NULL;
1298                 kfree(tp_rfk);
1299         }
1300 }
1301
1302 static void printk_deprecated_rfkill_attribute(const char * const what)
1303 {
1304         printk_deprecated_attribute(what,
1305                         "Please switch to generic rfkill before year 2010");
1306 }
1307
1308 /* sysfs <radio> enable ------------------------------------------------ */
1309 static ssize_t tpacpi_rfk_sysfs_enable_show(const enum tpacpi_rfk_id id,
1310                                             struct device_attribute *attr,
1311                                             char *buf)
1312 {
1313         int status;
1314
1315         printk_deprecated_rfkill_attribute(attr->attr.name);
1316
1317         /* This is in the ABI... */
1318         if (tpacpi_rfk_check_hwblock_state()) {
1319                 status = TPACPI_RFK_RADIO_OFF;
1320         } else {
1321                 status = tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[id]);
1322                 if (status < 0)
1323                         return status;
1324         }
1325
1326         return snprintf(buf, PAGE_SIZE, "%d\n",
1327                         (status == TPACPI_RFK_RADIO_ON) ? 1 : 0);
1328 }
1329
1330 static ssize_t tpacpi_rfk_sysfs_enable_store(const enum tpacpi_rfk_id id,
1331                             struct device_attribute *attr,
1332                             const char *buf, size_t count)
1333 {
1334         unsigned long t;
1335         int res;
1336
1337         printk_deprecated_rfkill_attribute(attr->attr.name);
1338
1339         if (parse_strtoul(buf, 1, &t))
1340                 return -EINVAL;
1341
1342         tpacpi_disclose_usertask(attr->attr.name, "set to %ld\n", t);
1343
1344         /* This is in the ABI... */
1345         if (tpacpi_rfk_check_hwblock_state() && !!t)
1346                 return -EPERM;
1347
1348         res = tpacpi_rfkill_switches[id]->ops->set_status((!!t) ?
1349                                 TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF);
1350         tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[id]);
1351
1352         return (res < 0) ? res : count;
1353 }
1354
1355 /* procfs -------------------------------------------------------------- */
1356 static int tpacpi_rfk_procfs_read(const enum tpacpi_rfk_id id, char *p)
1357 {
1358         int len = 0;
1359
1360         if (id >= TPACPI_RFK_SW_MAX)
1361                 len += sprintf(p + len, "status:\t\tnot supported\n");
1362         else {
1363                 int status;
1364
1365                 /* This is in the ABI... */
1366                 if (tpacpi_rfk_check_hwblock_state()) {
1367                         status = TPACPI_RFK_RADIO_OFF;
1368                 } else {
1369                         status = tpacpi_rfk_update_swstate(
1370                                                 tpacpi_rfkill_switches[id]);
1371                         if (status < 0)
1372                                 return status;
1373                 }
1374
1375                 len += sprintf(p + len, "status:\t\t%s\n",
1376                                 (status == TPACPI_RFK_RADIO_ON) ?
1377                                         "enabled" : "disabled");
1378                 len += sprintf(p + len, "commands:\tenable, disable\n");
1379         }
1380
1381         return len;
1382 }
1383
1384 static int tpacpi_rfk_procfs_write(const enum tpacpi_rfk_id id, char *buf)
1385 {
1386         char *cmd;
1387         int status = -1;
1388         int res = 0;
1389
1390         if (id >= TPACPI_RFK_SW_MAX)
1391                 return -ENODEV;
1392
1393         while ((cmd = next_cmd(&buf))) {
1394                 if (strlencmp(cmd, "enable") == 0)
1395                         status = TPACPI_RFK_RADIO_ON;
1396                 else if (strlencmp(cmd, "disable") == 0)
1397                         status = TPACPI_RFK_RADIO_OFF;
1398                 else
1399                         return -EINVAL;
1400         }
1401
1402         if (status != -1) {
1403                 tpacpi_disclose_usertask("procfs", "attempt to %s %s\n",
1404                                 (status == TPACPI_RFK_RADIO_ON) ?
1405                                                 "enable" : "disable",
1406                                 tpacpi_rfkill_names[id]);
1407                 res = (tpacpi_rfkill_switches[id]->ops->set_status)(status);
1408                 tpacpi_rfk_update_swstate(tpacpi_rfkill_switches[id]);
1409         }
1410
1411         return res;
1412 }
1413
1414 /*************************************************************************
1415  * thinkpad-acpi driver attributes
1416  */
1417
1418 /* interface_version --------------------------------------------------- */
1419 static ssize_t tpacpi_driver_interface_version_show(
1420                                 struct device_driver *drv,
1421                                 char *buf)
1422 {
1423         return snprintf(buf, PAGE_SIZE, "0x%08x\n", TPACPI_SYSFS_VERSION);
1424 }
1425
1426 static DRIVER_ATTR(interface_version, S_IRUGO,
1427                 tpacpi_driver_interface_version_show, NULL);
1428
1429 /* debug_level --------------------------------------------------------- */
1430 static ssize_t tpacpi_driver_debug_show(struct device_driver *drv,
1431                                                 char *buf)
1432 {
1433         return snprintf(buf, PAGE_SIZE, "0x%04x\n", dbg_level);
1434 }
1435
1436 static ssize_t tpacpi_driver_debug_store(struct device_driver *drv,
1437                                                 const char *buf, size_t count)
1438 {
1439         unsigned long t;
1440
1441         if (parse_strtoul(buf, 0xffff, &t))
1442                 return -EINVAL;
1443
1444         dbg_level = t;
1445
1446         return count;
1447 }
1448
1449 static DRIVER_ATTR(debug_level, S_IWUSR | S_IRUGO,
1450                 tpacpi_driver_debug_show, tpacpi_driver_debug_store);
1451
1452 /* version ------------------------------------------------------------- */
1453 static ssize_t tpacpi_driver_version_show(struct device_driver *drv,
1454                                                 char *buf)
1455 {
1456         return snprintf(buf, PAGE_SIZE, "%s v%s\n",
1457                         TPACPI_DESC, TPACPI_VERSION);
1458 }
1459
1460 static DRIVER_ATTR(version, S_IRUGO,
1461                 tpacpi_driver_version_show, NULL);
1462
1463 /* --------------------------------------------------------------------- */
1464
1465 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
1466
1467 /* wlsw_emulstate ------------------------------------------------------ */
1468 static ssize_t tpacpi_driver_wlsw_emulstate_show(struct device_driver *drv,
1469                                                 char *buf)
1470 {
1471         return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_wlsw_emulstate);
1472 }
1473
1474 static ssize_t tpacpi_driver_wlsw_emulstate_store(struct device_driver *drv,
1475                                                 const char *buf, size_t count)
1476 {
1477         unsigned long t;
1478
1479         if (parse_strtoul(buf, 1, &t))
1480                 return -EINVAL;
1481
1482         if (tpacpi_wlsw_emulstate != !!t) {
1483                 tpacpi_wlsw_emulstate = !!t;
1484                 tpacpi_rfk_update_hwblock_state(!t);    /* negative logic */
1485         }
1486
1487         return count;
1488 }
1489
1490 static DRIVER_ATTR(wlsw_emulstate, S_IWUSR | S_IRUGO,
1491                 tpacpi_driver_wlsw_emulstate_show,
1492                 tpacpi_driver_wlsw_emulstate_store);
1493
1494 /* bluetooth_emulstate ------------------------------------------------- */
1495 static ssize_t tpacpi_driver_bluetooth_emulstate_show(
1496                                         struct device_driver *drv,
1497                                         char *buf)
1498 {
1499         return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_bluetooth_emulstate);
1500 }
1501
1502 static ssize_t tpacpi_driver_bluetooth_emulstate_store(
1503                                         struct device_driver *drv,
1504                                         const char *buf, size_t count)
1505 {
1506         unsigned long t;
1507
1508         if (parse_strtoul(buf, 1, &t))
1509                 return -EINVAL;
1510
1511         tpacpi_bluetooth_emulstate = !!t;
1512
1513         return count;
1514 }
1515
1516 static DRIVER_ATTR(bluetooth_emulstate, S_IWUSR | S_IRUGO,
1517                 tpacpi_driver_bluetooth_emulstate_show,
1518                 tpacpi_driver_bluetooth_emulstate_store);
1519
1520 /* wwan_emulstate ------------------------------------------------- */
1521 static ssize_t tpacpi_driver_wwan_emulstate_show(
1522                                         struct device_driver *drv,
1523                                         char *buf)
1524 {
1525         return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_wwan_emulstate);
1526 }
1527
1528 static ssize_t tpacpi_driver_wwan_emulstate_store(
1529                                         struct device_driver *drv,
1530                                         const char *buf, size_t count)
1531 {
1532         unsigned long t;
1533
1534         if (parse_strtoul(buf, 1, &t))
1535                 return -EINVAL;
1536
1537         tpacpi_wwan_emulstate = !!t;
1538
1539         return count;
1540 }
1541
1542 static DRIVER_ATTR(wwan_emulstate, S_IWUSR | S_IRUGO,
1543                 tpacpi_driver_wwan_emulstate_show,
1544                 tpacpi_driver_wwan_emulstate_store);
1545
1546 /* uwb_emulstate ------------------------------------------------- */
1547 static ssize_t tpacpi_driver_uwb_emulstate_show(
1548                                         struct device_driver *drv,
1549                                         char *buf)
1550 {
1551         return snprintf(buf, PAGE_SIZE, "%d\n", !!tpacpi_uwb_emulstate);
1552 }
1553
1554 static ssize_t tpacpi_driver_uwb_emulstate_store(
1555                                         struct device_driver *drv,
1556                                         const char *buf, size_t count)
1557 {
1558         unsigned long t;
1559
1560         if (parse_strtoul(buf, 1, &t))
1561                 return -EINVAL;
1562
1563         tpacpi_uwb_emulstate = !!t;
1564
1565         return count;
1566 }
1567
1568 static DRIVER_ATTR(uwb_emulstate, S_IWUSR | S_IRUGO,
1569                 tpacpi_driver_uwb_emulstate_show,
1570                 tpacpi_driver_uwb_emulstate_store);
1571 #endif
1572
1573 /* --------------------------------------------------------------------- */
1574
1575 static struct driver_attribute *tpacpi_driver_attributes[] = {
1576         &driver_attr_debug_level, &driver_attr_version,
1577         &driver_attr_interface_version,
1578 };
1579
1580 static int __init tpacpi_create_driver_attributes(struct device_driver *drv)
1581 {
1582         int i, res;
1583
1584         i = 0;
1585         res = 0;
1586         while (!res && i < ARRAY_SIZE(tpacpi_driver_attributes)) {
1587                 res = driver_create_file(drv, tpacpi_driver_attributes[i]);
1588                 i++;
1589         }
1590
1591 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
1592         if (!res && dbg_wlswemul)
1593                 res = driver_create_file(drv, &driver_attr_wlsw_emulstate);
1594         if (!res && dbg_bluetoothemul)
1595                 res = driver_create_file(drv, &driver_attr_bluetooth_emulstate);
1596         if (!res && dbg_wwanemul)
1597                 res = driver_create_file(drv, &driver_attr_wwan_emulstate);
1598         if (!res && dbg_uwbemul)
1599                 res = driver_create_file(drv, &driver_attr_uwb_emulstate);
1600 #endif
1601
1602         return res;
1603 }
1604
1605 static void tpacpi_remove_driver_attributes(struct device_driver *drv)
1606 {
1607         int i;
1608
1609         for (i = 0; i < ARRAY_SIZE(tpacpi_driver_attributes); i++)
1610                 driver_remove_file(drv, tpacpi_driver_attributes[i]);
1611
1612 #ifdef THINKPAD_ACPI_DEBUGFACILITIES
1613         driver_remove_file(drv, &driver_attr_wlsw_emulstate);
1614         driver_remove_file(drv, &driver_attr_bluetooth_emulstate);
1615         driver_remove_file(drv, &driver_attr_wwan_emulstate);
1616         driver_remove_file(drv, &driver_attr_uwb_emulstate);
1617 #endif
1618 }
1619
1620 /****************************************************************************
1621  ****************************************************************************
1622  *
1623  * Subdrivers
1624  *
1625  ****************************************************************************
1626  ****************************************************************************/
1627
1628 /*************************************************************************
1629  * thinkpad-acpi init subdriver
1630  */
1631
1632 static int __init thinkpad_acpi_driver_init(struct ibm_init_struct *iibm)
1633 {
1634         printk(TPACPI_INFO "%s v%s\n", TPACPI_DESC, TPACPI_VERSION);
1635         printk(TPACPI_INFO "%s\n", TPACPI_URL);
1636
1637         printk(TPACPI_INFO "ThinkPad BIOS %s, EC %s\n",
1638                 (thinkpad_id.bios_version_str) ?
1639                         thinkpad_id.bios_version_str : "unknown",
1640                 (thinkpad_id.ec_version_str) ?
1641                         thinkpad_id.ec_version_str : "unknown");
1642
1643         if (thinkpad_id.vendor && thinkpad_id.model_str)
1644                 printk(TPACPI_INFO "%s %s, model %s\n",
1645                         (thinkpad_id.vendor == PCI_VENDOR_ID_IBM) ?
1646                                 "IBM" : ((thinkpad_id.vendor ==
1647                                                 PCI_VENDOR_ID_LENOVO) ?
1648                                         "Lenovo" : "Unknown vendor"),
1649                         thinkpad_id.model_str,
1650                         (thinkpad_id.nummodel_str) ?
1651                                 thinkpad_id.nummodel_str : "unknown");
1652
1653         return 0;
1654 }
1655
1656 static int thinkpad_acpi_driver_read(char *p)
1657 {
1658         int len = 0;
1659
1660         len += sprintf(p + len, "driver:\t\t%s\n", TPACPI_DESC);
1661         len += sprintf(p + len, "version:\t%s\n", TPACPI_VERSION);
1662
1663         return len;
1664 }
1665
1666 static struct ibm_struct thinkpad_acpi_driver_data = {
1667         .name = "driver",
1668         .read = thinkpad_acpi_driver_read,
1669 };
1670
1671 /*************************************************************************
1672  * Hotkey subdriver
1673  */
1674
1675 enum {  /* hot key scan codes (derived from ACPI DSDT) */
1676         TP_ACPI_HOTKEYSCAN_FNF1         = 0,
1677         TP_ACPI_HOTKEYSCAN_FNF2,
1678         TP_ACPI_HOTKEYSCAN_FNF3,
1679         TP_ACPI_HOTKEYSCAN_FNF4,
1680         TP_ACPI_HOTKEYSCAN_FNF5,
1681         TP_ACPI_HOTKEYSCAN_FNF6,
1682         TP_ACPI_HOTKEYSCAN_FNF7,
1683         TP_ACPI_HOTKEYSCAN_FNF8,
1684         TP_ACPI_HOTKEYSCAN_FNF9,
1685         TP_ACPI_HOTKEYSCAN_FNF10,
1686         TP_ACPI_HOTKEYSCAN_FNF11,
1687         TP_ACPI_HOTKEYSCAN_FNF12,
1688         TP_ACPI_HOTKEYSCAN_FNBACKSPACE,
1689         TP_ACPI_HOTKEYSCAN_FNINSERT,
1690         TP_ACPI_HOTKEYSCAN_FNDELETE,
1691         TP_ACPI_HOTKEYSCAN_FNHOME,
1692         TP_ACPI_HOTKEYSCAN_FNEND,
1693         TP_ACPI_HOTKEYSCAN_FNPAGEUP,
1694         TP_ACPI_HOTKEYSCAN_FNPAGEDOWN,
1695         TP_ACPI_HOTKEYSCAN_FNSPACE,
1696         TP_ACPI_HOTKEYSCAN_VOLUMEUP,
1697         TP_ACPI_HOTKEYSCAN_VOLUMEDOWN,
1698         TP_ACPI_HOTKEYSCAN_MUTE,
1699         TP_ACPI_HOTKEYSCAN_THINKPAD,
1700 };
1701
1702 enum {  /* Keys available through NVRAM polling */
1703         TPACPI_HKEY_NVRAM_KNOWN_MASK = 0x00fb88c0U,
1704         TPACPI_HKEY_NVRAM_GOOD_MASK  = 0x00fb8000U,
1705 };
1706
1707 enum {  /* Positions of some of the keys in hotkey masks */
1708         TP_ACPI_HKEY_DISPSWTCH_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF7,
1709         TP_ACPI_HKEY_DISPXPAND_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF8,
1710         TP_ACPI_HKEY_HIBERNATE_MASK     = 1 << TP_ACPI_HOTKEYSCAN_FNF12,
1711         TP_ACPI_HKEY_BRGHTUP_MASK       = 1 << TP_ACPI_HOTKEYSCAN_FNHOME,
1712         TP_ACPI_HKEY_BRGHTDWN_MASK      = 1 << TP_ACPI_HOTKEYSCAN_FNEND,
1713         TP_ACPI_HKEY_THNKLGHT_MASK      = 1 << TP_ACPI_HOTKEYSCAN_FNPAGEUP,
1714         TP_ACPI_HKEY_ZOOM_MASK          = 1 << TP_ACPI_HOTKEYSCAN_FNSPACE,
1715         TP_ACPI_HKEY_VOLUP_MASK         = 1 << TP_ACPI_HOTKEYSCAN_VOLUMEUP,
1716         TP_ACPI_HKEY_VOLDWN_MASK        = 1 << TP_ACPI_HOTKEYSCAN_VOLUMEDOWN,
1717         TP_ACPI_HKEY_MUTE_MASK          = 1 << TP_ACPI_HOTKEYSCAN_MUTE,
1718         TP_ACPI_HKEY_THINKPAD_MASK      = 1 << TP_ACPI_HOTKEYSCAN_THINKPAD,
1719 };
1720
1721 enum {  /* NVRAM to ACPI HKEY group map */
1722         TP_NVRAM_HKEY_GROUP_HK2         = TP_ACPI_HKEY_THINKPAD_MASK |
1723                                           TP_ACPI_HKEY_ZOOM_MASK |
1724                                           TP_ACPI_HKEY_DISPSWTCH_MASK |
1725                                           TP_ACPI_HKEY_HIBERNATE_MASK,
1726         TP_NVRAM_HKEY_GROUP_BRIGHTNESS  = TP_ACPI_HKEY_BRGHTUP_MASK |
1727                                           TP_ACPI_HKEY_BRGHTDWN_MASK,
1728         TP_NVRAM_HKEY_GROUP_VOLUME      = TP_ACPI_HKEY_VOLUP_MASK |
1729                                           TP_ACPI_HKEY_VOLDWN_MASK |
1730                                           TP_ACPI_HKEY_MUTE_MASK,
1731 };
1732
1733 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1734 struct tp_nvram_state {
1735        u16 thinkpad_toggle:1;
1736        u16 zoom_toggle:1;
1737        u16 display_toggle:1;
1738        u16 thinklight_toggle:1;
1739        u16 hibernate_toggle:1;
1740        u16 displayexp_toggle:1;
1741        u16 display_state:1;
1742        u16 brightness_toggle:1;
1743        u16 volume_toggle:1;
1744        u16 mute:1;
1745
1746        u8 brightness_level;
1747        u8 volume_level;
1748 };
1749
1750 static struct task_struct *tpacpi_hotkey_task;
1751 static u32 hotkey_source_mask;          /* bit mask 0=ACPI,1=NVRAM */
1752 static int hotkey_poll_freq = 10;       /* Hz */
1753 static struct mutex hotkey_thread_mutex;
1754 static struct mutex hotkey_thread_data_mutex;
1755 static unsigned int hotkey_config_change;
1756
1757 #else /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
1758
1759 #define hotkey_source_mask 0U
1760
1761 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
1762
1763 static struct mutex hotkey_mutex;
1764
1765 static enum {   /* Reasons for waking up */
1766         TP_ACPI_WAKEUP_NONE = 0,        /* None or unknown */
1767         TP_ACPI_WAKEUP_BAYEJ,           /* Bay ejection request */
1768         TP_ACPI_WAKEUP_UNDOCK,          /* Undock request */
1769 } hotkey_wakeup_reason;
1770
1771 static int hotkey_autosleep_ack;
1772
1773 static u32 hotkey_orig_mask;
1774 static u32 hotkey_all_mask;
1775 static u32 hotkey_reserved_mask;
1776 static u32 hotkey_mask;
1777
1778 static unsigned int hotkey_report_mode;
1779
1780 static u16 *hotkey_keycode_map;
1781
1782 static struct attribute_set *hotkey_dev_attributes;
1783
1784 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1785 #define HOTKEY_CONFIG_CRITICAL_START \
1786         do { \
1787                 mutex_lock(&hotkey_thread_data_mutex); \
1788                 hotkey_config_change++; \
1789         } while (0);
1790 #define HOTKEY_CONFIG_CRITICAL_END \
1791         mutex_unlock(&hotkey_thread_data_mutex);
1792 #else
1793 #define HOTKEY_CONFIG_CRITICAL_START
1794 #define HOTKEY_CONFIG_CRITICAL_END
1795 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
1796
1797 /* HKEY.MHKG() return bits */
1798 #define TP_HOTKEY_TABLET_MASK (1 << 3)
1799
1800 static int hotkey_get_wlsw(void)
1801 {
1802         int status;
1803
1804         if (!tp_features.hotkey_wlsw)
1805                 return -ENODEV;
1806
1807 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
1808         if (dbg_wlswemul)
1809                 return (tpacpi_wlsw_emulstate) ?
1810                                 TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
1811 #endif
1812
1813         if (!acpi_evalf(hkey_handle, &status, "WLSW", "d"))
1814                 return -EIO;
1815
1816         return (status) ? TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
1817 }
1818
1819 static int hotkey_get_tablet_mode(int *status)
1820 {
1821         int s;
1822
1823         if (!acpi_evalf(hkey_handle, &s, "MHKG", "d"))
1824                 return -EIO;
1825
1826         *status = ((s & TP_HOTKEY_TABLET_MASK) != 0);
1827         return 0;
1828 }
1829
1830 /*
1831  * Call with hotkey_mutex held
1832  */
1833 static int hotkey_mask_get(void)
1834 {
1835         u32 m = 0;
1836
1837         if (tp_features.hotkey_mask) {
1838                 if (!acpi_evalf(hkey_handle, &m, "DHKN", "d"))
1839                         return -EIO;
1840         }
1841         hotkey_mask = m | (hotkey_source_mask & hotkey_mask);
1842
1843         return 0;
1844 }
1845
1846 /*
1847  * Call with hotkey_mutex held
1848  */
1849 static int hotkey_mask_set(u32 mask)
1850 {
1851         int i;
1852         int rc = 0;
1853
1854         if (tp_features.hotkey_mask) {
1855                 if (!tp_warned.hotkey_mask_ff &&
1856                     (mask == 0xffff || mask == 0xffffff ||
1857                      mask == 0xffffffff)) {
1858                         tp_warned.hotkey_mask_ff = 1;
1859                         printk(TPACPI_NOTICE
1860                                "setting the hotkey mask to 0x%08x is likely "
1861                                "not the best way to go about it\n", mask);
1862                         printk(TPACPI_NOTICE
1863                                "please consider using the driver defaults, "
1864                                "and refer to up-to-date thinkpad-acpi "
1865                                "documentation\n");
1866                 }
1867
1868                 HOTKEY_CONFIG_CRITICAL_START
1869                 for (i = 0; i < 32; i++) {
1870                         u32 m = 1 << i;
1871                         /* enable in firmware mask only keys not in NVRAM
1872                          * mode, but enable the key in the cached hotkey_mask
1873                          * regardless of mode, or the key will end up
1874                          * disabled by hotkey_mask_get() */
1875                         if (!acpi_evalf(hkey_handle,
1876                                         NULL, "MHKM", "vdd", i + 1,
1877                                         !!((mask & ~hotkey_source_mask) & m))) {
1878                                 rc = -EIO;
1879                                 break;
1880                         } else {
1881                                 hotkey_mask = (hotkey_mask & ~m) | (mask & m);
1882                         }
1883                 }
1884                 HOTKEY_CONFIG_CRITICAL_END
1885
1886                 /* hotkey_mask_get must be called unconditionally below */
1887                 if (!hotkey_mask_get() && !rc &&
1888                     (hotkey_mask & ~hotkey_source_mask) !=
1889                      (mask & ~hotkey_source_mask)) {
1890                         printk(TPACPI_NOTICE
1891                                "requested hot key mask 0x%08x, but "
1892                                "firmware forced it to 0x%08x\n",
1893                                mask, hotkey_mask);
1894                 }
1895         } else {
1896 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1897                 HOTKEY_CONFIG_CRITICAL_START
1898                 hotkey_mask = mask & hotkey_source_mask;
1899                 HOTKEY_CONFIG_CRITICAL_END
1900                 hotkey_mask_get();
1901                 if (hotkey_mask != mask) {
1902                         printk(TPACPI_NOTICE
1903                                "requested hot key mask 0x%08x, "
1904                                "forced to 0x%08x (NVRAM poll mask is "
1905                                "0x%08x): no firmware mask support\n",
1906                                mask, hotkey_mask, hotkey_source_mask);
1907                 }
1908 #else
1909                 hotkey_mask_get();
1910                 rc = -ENXIO;
1911 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
1912         }
1913
1914         return rc;
1915 }
1916
1917 static int hotkey_status_get(int *status)
1918 {
1919         if (!acpi_evalf(hkey_handle, status, "DHKC", "d"))
1920                 return -EIO;
1921
1922         return 0;
1923 }
1924
1925 static int hotkey_status_set(bool enable)
1926 {
1927         if (!acpi_evalf(hkey_handle, NULL, "MHKC", "vd", enable ? 1 : 0))
1928                 return -EIO;
1929
1930         return 0;
1931 }
1932
1933 static void tpacpi_input_send_tabletsw(void)
1934 {
1935         int state;
1936
1937         if (tp_features.hotkey_tablet &&
1938             !hotkey_get_tablet_mode(&state)) {
1939                 mutex_lock(&tpacpi_inputdev_send_mutex);
1940
1941                 input_report_switch(tpacpi_inputdev,
1942                                     SW_TABLET_MODE, !!state);
1943                 input_sync(tpacpi_inputdev);
1944
1945                 mutex_unlock(&tpacpi_inputdev_send_mutex);
1946         }
1947 }
1948
1949 static void tpacpi_input_send_key(unsigned int scancode)
1950 {
1951         unsigned int keycode;
1952
1953         keycode = hotkey_keycode_map[scancode];
1954
1955         if (keycode != KEY_RESERVED) {
1956                 mutex_lock(&tpacpi_inputdev_send_mutex);
1957
1958                 input_report_key(tpacpi_inputdev, keycode, 1);
1959                 if (keycode == KEY_UNKNOWN)
1960                         input_event(tpacpi_inputdev, EV_MSC, MSC_SCAN,
1961                                     scancode);
1962                 input_sync(tpacpi_inputdev);
1963
1964                 input_report_key(tpacpi_inputdev, keycode, 0);
1965                 if (keycode == KEY_UNKNOWN)
1966                         input_event(tpacpi_inputdev, EV_MSC, MSC_SCAN,
1967                                     scancode);
1968                 input_sync(tpacpi_inputdev);
1969
1970                 mutex_unlock(&tpacpi_inputdev_send_mutex);
1971         }
1972 }
1973
1974 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
1975 static struct tp_acpi_drv_struct ibm_hotkey_acpidriver;
1976
1977 static void tpacpi_hotkey_send_key(unsigned int scancode)
1978 {
1979         tpacpi_input_send_key(scancode);
1980         if (hotkey_report_mode < 2) {
1981                 acpi_bus_generate_proc_event(ibm_hotkey_acpidriver.device,
1982                                                 0x80, 0x1001 + scancode);
1983         }
1984 }
1985
1986 static void hotkey_read_nvram(struct tp_nvram_state *n, u32 m)
1987 {
1988         u8 d;
1989
1990         if (m & TP_NVRAM_HKEY_GROUP_HK2) {
1991                 d = nvram_read_byte(TP_NVRAM_ADDR_HK2);
1992                 n->thinkpad_toggle = !!(d & TP_NVRAM_MASK_HKT_THINKPAD);
1993                 n->zoom_toggle = !!(d & TP_NVRAM_MASK_HKT_ZOOM);
1994                 n->display_toggle = !!(d & TP_NVRAM_MASK_HKT_DISPLAY);
1995                 n->hibernate_toggle = !!(d & TP_NVRAM_MASK_HKT_HIBERNATE);
1996         }
1997         if (m & TP_ACPI_HKEY_THNKLGHT_MASK) {
1998                 d = nvram_read_byte(TP_NVRAM_ADDR_THINKLIGHT);
1999                 n->thinklight_toggle = !!(d & TP_NVRAM_MASK_THINKLIGHT);
2000         }
2001         if (m & TP_ACPI_HKEY_DISPXPAND_MASK) {
2002                 d = nvram_read_byte(TP_NVRAM_ADDR_VIDEO);
2003                 n->displayexp_toggle =
2004                                 !!(d & TP_NVRAM_MASK_HKT_DISPEXPND);
2005         }
2006         if (m & TP_NVRAM_HKEY_GROUP_BRIGHTNESS) {
2007                 d = nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS);
2008                 n->brightness_level = (d & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
2009                                 >> TP_NVRAM_POS_LEVEL_BRIGHTNESS;
2010                 n->brightness_toggle =
2011                                 !!(d & TP_NVRAM_MASK_HKT_BRIGHTNESS);
2012         }
2013         if (m & TP_NVRAM_HKEY_GROUP_VOLUME) {
2014                 d = nvram_read_byte(TP_NVRAM_ADDR_MIXER);
2015                 n->volume_level = (d & TP_NVRAM_MASK_LEVEL_VOLUME)
2016                                 >> TP_NVRAM_POS_LEVEL_VOLUME;
2017                 n->mute = !!(d & TP_NVRAM_MASK_MUTE);
2018                 n->volume_toggle = !!(d & TP_NVRAM_MASK_HKT_VOLUME);
2019         }
2020 }
2021
2022 #define TPACPI_COMPARE_KEY(__scancode, __member) \
2023         do { \
2024                 if ((mask & (1 << __scancode)) && \
2025                     oldn->__member != newn->__member) \
2026                 tpacpi_hotkey_send_key(__scancode); \
2027         } while (0)
2028
2029 #define TPACPI_MAY_SEND_KEY(__scancode) \
2030         do { if (mask & (1 << __scancode)) \
2031                 tpacpi_hotkey_send_key(__scancode); } while (0)
2032
2033 static void hotkey_compare_and_issue_event(struct tp_nvram_state *oldn,
2034                                            struct tp_nvram_state *newn,
2035                                            u32 mask)
2036 {
2037         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_THINKPAD, thinkpad_toggle);
2038         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNSPACE, zoom_toggle);
2039         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF7, display_toggle);
2040         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF12, hibernate_toggle);
2041
2042         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNPAGEUP, thinklight_toggle);
2043
2044         TPACPI_COMPARE_KEY(TP_ACPI_HOTKEYSCAN_FNF8, displayexp_toggle);
2045
2046         /* handle volume */
2047         if (oldn->volume_toggle != newn->volume_toggle) {
2048                 if (oldn->mute != newn->mute) {
2049                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_MUTE);
2050                 }
2051                 if (oldn->volume_level > newn->volume_level) {
2052                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEDOWN);
2053                 } else if (oldn->volume_level < newn->volume_level) {
2054                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP);
2055                 } else if (oldn->mute == newn->mute) {
2056                         /* repeated key presses that didn't change state */
2057                         if (newn->mute) {
2058                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_MUTE);
2059                         } else if (newn->volume_level != 0) {
2060                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEUP);
2061                         } else {
2062                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_VOLUMEDOWN);
2063                         }
2064                 }
2065         }
2066
2067         /* handle brightness */
2068         if (oldn->brightness_toggle != newn->brightness_toggle) {
2069                 if (oldn->brightness_level < newn->brightness_level) {
2070                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNHOME);
2071                 } else if (oldn->brightness_level > newn->brightness_level) {
2072                         TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNEND);
2073                 } else {
2074                         /* repeated key presses that didn't change state */
2075                         if (newn->brightness_level != 0) {
2076                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNHOME);
2077                         } else {
2078                                 TPACPI_MAY_SEND_KEY(TP_ACPI_HOTKEYSCAN_FNEND);
2079                         }
2080                 }
2081         }
2082 }
2083
2084 #undef TPACPI_COMPARE_KEY
2085 #undef TPACPI_MAY_SEND_KEY
2086
2087 static int hotkey_kthread(void *data)
2088 {
2089         struct tp_nvram_state s[2];
2090         u32 mask;
2091         unsigned int si, so;
2092         unsigned long t;
2093         unsigned int change_detector, must_reset;
2094
2095         mutex_lock(&hotkey_thread_mutex);
2096
2097         if (tpacpi_lifecycle == TPACPI_LIFE_EXITING)
2098                 goto exit;
2099
2100         set_freezable();
2101
2102         so = 0;
2103         si = 1;
2104         t = 0;
2105
2106         /* Initial state for compares */
2107         mutex_lock(&hotkey_thread_data_mutex);
2108         change_detector = hotkey_config_change;
2109         mask = hotkey_source_mask & hotkey_mask;
2110         mutex_unlock(&hotkey_thread_data_mutex);
2111         hotkey_read_nvram(&s[so], mask);
2112
2113         while (!kthread_should_stop() && hotkey_poll_freq) {
2114                 if (t == 0)
2115                         t = 1000/hotkey_poll_freq;
2116                 t = msleep_interruptible(t);
2117                 if (unlikely(kthread_should_stop()))
2118                         break;
2119                 must_reset = try_to_freeze();
2120                 if (t > 0 && !must_reset)
2121                         continue;
2122
2123                 mutex_lock(&hotkey_thread_data_mutex);
2124                 if (must_reset || hotkey_config_change != change_detector) {
2125                         /* forget old state on thaw or config change */
2126                         si = so;
2127                         t = 0;
2128                         change_detector = hotkey_config_change;
2129                 }
2130                 mask = hotkey_source_mask & hotkey_mask;
2131                 mutex_unlock(&hotkey_thread_data_mutex);
2132
2133                 if (likely(mask)) {
2134                         hotkey_read_nvram(&s[si], mask);
2135                         if (likely(si != so)) {
2136                                 hotkey_compare_and_issue_event(&s[so], &s[si],
2137                                                                 mask);
2138                         }
2139                 }
2140
2141                 so = si;
2142                 si ^= 1;
2143         }
2144
2145 exit:
2146         mutex_unlock(&hotkey_thread_mutex);
2147         return 0;
2148 }
2149
2150 static void hotkey_poll_stop_sync(void)
2151 {
2152         if (tpacpi_hotkey_task) {
2153                 if (frozen(tpacpi_hotkey_task) ||
2154                     freezing(tpacpi_hotkey_task))
2155                         thaw_process(tpacpi_hotkey_task);
2156
2157                 kthread_stop(tpacpi_hotkey_task);
2158                 tpacpi_hotkey_task = NULL;
2159                 mutex_lock(&hotkey_thread_mutex);
2160                 /* at this point, the thread did exit */
2161                 mutex_unlock(&hotkey_thread_mutex);
2162         }
2163 }
2164
2165 /* call with hotkey_mutex held */
2166 static void hotkey_poll_setup(int may_warn)
2167 {
2168         if ((hotkey_source_mask & hotkey_mask) != 0 &&
2169             hotkey_poll_freq > 0 &&
2170             (tpacpi_inputdev->users > 0 || hotkey_report_mode < 2)) {
2171                 if (!tpacpi_hotkey_task) {
2172                         tpacpi_hotkey_task = kthread_run(hotkey_kthread,
2173                                         NULL, TPACPI_NVRAM_KTHREAD_NAME);
2174                         if (IS_ERR(tpacpi_hotkey_task)) {
2175                                 tpacpi_hotkey_task = NULL;
2176                                 printk(TPACPI_ERR
2177                                        "could not create kernel thread "
2178                                        "for hotkey polling\n");
2179                         }
2180                 }
2181         } else {
2182                 hotkey_poll_stop_sync();
2183                 if (may_warn &&
2184                     hotkey_source_mask != 0 && hotkey_poll_freq == 0) {
2185                         printk(TPACPI_NOTICE
2186                                 "hot keys 0x%08x require polling, "
2187                                 "which is currently disabled\n",
2188                                 hotkey_source_mask);
2189                 }
2190         }
2191 }
2192
2193 static void hotkey_poll_setup_safe(int may_warn)
2194 {
2195         mutex_lock(&hotkey_mutex);
2196         hotkey_poll_setup(may_warn);
2197         mutex_unlock(&hotkey_mutex);
2198 }
2199
2200 #else /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2201
2202 static void hotkey_poll_setup_safe(int __unused)
2203 {
2204 }
2205
2206 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2207
2208 static int hotkey_inputdev_open(struct input_dev *dev)
2209 {
2210         switch (tpacpi_lifecycle) {
2211         case TPACPI_LIFE_INIT:
2212                 /*
2213                  * hotkey_init will call hotkey_poll_setup_safe
2214                  * at the appropriate moment
2215                  */
2216                 return 0;
2217         case TPACPI_LIFE_EXITING:
2218                 return -EBUSY;
2219         case TPACPI_LIFE_RUNNING:
2220                 hotkey_poll_setup_safe(0);
2221                 return 0;
2222         }
2223
2224         /* Should only happen if tpacpi_lifecycle is corrupt */
2225         BUG();
2226         return -EBUSY;
2227 }
2228
2229 static void hotkey_inputdev_close(struct input_dev *dev)
2230 {
2231         /* disable hotkey polling when possible */
2232         if (tpacpi_lifecycle == TPACPI_LIFE_RUNNING)
2233                 hotkey_poll_setup_safe(0);
2234 }
2235
2236 /* sysfs hotkey enable ------------------------------------------------- */
2237 static ssize_t hotkey_enable_show(struct device *dev,
2238                            struct device_attribute *attr,
2239                            char *buf)
2240 {
2241         int res, status;
2242
2243         printk_deprecated_attribute("hotkey_enable",
2244                         "Hotkey reporting is always enabled");
2245
2246         res = hotkey_status_get(&status);
2247         if (res)
2248                 return res;
2249
2250         return snprintf(buf, PAGE_SIZE, "%d\n", status);
2251 }
2252
2253 static ssize_t hotkey_enable_store(struct device *dev,
2254                             struct device_attribute *attr,
2255                             const char *buf, size_t count)
2256 {
2257         unsigned long t;
2258
2259         printk_deprecated_attribute("hotkey_enable",
2260                         "Hotkeys can be disabled through hotkey_mask");
2261
2262         if (parse_strtoul(buf, 1, &t))
2263                 return -EINVAL;
2264
2265         if (t == 0)
2266                 return -EPERM;
2267
2268         return count;
2269 }
2270
2271 static struct device_attribute dev_attr_hotkey_enable =
2272         __ATTR(hotkey_enable, S_IWUSR | S_IRUGO,
2273                 hotkey_enable_show, hotkey_enable_store);
2274
2275 /* sysfs hotkey mask --------------------------------------------------- */
2276 static ssize_t hotkey_mask_show(struct device *dev,
2277                            struct device_attribute *attr,
2278                            char *buf)
2279 {
2280         int res;
2281
2282         if (mutex_lock_killable(&hotkey_mutex))
2283                 return -ERESTARTSYS;
2284         res = hotkey_mask_get();
2285         mutex_unlock(&hotkey_mutex);
2286
2287         return (res)?
2288                 res : snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_mask);
2289 }
2290
2291 static ssize_t hotkey_mask_store(struct device *dev,
2292                             struct device_attribute *attr,
2293                             const char *buf, size_t count)
2294 {
2295         unsigned long t;
2296         int res;
2297
2298         if (parse_strtoul(buf, 0xffffffffUL, &t))
2299                 return -EINVAL;
2300
2301         if (mutex_lock_killable(&hotkey_mutex))
2302                 return -ERESTARTSYS;
2303
2304         res = hotkey_mask_set(t);
2305
2306 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2307         hotkey_poll_setup(1);
2308 #endif
2309
2310         mutex_unlock(&hotkey_mutex);
2311
2312         tpacpi_disclose_usertask("hotkey_mask", "set to 0x%08lx\n", t);
2313
2314         return (res) ? res : count;
2315 }
2316
2317 static struct device_attribute dev_attr_hotkey_mask =
2318         __ATTR(hotkey_mask, S_IWUSR | S_IRUGO,
2319                 hotkey_mask_show, hotkey_mask_store);
2320
2321 /* sysfs hotkey bios_enabled ------------------------------------------- */
2322 static ssize_t hotkey_bios_enabled_show(struct device *dev,
2323                            struct device_attribute *attr,
2324                            char *buf)
2325 {
2326         return sprintf(buf, "0\n");
2327 }
2328
2329 static struct device_attribute dev_attr_hotkey_bios_enabled =
2330         __ATTR(hotkey_bios_enabled, S_IRUGO, hotkey_bios_enabled_show, NULL);
2331
2332 /* sysfs hotkey bios_mask ---------------------------------------------- */
2333 static ssize_t hotkey_bios_mask_show(struct device *dev,
2334                            struct device_attribute *attr,
2335                            char *buf)
2336 {
2337         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_orig_mask);
2338 }
2339
2340 static struct device_attribute dev_attr_hotkey_bios_mask =
2341         __ATTR(hotkey_bios_mask, S_IRUGO, hotkey_bios_mask_show, NULL);
2342
2343 /* sysfs hotkey all_mask ----------------------------------------------- */
2344 static ssize_t hotkey_all_mask_show(struct device *dev,
2345                            struct device_attribute *attr,
2346                            char *buf)
2347 {
2348         return snprintf(buf, PAGE_SIZE, "0x%08x\n",
2349                                 hotkey_all_mask | hotkey_source_mask);
2350 }
2351
2352 static struct device_attribute dev_attr_hotkey_all_mask =
2353         __ATTR(hotkey_all_mask, S_IRUGO, hotkey_all_mask_show, NULL);
2354
2355 /* sysfs hotkey recommended_mask --------------------------------------- */
2356 static ssize_t hotkey_recommended_mask_show(struct device *dev,
2357                                             struct device_attribute *attr,
2358                                             char *buf)
2359 {
2360         return snprintf(buf, PAGE_SIZE, "0x%08x\n",
2361                         (hotkey_all_mask | hotkey_source_mask)
2362                         & ~hotkey_reserved_mask);
2363 }
2364
2365 static struct device_attribute dev_attr_hotkey_recommended_mask =
2366         __ATTR(hotkey_recommended_mask, S_IRUGO,
2367                 hotkey_recommended_mask_show, NULL);
2368
2369 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2370
2371 /* sysfs hotkey hotkey_source_mask ------------------------------------- */
2372 static ssize_t hotkey_source_mask_show(struct device *dev,
2373                            struct device_attribute *attr,
2374                            char *buf)
2375 {
2376         return snprintf(buf, PAGE_SIZE, "0x%08x\n", hotkey_source_mask);
2377 }
2378
2379 static ssize_t hotkey_source_mask_store(struct device *dev,
2380                             struct device_attribute *attr,
2381                             const char *buf, size_t count)
2382 {
2383         unsigned long t;
2384
2385         if (parse_strtoul(buf, 0xffffffffUL, &t) ||
2386                 ((t & ~TPACPI_HKEY_NVRAM_KNOWN_MASK) != 0))
2387                 return -EINVAL;
2388
2389         if (mutex_lock_killable(&hotkey_mutex))
2390                 return -ERESTARTSYS;
2391
2392         HOTKEY_CONFIG_CRITICAL_START
2393         hotkey_source_mask = t;
2394         HOTKEY_CONFIG_CRITICAL_END
2395
2396         hotkey_poll_setup(1);
2397
2398         mutex_unlock(&hotkey_mutex);
2399
2400         tpacpi_disclose_usertask("hotkey_source_mask", "set to 0x%08lx\n", t);
2401
2402         return count;
2403 }
2404
2405 static struct device_attribute dev_attr_hotkey_source_mask =
2406         __ATTR(hotkey_source_mask, S_IWUSR | S_IRUGO,
2407                 hotkey_source_mask_show, hotkey_source_mask_store);
2408
2409 /* sysfs hotkey hotkey_poll_freq --------------------------------------- */
2410 static ssize_t hotkey_poll_freq_show(struct device *dev,
2411                            struct device_attribute *attr,
2412                            char *buf)
2413 {
2414         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_poll_freq);
2415 }
2416
2417 static ssize_t hotkey_poll_freq_store(struct device *dev,
2418                             struct device_attribute *attr,
2419                             const char *buf, size_t count)
2420 {
2421         unsigned long t;
2422
2423         if (parse_strtoul(buf, 25, &t))
2424                 return -EINVAL;
2425
2426         if (mutex_lock_killable(&hotkey_mutex))
2427                 return -ERESTARTSYS;
2428
2429         hotkey_poll_freq = t;
2430
2431         hotkey_poll_setup(1);
2432         mutex_unlock(&hotkey_mutex);
2433
2434         tpacpi_disclose_usertask("hotkey_poll_freq", "set to %lu\n", t);
2435
2436         return count;
2437 }
2438
2439 static struct device_attribute dev_attr_hotkey_poll_freq =
2440         __ATTR(hotkey_poll_freq, S_IWUSR | S_IRUGO,
2441                 hotkey_poll_freq_show, hotkey_poll_freq_store);
2442
2443 #endif /* CONFIG_THINKPAD_ACPI_HOTKEY_POLL */
2444
2445 /* sysfs hotkey radio_sw (pollable) ------------------------------------ */
2446 static ssize_t hotkey_radio_sw_show(struct device *dev,
2447                            struct device_attribute *attr,
2448                            char *buf)
2449 {
2450         int res;
2451         res = hotkey_get_wlsw();
2452         if (res < 0)
2453                 return res;
2454
2455         /* Opportunistic update */
2456         tpacpi_rfk_update_hwblock_state((res == TPACPI_RFK_RADIO_OFF));
2457
2458         return snprintf(buf, PAGE_SIZE, "%d\n",
2459                         (res == TPACPI_RFK_RADIO_OFF) ? 0 : 1);
2460 }
2461
2462 static struct device_attribute dev_attr_hotkey_radio_sw =
2463         __ATTR(hotkey_radio_sw, S_IRUGO, hotkey_radio_sw_show, NULL);
2464
2465 static void hotkey_radio_sw_notify_change(void)
2466 {
2467         if (tp_features.hotkey_wlsw)
2468                 sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2469                              "hotkey_radio_sw");
2470 }
2471
2472 /* sysfs hotkey tablet mode (pollable) --------------------------------- */
2473 static ssize_t hotkey_tablet_mode_show(struct device *dev,
2474                            struct device_attribute *attr,
2475                            char *buf)
2476 {
2477         int res, s;
2478         res = hotkey_get_tablet_mode(&s);
2479         if (res < 0)
2480                 return res;
2481
2482         return snprintf(buf, PAGE_SIZE, "%d\n", !!s);
2483 }
2484
2485 static struct device_attribute dev_attr_hotkey_tablet_mode =
2486         __ATTR(hotkey_tablet_mode, S_IRUGO, hotkey_tablet_mode_show, NULL);
2487
2488 static void hotkey_tablet_mode_notify_change(void)
2489 {
2490         if (tp_features.hotkey_tablet)
2491                 sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2492                              "hotkey_tablet_mode");
2493 }
2494
2495 /* sysfs hotkey report_mode -------------------------------------------- */
2496 static ssize_t hotkey_report_mode_show(struct device *dev,
2497                            struct device_attribute *attr,
2498                            char *buf)
2499 {
2500         return snprintf(buf, PAGE_SIZE, "%d\n",
2501                 (hotkey_report_mode != 0) ? hotkey_report_mode : 1);
2502 }
2503
2504 static struct device_attribute dev_attr_hotkey_report_mode =
2505         __ATTR(hotkey_report_mode, S_IRUGO, hotkey_report_mode_show, NULL);
2506
2507 /* sysfs wakeup reason (pollable) -------------------------------------- */
2508 static ssize_t hotkey_wakeup_reason_show(struct device *dev,
2509                            struct device_attribute *attr,
2510                            char *buf)
2511 {
2512         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_wakeup_reason);
2513 }
2514
2515 static struct device_attribute dev_attr_hotkey_wakeup_reason =
2516         __ATTR(wakeup_reason, S_IRUGO, hotkey_wakeup_reason_show, NULL);
2517
2518 static void hotkey_wakeup_reason_notify_change(void)
2519 {
2520         if (tp_features.hotkey_mask)
2521                 sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2522                              "wakeup_reason");
2523 }
2524
2525 /* sysfs wakeup hotunplug_complete (pollable) -------------------------- */
2526 static ssize_t hotkey_wakeup_hotunplug_complete_show(struct device *dev,
2527                            struct device_attribute *attr,
2528                            char *buf)
2529 {
2530         return snprintf(buf, PAGE_SIZE, "%d\n", hotkey_autosleep_ack);
2531 }
2532
2533 static struct device_attribute dev_attr_hotkey_wakeup_hotunplug_complete =
2534         __ATTR(wakeup_hotunplug_complete, S_IRUGO,
2535                hotkey_wakeup_hotunplug_complete_show, NULL);
2536
2537 static void hotkey_wakeup_hotunplug_complete_notify_change(void)
2538 {
2539         if (tp_features.hotkey_mask)
2540                 sysfs_notify(&tpacpi_pdev->dev.kobj, NULL,
2541                              "wakeup_hotunplug_complete");
2542 }
2543
2544 /* --------------------------------------------------------------------- */
2545
2546 static struct attribute *hotkey_attributes[] __initdata = {
2547         &dev_attr_hotkey_enable.attr,
2548         &dev_attr_hotkey_bios_enabled.attr,
2549         &dev_attr_hotkey_report_mode.attr,
2550 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2551         &dev_attr_hotkey_mask.attr,
2552         &dev_attr_hotkey_all_mask.attr,
2553         &dev_attr_hotkey_recommended_mask.attr,
2554         &dev_attr_hotkey_source_mask.attr,
2555         &dev_attr_hotkey_poll_freq.attr,
2556 #endif
2557 };
2558
2559 static struct attribute *hotkey_mask_attributes[] __initdata = {
2560         &dev_attr_hotkey_bios_mask.attr,
2561 #ifndef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2562         &dev_attr_hotkey_mask.attr,
2563         &dev_attr_hotkey_all_mask.attr,
2564         &dev_attr_hotkey_recommended_mask.attr,
2565 #endif
2566         &dev_attr_hotkey_wakeup_reason.attr,
2567         &dev_attr_hotkey_wakeup_hotunplug_complete.attr,
2568 };
2569
2570 /*
2571  * Sync both the hw and sw blocking state of all switches
2572  */
2573 static void tpacpi_send_radiosw_update(void)
2574 {
2575         int wlsw;
2576
2577         /*
2578          * We must sync all rfkill controllers *before* issuing any
2579          * rfkill input events, or we will race the rfkill core input
2580          * handler.
2581          *
2582          * tpacpi_inputdev_send_mutex works as a syncronization point
2583          * for the above.
2584          *
2585          * We optimize to avoid numerous calls to hotkey_get_wlsw.
2586          */
2587
2588         wlsw = hotkey_get_wlsw();
2589
2590         /* Sync hw blocking state first if it is hw-blocked */
2591         if (wlsw == TPACPI_RFK_RADIO_OFF)
2592                 tpacpi_rfk_update_hwblock_state(true);
2593
2594         /* Sync sw blocking state */
2595         tpacpi_rfk_update_swstate_all();
2596
2597         /* Sync hw blocking state last if it is hw-unblocked */
2598         if (wlsw == TPACPI_RFK_RADIO_ON)
2599                 tpacpi_rfk_update_hwblock_state(false);
2600
2601         /* Issue rfkill input event for WLSW switch */
2602         if (!(wlsw < 0)) {
2603                 mutex_lock(&tpacpi_inputdev_send_mutex);
2604
2605                 input_report_switch(tpacpi_inputdev,
2606                                     SW_RFKILL_ALL, (wlsw > 0));
2607                 input_sync(tpacpi_inputdev);
2608
2609                 mutex_unlock(&tpacpi_inputdev_send_mutex);
2610         }
2611
2612         /*
2613          * this can be unconditional, as we will poll state again
2614          * if userspace uses the notify to read data
2615          */
2616         hotkey_radio_sw_notify_change();
2617 }
2618
2619 static void hotkey_exit(void)
2620 {
2621 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2622         hotkey_poll_stop_sync();
2623 #endif
2624
2625         if (hotkey_dev_attributes)
2626                 delete_attr_set(hotkey_dev_attributes, &tpacpi_pdev->dev.kobj);
2627
2628         kfree(hotkey_keycode_map);
2629
2630         if (tp_features.hotkey) {
2631                 dbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_HKEY,
2632                            "restoring original hot key mask\n");
2633                 /* no short-circuit boolean operator below! */
2634                 if ((hotkey_mask_set(hotkey_orig_mask) |
2635                      hotkey_status_set(false)) != 0)
2636                         printk(TPACPI_ERR
2637                                "failed to restore hot key mask "
2638                                "to BIOS defaults\n");
2639         }
2640 }
2641
2642 static int __init hotkey_init(struct ibm_init_struct *iibm)
2643 {
2644         /* Requirements for changing the default keymaps:
2645          *
2646          * 1. Many of the keys are mapped to KEY_RESERVED for very
2647          *    good reasons.  Do not change them unless you have deep
2648          *    knowledge on the IBM and Lenovo ThinkPad firmware for
2649          *    the various ThinkPad models.  The driver behaves
2650          *    differently for KEY_RESERVED: such keys have their
2651          *    hot key mask *unset* in mask_recommended, and also
2652          *    in the initial hot key mask programmed into the
2653          *    firmware at driver load time, which means the firm-
2654          *    ware may react very differently if you change them to
2655          *    something else;
2656          *
2657          * 2. You must be subscribed to the linux-thinkpad and
2658          *    ibm-acpi-devel mailing lists, and you should read the
2659          *    list archives since 2007 if you want to change the
2660          *    keymaps.  This requirement exists so that you will
2661          *    know the past history of problems with the thinkpad-
2662          *    acpi driver keymaps, and also that you will be
2663          *    listening to any bug reports;
2664          *
2665          * 3. Do not send thinkpad-acpi specific patches directly to
2666          *    for merging, *ever*.  Send them to the linux-acpi
2667          *    mailinglist for comments.  Merging is to be done only
2668          *    through acpi-test and the ACPI maintainer.
2669          *
2670          * If the above is too much to ask, don't change the keymap.
2671          * Ask the thinkpad-acpi maintainer to do it, instead.
2672          */
2673         static u16 ibm_keycode_map[] __initdata = {
2674                 /* Scan Codes 0x00 to 0x0B: ACPI HKEY FN+F1..F12 */
2675                 KEY_FN_F1,      KEY_FN_F2,      KEY_COFFEE,     KEY_SLEEP,
2676                 KEY_WLAN,       KEY_FN_F6, KEY_SWITCHVIDEOMODE, KEY_FN_F8,
2677                 KEY_FN_F9,      KEY_FN_F10,     KEY_FN_F11,     KEY_SUSPEND,
2678
2679                 /* Scan codes 0x0C to 0x1F: Other ACPI HKEY hot keys */
2680                 KEY_UNKNOWN,    /* 0x0C: FN+BACKSPACE */
2681                 KEY_UNKNOWN,    /* 0x0D: FN+INSERT */
2682                 KEY_UNKNOWN,    /* 0x0E: FN+DELETE */
2683
2684                 /* brightness: firmware always reacts to them, unless
2685                  * X.org did some tricks in the radeon BIOS scratch
2686                  * registers of *some* models */
2687                 KEY_RESERVED,   /* 0x0F: FN+HOME (brightness up) */
2688                 KEY_RESERVED,   /* 0x10: FN+END (brightness down) */
2689
2690                 /* Thinklight: firmware always react to it */
2691                 KEY_RESERVED,   /* 0x11: FN+PGUP (thinklight toggle) */
2692
2693                 KEY_UNKNOWN,    /* 0x12: FN+PGDOWN */
2694                 KEY_ZOOM,       /* 0x13: FN+SPACE (zoom) */
2695
2696                 /* Volume: firmware always react to it and reprograms
2697                  * the built-in *extra* mixer.  Never map it to control
2698                  * another mixer by default. */
2699                 KEY_RESERVED,   /* 0x14: VOLUME UP */
2700                 KEY_RESERVED,   /* 0x15: VOLUME DOWN */
2701                 KEY_RESERVED,   /* 0x16: MUTE */
2702
2703                 KEY_VENDOR,     /* 0x17: Thinkpad/AccessIBM/Lenovo */
2704
2705                 /* (assignments unknown, please report if found) */
2706                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
2707                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
2708         };
2709         static u16 lenovo_keycode_map[] __initdata = {
2710                 /* Scan Codes 0x00 to 0x0B: ACPI HKEY FN+F1..F12 */
2711                 KEY_FN_F1,      KEY_COFFEE,     KEY_BATTERY,    KEY_SLEEP,
2712                 KEY_WLAN,       KEY_FN_F6, KEY_SWITCHVIDEOMODE, KEY_FN_F8,
2713                 KEY_FN_F9,      KEY_FN_F10,     KEY_FN_F11,     KEY_SUSPEND,
2714
2715                 /* Scan codes 0x0C to 0x1F: Other ACPI HKEY hot keys */
2716                 KEY_UNKNOWN,    /* 0x0C: FN+BACKSPACE */
2717                 KEY_UNKNOWN,    /* 0x0D: FN+INSERT */
2718                 KEY_UNKNOWN,    /* 0x0E: FN+DELETE */
2719
2720                 /* These either have to go through ACPI video, or
2721                  * act like in the IBM ThinkPads, so don't ever
2722                  * enable them by default */
2723                 KEY_RESERVED,   /* 0x0F: FN+HOME (brightness up) */
2724                 KEY_RESERVED,   /* 0x10: FN+END (brightness down) */
2725
2726                 KEY_RESERVED,   /* 0x11: FN+PGUP (thinklight toggle) */
2727
2728                 KEY_UNKNOWN,    /* 0x12: FN+PGDOWN */
2729                 KEY_ZOOM,       /* 0x13: FN+SPACE (zoom) */
2730
2731                 /* Volume: z60/z61, T60 (BIOS version?): firmware always
2732                  * react to it and reprograms the built-in *extra* mixer.
2733                  * Never map it to control another mixer by default.
2734                  *
2735                  * T60?, T61, R60?, R61: firmware and EC tries to send
2736                  * these over the regular keyboard, so these are no-ops,
2737                  * but there are still weird bugs re. MUTE, so do not
2738                  * change unless you get test reports from all Lenovo
2739                  * models.  May cause the BIOS to interfere with the
2740                  * HDA mixer.
2741                  */
2742                 KEY_RESERVED,   /* 0x14: VOLUME UP */
2743                 KEY_RESERVED,   /* 0x15: VOLUME DOWN */
2744                 KEY_RESERVED,   /* 0x16: MUTE */
2745
2746                 KEY_VENDOR,     /* 0x17: Thinkpad/AccessIBM/Lenovo */
2747
2748                 /* (assignments unknown, please report if found) */
2749                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
2750                 KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN, KEY_UNKNOWN,
2751         };
2752
2753 #define TPACPI_HOTKEY_MAP_LEN           ARRAY_SIZE(ibm_keycode_map)
2754 #define TPACPI_HOTKEY_MAP_SIZE          sizeof(ibm_keycode_map)
2755 #define TPACPI_HOTKEY_MAP_TYPESIZE      sizeof(ibm_keycode_map[0])
2756
2757         int res, i;
2758         int status;
2759         int hkeyv;
2760
2761         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
2762                         "initializing hotkey subdriver\n");
2763
2764         BUG_ON(!tpacpi_inputdev);
2765         BUG_ON(tpacpi_inputdev->open != NULL ||
2766                tpacpi_inputdev->close != NULL);
2767
2768         TPACPI_ACPIHANDLE_INIT(hkey);
2769         mutex_init(&hotkey_mutex);
2770
2771 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2772         mutex_init(&hotkey_thread_mutex);
2773         mutex_init(&hotkey_thread_data_mutex);
2774 #endif
2775
2776         /* hotkey not supported on 570 */
2777         tp_features.hotkey = hkey_handle != NULL;
2778
2779         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
2780                 "hotkeys are %s\n",
2781                 str_supported(tp_features.hotkey));
2782
2783         if (!tp_features.hotkey)
2784                 return 1;
2785
2786         tpacpi_disable_brightness_delay();
2787
2788         hotkey_dev_attributes = create_attr_set(13, NULL);
2789         if (!hotkey_dev_attributes)
2790                 return -ENOMEM;
2791         res = add_many_to_attr_set(hotkey_dev_attributes,
2792                         hotkey_attributes,
2793                         ARRAY_SIZE(hotkey_attributes));
2794         if (res)
2795                 goto err_exit;
2796
2797         /* mask not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
2798            A30, R30, R31, T20-22, X20-21, X22-24.  Detected by checking
2799            for HKEY interface version 0x100 */
2800         if (acpi_evalf(hkey_handle, &hkeyv, "MHKV", "qd")) {
2801                 if ((hkeyv >> 8) != 1) {
2802                         printk(TPACPI_ERR "unknown version of the "
2803                                "HKEY interface: 0x%x\n", hkeyv);
2804                         printk(TPACPI_ERR "please report this to %s\n",
2805                                TPACPI_MAIL);
2806                 } else {
2807                         /*
2808                          * MHKV 0x100 in A31, R40, R40e,
2809                          * T4x, X31, and later
2810                          */
2811                         tp_features.hotkey_mask = 1;
2812                         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
2813                                 "firmware HKEY interface version: 0x%x\n",
2814                                 hkeyv);
2815                 }
2816         }
2817
2818         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
2819                 "hotkey masks are %s\n",
2820                 str_supported(tp_features.hotkey_mask));
2821
2822         if (tp_features.hotkey_mask) {
2823                 if (!acpi_evalf(hkey_handle, &hotkey_all_mask,
2824                                 "MHKA", "qd")) {
2825                         printk(TPACPI_ERR
2826                                "missing MHKA handler, "
2827                                "please report this to %s\n",
2828                                TPACPI_MAIL);
2829                         /* FN+F12, FN+F4, FN+F3 */
2830                         hotkey_all_mask = 0x080cU;
2831                 }
2832         }
2833
2834         /* hotkey_source_mask *must* be zero for
2835          * the first hotkey_mask_get */
2836         if (tp_features.hotkey_mask) {
2837                 res = hotkey_mask_get();
2838                 if (res)
2839                         goto err_exit;
2840
2841                 hotkey_orig_mask = hotkey_mask;
2842                 res = add_many_to_attr_set(
2843                                 hotkey_dev_attributes,
2844                                 hotkey_mask_attributes,
2845                                 ARRAY_SIZE(hotkey_mask_attributes));
2846                 if (res)
2847                         goto err_exit;
2848         }
2849
2850 #ifdef CONFIG_THINKPAD_ACPI_HOTKEY_POLL
2851         if (tp_features.hotkey_mask) {
2852                 hotkey_source_mask = TPACPI_HKEY_NVRAM_GOOD_MASK
2853                                         & ~hotkey_all_mask;
2854         } else {
2855                 hotkey_source_mask = TPACPI_HKEY_NVRAM_GOOD_MASK;
2856         }
2857
2858         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
2859                     "hotkey source mask 0x%08x, polling freq %d\n",
2860                     hotkey_source_mask, hotkey_poll_freq);
2861 #endif
2862
2863 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
2864         if (dbg_wlswemul) {
2865                 tp_features.hotkey_wlsw = 1;
2866                 printk(TPACPI_INFO
2867                         "radio switch emulation enabled\n");
2868         } else
2869 #endif
2870         /* Not all thinkpads have a hardware radio switch */
2871         if (acpi_evalf(hkey_handle, &status, "WLSW", "qd")) {
2872                 tp_features.hotkey_wlsw = 1;
2873                 printk(TPACPI_INFO
2874                         "radio switch found; radios are %s\n",
2875                         enabled(status, 0));
2876         }
2877         if (tp_features.hotkey_wlsw)
2878                 res = add_to_attr_set(hotkey_dev_attributes,
2879                                 &dev_attr_hotkey_radio_sw.attr);
2880
2881         /* For X41t, X60t, X61t Tablets... */
2882         if (!res && acpi_evalf(hkey_handle, &status, "MHKG", "qd")) {
2883                 tp_features.hotkey_tablet = 1;
2884                 printk(TPACPI_INFO
2885                         "possible tablet mode switch found; "
2886                         "ThinkPad in %s mode\n",
2887                         (status & TP_HOTKEY_TABLET_MASK)?
2888                                 "tablet" : "laptop");
2889                 res = add_to_attr_set(hotkey_dev_attributes,
2890                                 &dev_attr_hotkey_tablet_mode.attr);
2891         }
2892
2893         if (!res)
2894                 res = register_attr_set_with_sysfs(
2895                                 hotkey_dev_attributes,
2896                                 &tpacpi_pdev->dev.kobj);
2897         if (res)
2898                 goto err_exit;
2899
2900         /* Set up key map */
2901
2902         hotkey_keycode_map = kmalloc(TPACPI_HOTKEY_MAP_SIZE,
2903                                         GFP_KERNEL);
2904         if (!hotkey_keycode_map) {
2905                 printk(TPACPI_ERR
2906                         "failed to allocate memory for key map\n");
2907                 res = -ENOMEM;
2908                 goto err_exit;
2909         }
2910
2911         if (thinkpad_id.vendor == PCI_VENDOR_ID_LENOVO) {
2912                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
2913                            "using Lenovo default hot key map\n");
2914                 memcpy(hotkey_keycode_map, &lenovo_keycode_map,
2915                         TPACPI_HOTKEY_MAP_SIZE);
2916         } else {
2917                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
2918                            "using IBM default hot key map\n");
2919                 memcpy(hotkey_keycode_map, &ibm_keycode_map,
2920                         TPACPI_HOTKEY_MAP_SIZE);
2921         }
2922
2923         set_bit(EV_KEY, tpacpi_inputdev->evbit);
2924         set_bit(EV_MSC, tpacpi_inputdev->evbit);
2925         set_bit(MSC_SCAN, tpacpi_inputdev->mscbit);
2926         tpacpi_inputdev->keycodesize = TPACPI_HOTKEY_MAP_TYPESIZE;
2927         tpacpi_inputdev->keycodemax = TPACPI_HOTKEY_MAP_LEN;
2928         tpacpi_inputdev->keycode = hotkey_keycode_map;
2929         for (i = 0; i < TPACPI_HOTKEY_MAP_LEN; i++) {
2930                 if (hotkey_keycode_map[i] != KEY_RESERVED) {
2931                         set_bit(hotkey_keycode_map[i],
2932                                 tpacpi_inputdev->keybit);
2933                 } else {
2934                         if (i < sizeof(hotkey_reserved_mask)*8)
2935                                 hotkey_reserved_mask |= 1 << i;
2936                 }
2937         }
2938
2939         if (tp_features.hotkey_wlsw) {
2940                 set_bit(EV_SW, tpacpi_inputdev->evbit);
2941                 set_bit(SW_RFKILL_ALL, tpacpi_inputdev->swbit);
2942         }
2943         if (tp_features.hotkey_tablet) {
2944                 set_bit(EV_SW, tpacpi_inputdev->evbit);
2945                 set_bit(SW_TABLET_MODE, tpacpi_inputdev->swbit);
2946         }
2947
2948         /* Do not issue duplicate brightness change events to
2949          * userspace */
2950         if (!tp_features.bright_acpimode)
2951                 /* update bright_acpimode... */
2952                 tpacpi_check_std_acpi_brightness_support();
2953
2954         if (tp_features.bright_acpimode && acpi_video_backlight_support()) {
2955                 printk(TPACPI_INFO
2956                        "This ThinkPad has standard ACPI backlight "
2957                        "brightness control, supported by the ACPI "
2958                        "video driver\n");
2959                 printk(TPACPI_NOTICE
2960                        "Disabling thinkpad-acpi brightness events "
2961                        "by default...\n");
2962
2963                 /* The hotkey_reserved_mask change below is not
2964                  * necessary while the keys are at KEY_RESERVED in the
2965                  * default map, but better safe than sorry, leave it
2966                  * here as a marker of what we have to do, especially
2967                  * when we finally become able to set this at runtime
2968                  * on response to X.org requests */
2969                 hotkey_reserved_mask |=
2970                         (1 << TP_ACPI_HOTKEYSCAN_FNHOME)
2971                         | (1 << TP_ACPI_HOTKEYSCAN_FNEND);
2972         }
2973
2974         dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
2975                         "enabling firmware HKEY event interface...\n");
2976         res = hotkey_status_set(true);
2977         if (res) {
2978                 hotkey_exit();
2979                 return res;
2980         }
2981         res = hotkey_mask_set(((hotkey_all_mask | hotkey_source_mask)
2982                                 & ~hotkey_reserved_mask)
2983                                 | hotkey_orig_mask);
2984         if (res < 0 && res != -ENXIO) {
2985                 hotkey_exit();
2986                 return res;
2987         }
2988
2989         dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_HKEY,
2990                         "legacy ibm/hotkey event reporting over procfs %s\n",
2991                         (hotkey_report_mode < 2) ?
2992                                 "enabled" : "disabled");
2993
2994         tpacpi_inputdev->open = &hotkey_inputdev_open;
2995         tpacpi_inputdev->close = &hotkey_inputdev_close;
2996
2997         hotkey_poll_setup_safe(1);
2998         tpacpi_send_radiosw_update();
2999         tpacpi_input_send_tabletsw();
3000
3001         return 0;
3002
3003 err_exit:
3004         delete_attr_set(hotkey_dev_attributes, &tpacpi_pdev->dev.kobj);
3005         hotkey_dev_attributes = NULL;
3006
3007         return (res < 0)? res : 1;
3008 }
3009
3010 static bool hotkey_notify_hotkey(const u32 hkey,
3011                                  bool *send_acpi_ev,
3012                                  bool *ignore_acpi_ev)
3013 {
3014         /* 0x1000-0x1FFF: key presses */
3015         unsigned int scancode = hkey & 0xfff;
3016         *send_acpi_ev = true;
3017         *ignore_acpi_ev = false;
3018
3019         if (scancode > 0 && scancode < 0x21) {
3020                 scancode--;
3021                 if (!(hotkey_source_mask & (1 << scancode))) {
3022                         tpacpi_input_send_key(scancode);
3023                         *send_acpi_ev = false;
3024                 } else {
3025                         *ignore_acpi_ev = true;
3026                 }
3027                 return true;
3028         }
3029         return false;
3030 }
3031
3032 static bool hotkey_notify_wakeup(const u32 hkey,
3033                                  bool *send_acpi_ev,
3034                                  bool *ignore_acpi_ev)
3035 {
3036         /* 0x2000-0x2FFF: Wakeup reason */
3037         *send_acpi_ev = true;
3038         *ignore_acpi_ev = false;
3039
3040         switch (hkey) {
3041         case 0x2304: /* suspend, undock */
3042         case 0x2404: /* hibernation, undock */
3043                 hotkey_wakeup_reason = TP_ACPI_WAKEUP_UNDOCK;
3044                 *ignore_acpi_ev = true;
3045                 break;
3046
3047         case 0x2305: /* suspend, bay eject */
3048         case 0x2405: /* hibernation, bay eject */
3049                 hotkey_wakeup_reason = TP_ACPI_WAKEUP_BAYEJ;
3050                 *ignore_acpi_ev = true;
3051                 break;
3052
3053         case 0x2313: /* Battery on critical low level (S3) */
3054         case 0x2413: /* Battery on critical low level (S4) */
3055                 printk(TPACPI_ALERT
3056                         "EMERGENCY WAKEUP: battery almost empty\n");
3057                 /* how to auto-heal: */
3058                 /* 2313: woke up from S3, go to S4/S5 */
3059                 /* 2413: woke up from S4, go to S5 */
3060                 break;
3061
3062         default:
3063                 return false;
3064         }
3065
3066         if (hotkey_wakeup_reason != TP_ACPI_WAKEUP_NONE) {
3067                 printk(TPACPI_INFO
3068                        "woke up due to a hot-unplug "
3069                        "request...\n");
3070                 hotkey_wakeup_reason_notify_change();
3071         }
3072         return true;
3073 }
3074
3075 static bool hotkey_notify_usrevent(const u32 hkey,
3076                                  bool *send_acpi_ev,
3077                                  bool *ignore_acpi_ev)
3078 {
3079         /* 0x5000-0x5FFF: human interface helpers */
3080         *send_acpi_ev = true;
3081         *ignore_acpi_ev = false;
3082
3083         switch (hkey) {
3084         case 0x5010: /* Lenovo new BIOS: brightness changed */
3085         case 0x500b: /* X61t: tablet pen inserted into bay */
3086         case 0x500c: /* X61t: tablet pen removed from bay */
3087                 return true;
3088
3089         case 0x5009: /* X41t-X61t: swivel up (tablet mode) */
3090         case 0x500a: /* X41t-X61t: swivel down (normal mode) */
3091                 tpacpi_input_send_tabletsw();
3092                 hotkey_tablet_mode_notify_change();
3093                 *send_acpi_ev = false;
3094                 return true;
3095
3096         case 0x5001:
3097         case 0x5002:
3098                 /* LID switch events.  Do not propagate */
3099                 *ignore_acpi_ev = true;
3100                 return true;
3101
3102         default:
3103                 return false;
3104         }
3105 }
3106
3107 static bool hotkey_notify_thermal(const u32 hkey,
3108                                  bool *send_acpi_ev,
3109                                  bool *ignore_acpi_ev)
3110 {
3111         /* 0x6000-0x6FFF: thermal alarms */
3112         *send_acpi_ev = true;
3113         *ignore_acpi_ev = false;
3114
3115         switch (hkey) {
3116         case 0x6011:
3117                 printk(TPACPI_CRIT
3118                         "THERMAL ALARM: battery is too hot!\n");
3119                 /* recommended action: warn user through gui */
3120                 return true;
3121         case 0x6012:
3122                 printk(TPACPI_ALERT
3123                         "THERMAL EMERGENCY: battery is extremely hot!\n");
3124                 /* recommended action: immediate sleep/hibernate */
3125                 return true;
3126         case 0x6021:
3127                 printk(TPACPI_CRIT
3128                         "THERMAL ALARM: "
3129                         "a sensor reports something is too hot!\n");
3130                 /* recommended action: warn user through gui, that */
3131                 /* some internal component is too hot */
3132                 return true;
3133         case 0x6022:
3134                 printk(TPACPI_ALERT
3135                         "THERMAL EMERGENCY: "
3136                         "a sensor reports something is extremely hot!\n");
3137                 /* recommended action: immediate sleep/hibernate */
3138                 return true;
3139         case 0x6030:
3140                 printk(TPACPI_INFO
3141                         "EC reports that Thermal Table has changed\n");
3142                 /* recommended action: do nothing, we don't have
3143                  * Lenovo ATM information */
3144                 return true;
3145         default:
3146                 printk(TPACPI_ALERT
3147                          "THERMAL ALERT: unknown thermal alarm received\n");
3148                 return false;
3149         }
3150 }
3151
3152 static void hotkey_notify(struct ibm_struct *ibm, u32 event)
3153 {
3154         u32 hkey;
3155         bool send_acpi_ev;
3156         bool ignore_acpi_ev;
3157         bool known_ev;
3158
3159         if (event != 0x80) {
3160                 printk(TPACPI_ERR
3161                        "unknown HKEY notification event %d\n", event);
3162                 /* forward it to userspace, maybe it knows how to handle it */
3163                 acpi_bus_generate_netlink_event(
3164                                         ibm->acpi->device->pnp.device_class,
3165                                         dev_name(&ibm->acpi->device->dev),
3166                                         event, 0);
3167                 return;
3168         }
3169
3170         while (1) {
3171                 if (!acpi_evalf(hkey_handle, &hkey, "MHKP", "d")) {
3172                         printk(TPACPI_ERR "failed to retrieve HKEY event\n");
3173                         return;
3174                 }
3175
3176                 if (hkey == 0) {
3177                         /* queue empty */
3178                         return;
3179                 }
3180
3181                 send_acpi_ev = true;
3182                 ignore_acpi_ev = false;
3183
3184                 switch (hkey >> 12) {
3185                 case 1:
3186                         /* 0x1000-0x1FFF: key presses */
3187                         known_ev = hotkey_notify_hotkey(hkey, &send_acpi_ev,
3188                                                  &ignore_acpi_ev);
3189                         break;
3190                 case 2:
3191                         /* 0x2000-0x2FFF: Wakeup reason */
3192                         known_ev = hotkey_notify_wakeup(hkey, &send_acpi_ev,
3193                                                  &ignore_acpi_ev);
3194                         break;
3195                 case 3:
3196                         /* 0x3000-0x3FFF: bay-related wakeups */
3197                         if (hkey == 0x3003) {
3198                                 hotkey_autosleep_ack = 1;
3199                                 printk(TPACPI_INFO
3200                                        "bay ejected\n");
3201                                 hotkey_wakeup_hotunplug_complete_notify_change();
3202                                 known_ev = true;
3203                         } else {
3204                                 known_ev = false;
3205                         }
3206                         break;
3207                 case 4:
3208                         /* 0x4000-0x4FFF: dock-related wakeups */
3209                         if (hkey == 0x4003) {
3210                                 hotkey_autosleep_ack = 1;
3211                                 printk(TPACPI_INFO
3212                                        "undocked\n");
3213                                 hotkey_wakeup_hotunplug_complete_notify_change();
3214                                 known_ev = true;
3215                         } else {
3216                                 known_ev = false;
3217                         }
3218                         break;
3219                 case 5:
3220                         /* 0x5000-0x5FFF: human interface helpers */
3221                         known_ev = hotkey_notify_usrevent(hkey, &send_acpi_ev,
3222                                                  &ignore_acpi_ev);
3223                         break;
3224                 case 6:
3225                         /* 0x6000-0x6FFF: thermal alarms */
3226                         known_ev = hotkey_notify_thermal(hkey, &send_acpi_ev,
3227                                                  &ignore_acpi_ev);
3228                         break;
3229                 case 7:
3230                         /* 0x7000-0x7FFF: misc */
3231                         if (tp_features.hotkey_wlsw && hkey == 0x7000) {
3232                                 tpacpi_send_radiosw_update();
3233                                 send_acpi_ev = 0;
3234                                 known_ev = true;
3235                                 break;
3236                         }
3237                         /* fallthrough to default */
3238                 default:
3239                         known_ev = false;
3240                 }
3241                 if (!known_ev) {
3242                         printk(TPACPI_NOTICE
3243                                "unhandled HKEY event 0x%04x\n", hkey);
3244                         printk(TPACPI_NOTICE
3245                                "please report the conditions when this "
3246                                "event happened to %s\n", TPACPI_MAIL);
3247                 }
3248
3249                 /* Legacy events */
3250                 if (!ignore_acpi_ev &&
3251                     (send_acpi_ev || hotkey_report_mode < 2)) {
3252                         acpi_bus_generate_proc_event(ibm->acpi->device,
3253                                                      event, hkey);
3254                 }
3255
3256                 /* netlink events */
3257                 if (!ignore_acpi_ev && send_acpi_ev) {
3258                         acpi_bus_generate_netlink_event(
3259                                         ibm->acpi->device->pnp.device_class,
3260                                         dev_name(&ibm->acpi->device->dev),
3261                                         event, hkey);
3262                 }
3263         }
3264 }
3265
3266 static void hotkey_suspend(pm_message_t state)
3267 {
3268         /* Do these on suspend, we get the events on early resume! */
3269         hotkey_wakeup_reason = TP_ACPI_WAKEUP_NONE;
3270         hotkey_autosleep_ack = 0;
3271 }
3272
3273 static void hotkey_resume(void)
3274 {
3275         tpacpi_disable_brightness_delay();
3276
3277         if (hotkey_mask_get())
3278                 printk(TPACPI_ERR
3279                        "error while trying to read hot key mask "
3280                        "from firmware\n");
3281         tpacpi_send_radiosw_update();
3282         hotkey_tablet_mode_notify_change();
3283         hotkey_wakeup_reason_notify_change();
3284         hotkey_wakeup_hotunplug_complete_notify_change();
3285         hotkey_poll_setup_safe(0);
3286 }
3287
3288 /* procfs -------------------------------------------------------------- */
3289 static int hotkey_read(char *p)
3290 {
3291         int res, status;
3292         int len = 0;
3293
3294         if (!tp_features.hotkey) {
3295                 len += sprintf(p + len, "status:\t\tnot supported\n");
3296                 return len;
3297         }
3298
3299         if (mutex_lock_killable(&hotkey_mutex))
3300                 return -ERESTARTSYS;
3301         res = hotkey_status_get(&status);
3302         if (!res)
3303                 res = hotkey_mask_get();
3304         mutex_unlock(&hotkey_mutex);
3305         if (res)
3306                 return res;
3307
3308         len += sprintf(p + len, "status:\t\t%s\n", enabled(status, 0));
3309         if (tp_features.hotkey_mask) {
3310                 len += sprintf(p + len, "mask:\t\t0x%08x\n", hotkey_mask);
3311                 len += sprintf(p + len,
3312                                "commands:\tenable, disable, reset, <mask>\n");
3313         } else {
3314                 len += sprintf(p + len, "mask:\t\tnot supported\n");
3315                 len += sprintf(p + len, "commands:\tenable, disable, reset\n");
3316         }
3317
3318         return len;
3319 }
3320
3321 static void hotkey_enabledisable_warn(bool enable)
3322 {
3323         tpacpi_log_usertask("procfs hotkey enable/disable");
3324         if (!WARN((tpacpi_lifecycle == TPACPI_LIFE_RUNNING || !enable),
3325                         TPACPI_WARN
3326                         "hotkey enable/disable functionality has been "
3327                         "removed from the driver.  Hotkeys are always "
3328                         "enabled\n"))
3329                 printk(TPACPI_ERR
3330                         "Please remove the hotkey=enable module "
3331                         "parameter, it is deprecated.  Hotkeys are always "
3332                         "enabled\n");
3333 }
3334
3335 static int hotkey_write(char *buf)
3336 {
3337         int res;
3338         u32 mask;
3339         char *cmd;
3340
3341         if (!tp_features.hotkey)
3342                 return -ENODEV;
3343
3344         if (mutex_lock_killable(&hotkey_mutex))
3345                 return -ERESTARTSYS;
3346
3347         mask = hotkey_mask;
3348
3349         res = 0;
3350         while ((cmd = next_cmd(&buf))) {
3351                 if (strlencmp(cmd, "enable") == 0) {
3352                         hotkey_enabledisable_warn(1);
3353                 } else if (strlencmp(cmd, "disable") == 0) {
3354                         hotkey_enabledisable_warn(0);
3355                         res = -EPERM;
3356                 } else if (strlencmp(cmd, "reset") == 0) {
3357                         mask = hotkey_orig_mask;
3358                 } else if (sscanf(cmd, "0x%x", &mask) == 1) {
3359                         /* mask set */
3360                 } else if (sscanf(cmd, "%x", &mask) == 1) {
3361                         /* mask set */
3362                 } else {
3363                         res = -EINVAL;
3364                         goto errexit;
3365                 }
3366         }
3367
3368         if (!res)
3369                 tpacpi_disclose_usertask("procfs hotkey",
3370                         "set mask to 0x%08x\n", mask);
3371
3372         if (!res && mask != hotkey_mask)
3373                 res = hotkey_mask_set(mask);
3374
3375 errexit:
3376         mutex_unlock(&hotkey_mutex);
3377         return res;
3378 }
3379
3380 static const struct acpi_device_id ibm_htk_device_ids[] = {
3381         {TPACPI_ACPI_HKEY_HID, 0},
3382         {"", 0},
3383 };
3384
3385 static struct tp_acpi_drv_struct ibm_hotkey_acpidriver = {
3386         .hid = ibm_htk_device_ids,
3387         .notify = hotkey_notify,
3388         .handle = &hkey_handle,
3389         .type = ACPI_DEVICE_NOTIFY,
3390 };
3391
3392 static struct ibm_struct hotkey_driver_data = {
3393         .name = "hotkey",
3394         .read = hotkey_read,
3395         .write = hotkey_write,
3396         .exit = hotkey_exit,
3397         .resume = hotkey_resume,
3398         .suspend = hotkey_suspend,
3399         .acpi = &ibm_hotkey_acpidriver,
3400 };
3401
3402 /*************************************************************************
3403  * Bluetooth subdriver
3404  */
3405
3406 enum {
3407         /* ACPI GBDC/SBDC bits */
3408         TP_ACPI_BLUETOOTH_HWPRESENT     = 0x01, /* Bluetooth hw available */
3409         TP_ACPI_BLUETOOTH_RADIOSSW      = 0x02, /* Bluetooth radio enabled */
3410         TP_ACPI_BLUETOOTH_RESUMECTRL    = 0x04, /* Bluetooth state at resume:
3411                                                    off / last state */
3412 };
3413
3414 enum {
3415         /* ACPI \BLTH commands */
3416         TP_ACPI_BLTH_GET_ULTRAPORT_ID   = 0x00, /* Get Ultraport BT ID */
3417         TP_ACPI_BLTH_GET_PWR_ON_RESUME  = 0x01, /* Get power-on-resume state */
3418         TP_ACPI_BLTH_PWR_ON_ON_RESUME   = 0x02, /* Resume powered on */
3419         TP_ACPI_BLTH_PWR_OFF_ON_RESUME  = 0x03, /* Resume powered off */
3420         TP_ACPI_BLTH_SAVE_STATE         = 0x05, /* Save state for S4/S5 */
3421 };
3422
3423 #define TPACPI_RFK_BLUETOOTH_SW_NAME    "tpacpi_bluetooth_sw"
3424
3425 static void bluetooth_suspend(pm_message_t state)
3426 {
3427         /* Try to make sure radio will resume powered off */
3428         if (!acpi_evalf(NULL, NULL, "\\BLTH", "vd",
3429                    TP_ACPI_BLTH_PWR_OFF_ON_RESUME))
3430                 vdbg_printk(TPACPI_DBG_RFKILL,
3431                         "bluetooth power down on resume request failed\n");
3432 }
3433
3434 static int bluetooth_get_status(void)
3435 {
3436         int status;
3437
3438 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3439         if (dbg_bluetoothemul)
3440                 return (tpacpi_bluetooth_emulstate) ?
3441                        TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
3442 #endif
3443
3444         if (!acpi_evalf(hkey_handle, &status, "GBDC", "d"))
3445                 return -EIO;
3446
3447         return ((status & TP_ACPI_BLUETOOTH_RADIOSSW) != 0) ?
3448                         TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
3449 }
3450
3451 static int bluetooth_set_status(enum tpacpi_rfkill_state state)
3452 {
3453         int status;
3454
3455         vdbg_printk(TPACPI_DBG_RFKILL,
3456                 "will attempt to %s bluetooth\n",
3457                 (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable");
3458
3459 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3460         if (dbg_bluetoothemul) {
3461                 tpacpi_bluetooth_emulstate = (state == TPACPI_RFK_RADIO_ON);
3462                 return 0;
3463         }
3464 #endif
3465
3466         /* We make sure to keep TP_ACPI_BLUETOOTH_RESUMECTRL off */
3467         if (state == TPACPI_RFK_RADIO_ON)
3468                 status = TP_ACPI_BLUETOOTH_RADIOSSW;
3469         else
3470                 status = 0;
3471
3472         if (!acpi_evalf(hkey_handle, NULL, "SBDC", "vd", status))
3473                 return -EIO;
3474
3475         return 0;
3476 }
3477
3478 /* sysfs bluetooth enable ---------------------------------------------- */
3479 static ssize_t bluetooth_enable_show(struct device *dev,
3480                            struct device_attribute *attr,
3481                            char *buf)
3482 {
3483         return tpacpi_rfk_sysfs_enable_show(TPACPI_RFK_BLUETOOTH_SW_ID,
3484                         attr, buf);
3485 }
3486
3487 static ssize_t bluetooth_enable_store(struct device *dev,
3488                             struct device_attribute *attr,
3489                             const char *buf, size_t count)
3490 {
3491         return tpacpi_rfk_sysfs_enable_store(TPACPI_RFK_BLUETOOTH_SW_ID,
3492                                 attr, buf, count);
3493 }
3494
3495 static struct device_attribute dev_attr_bluetooth_enable =
3496         __ATTR(bluetooth_enable, S_IWUSR | S_IRUGO,
3497                 bluetooth_enable_show, bluetooth_enable_store);
3498
3499 /* --------------------------------------------------------------------- */
3500
3501 static struct attribute *bluetooth_attributes[] = {
3502         &dev_attr_bluetooth_enable.attr,
3503         NULL
3504 };
3505
3506 static const struct attribute_group bluetooth_attr_group = {
3507         .attrs = bluetooth_attributes,
3508 };
3509
3510 static const struct tpacpi_rfk_ops bluetooth_tprfk_ops = {
3511         .get_status = bluetooth_get_status,
3512         .set_status = bluetooth_set_status,
3513 };
3514
3515 static void bluetooth_shutdown(void)
3516 {
3517         /* Order firmware to save current state to NVRAM */
3518         if (!acpi_evalf(NULL, NULL, "\\BLTH", "vd",
3519                         TP_ACPI_BLTH_SAVE_STATE))
3520                 printk(TPACPI_NOTICE
3521                         "failed to save bluetooth state to NVRAM\n");
3522         else
3523                 vdbg_printk(TPACPI_DBG_RFKILL,
3524                         "bluestooth state saved to NVRAM\n");
3525 }
3526
3527 static void bluetooth_exit(void)
3528 {
3529         sysfs_remove_group(&tpacpi_pdev->dev.kobj,
3530                         &bluetooth_attr_group);
3531
3532         tpacpi_destroy_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID);
3533
3534         bluetooth_shutdown();
3535 }
3536
3537 static int __init bluetooth_init(struct ibm_init_struct *iibm)
3538 {
3539         int res;
3540         int status = 0;
3541
3542         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
3543                         "initializing bluetooth subdriver\n");
3544
3545         TPACPI_ACPIHANDLE_INIT(hkey);
3546
3547         /* bluetooth not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
3548            G4x, R30, R31, R40e, R50e, T20-22, X20-21 */
3549         tp_features.bluetooth = hkey_handle &&
3550             acpi_evalf(hkey_handle, &status, "GBDC", "qd");
3551
3552         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
3553                 "bluetooth is %s, status 0x%02x\n",
3554                 str_supported(tp_features.bluetooth),
3555                 status);
3556
3557 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3558         if (dbg_bluetoothemul) {
3559                 tp_features.bluetooth = 1;
3560                 printk(TPACPI_INFO
3561                         "bluetooth switch emulation enabled\n");
3562         } else
3563 #endif
3564         if (tp_features.bluetooth &&
3565             !(status & TP_ACPI_BLUETOOTH_HWPRESENT)) {
3566                 /* no bluetooth hardware present in system */
3567                 tp_features.bluetooth = 0;
3568                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
3569                            "bluetooth hardware not installed\n");
3570         }
3571
3572         if (!tp_features.bluetooth)
3573                 return 1;
3574
3575         res = tpacpi_new_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID,
3576                                 &bluetooth_tprfk_ops,
3577                                 RFKILL_TYPE_BLUETOOTH,
3578                                 TPACPI_RFK_BLUETOOTH_SW_NAME,
3579                                 true);
3580         if (res)
3581                 return res;
3582
3583         res = sysfs_create_group(&tpacpi_pdev->dev.kobj,
3584                                 &bluetooth_attr_group);
3585         if (res) {
3586                 tpacpi_destroy_rfkill(TPACPI_RFK_BLUETOOTH_SW_ID);
3587                 return res;
3588         }
3589
3590         return 0;
3591 }
3592
3593 /* procfs -------------------------------------------------------------- */
3594 static int bluetooth_read(char *p)
3595 {
3596         return tpacpi_rfk_procfs_read(TPACPI_RFK_BLUETOOTH_SW_ID, p);
3597 }
3598
3599 static int bluetooth_write(char *buf)
3600 {
3601         return tpacpi_rfk_procfs_write(TPACPI_RFK_BLUETOOTH_SW_ID, buf);
3602 }
3603
3604 static struct ibm_struct bluetooth_driver_data = {
3605         .name = "bluetooth",
3606         .read = bluetooth_read,
3607         .write = bluetooth_write,
3608         .exit = bluetooth_exit,
3609         .suspend = bluetooth_suspend,
3610         .shutdown = bluetooth_shutdown,
3611 };
3612
3613 /*************************************************************************
3614  * Wan subdriver
3615  */
3616
3617 enum {
3618         /* ACPI GWAN/SWAN bits */
3619         TP_ACPI_WANCARD_HWPRESENT       = 0x01, /* Wan hw available */
3620         TP_ACPI_WANCARD_RADIOSSW        = 0x02, /* Wan radio enabled */
3621         TP_ACPI_WANCARD_RESUMECTRL      = 0x04, /* Wan state at resume:
3622                                                    off / last state */
3623 };
3624
3625 #define TPACPI_RFK_WWAN_SW_NAME         "tpacpi_wwan_sw"
3626
3627 static void wan_suspend(pm_message_t state)
3628 {
3629         /* Try to make sure radio will resume powered off */
3630         if (!acpi_evalf(NULL, NULL, "\\WGSV", "qvd",
3631                    TP_ACPI_WGSV_PWR_OFF_ON_RESUME))
3632                 vdbg_printk(TPACPI_DBG_RFKILL,
3633                         "WWAN power down on resume request failed\n");
3634 }
3635
3636 static int wan_get_status(void)
3637 {
3638         int status;
3639
3640 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3641         if (dbg_wwanemul)
3642                 return (tpacpi_wwan_emulstate) ?
3643                        TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
3644 #endif
3645
3646         if (!acpi_evalf(hkey_handle, &status, "GWAN", "d"))
3647                 return -EIO;
3648
3649         return ((status & TP_ACPI_WANCARD_RADIOSSW) != 0) ?
3650                         TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
3651 }
3652
3653 static int wan_set_status(enum tpacpi_rfkill_state state)
3654 {
3655         int status;
3656
3657         vdbg_printk(TPACPI_DBG_RFKILL,
3658                 "will attempt to %s wwan\n",
3659                 (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable");
3660
3661 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3662         if (dbg_wwanemul) {
3663                 tpacpi_wwan_emulstate = (state == TPACPI_RFK_RADIO_ON);
3664                 return 0;
3665         }
3666 #endif
3667
3668         /* We make sure to keep TP_ACPI_WANCARD_RESUMECTRL off */
3669         if (state == TPACPI_RFK_RADIO_ON)
3670                 status = TP_ACPI_WANCARD_RADIOSSW;
3671         else
3672                 status = 0;
3673
3674         if (!acpi_evalf(hkey_handle, NULL, "SWAN", "vd", status))
3675                 return -EIO;
3676
3677         return 0;
3678 }
3679
3680 /* sysfs wan enable ---------------------------------------------------- */
3681 static ssize_t wan_enable_show(struct device *dev,
3682                            struct device_attribute *attr,
3683                            char *buf)
3684 {
3685         return tpacpi_rfk_sysfs_enable_show(TPACPI_RFK_WWAN_SW_ID,
3686                         attr, buf);
3687 }
3688
3689 static ssize_t wan_enable_store(struct device *dev,
3690                             struct device_attribute *attr,
3691                             const char *buf, size_t count)
3692 {
3693         return tpacpi_rfk_sysfs_enable_store(TPACPI_RFK_WWAN_SW_ID,
3694                         attr, buf, count);
3695 }
3696
3697 static struct device_attribute dev_attr_wan_enable =
3698         __ATTR(wwan_enable, S_IWUSR | S_IRUGO,
3699                 wan_enable_show, wan_enable_store);
3700
3701 /* --------------------------------------------------------------------- */
3702
3703 static struct attribute *wan_attributes[] = {
3704         &dev_attr_wan_enable.attr,
3705         NULL
3706 };
3707
3708 static const struct attribute_group wan_attr_group = {
3709         .attrs = wan_attributes,
3710 };
3711
3712 static const struct tpacpi_rfk_ops wan_tprfk_ops = {
3713         .get_status = wan_get_status,
3714         .set_status = wan_set_status,
3715 };
3716
3717 static void wan_shutdown(void)
3718 {
3719         /* Order firmware to save current state to NVRAM */
3720         if (!acpi_evalf(NULL, NULL, "\\WGSV", "vd",
3721                         TP_ACPI_WGSV_SAVE_STATE))
3722                 printk(TPACPI_NOTICE
3723                         "failed to save WWAN state to NVRAM\n");
3724         else
3725                 vdbg_printk(TPACPI_DBG_RFKILL,
3726                         "WWAN state saved to NVRAM\n");
3727 }
3728
3729 static void wan_exit(void)
3730 {
3731         sysfs_remove_group(&tpacpi_pdev->dev.kobj,
3732                 &wan_attr_group);
3733
3734         tpacpi_destroy_rfkill(TPACPI_RFK_WWAN_SW_ID);
3735
3736         wan_shutdown();
3737 }
3738
3739 static int __init wan_init(struct ibm_init_struct *iibm)
3740 {
3741         int res;
3742         int status = 0;
3743
3744         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
3745                         "initializing wan subdriver\n");
3746
3747         TPACPI_ACPIHANDLE_INIT(hkey);
3748
3749         tp_features.wan = hkey_handle &&
3750             acpi_evalf(hkey_handle, &status, "GWAN", "qd");
3751
3752         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
3753                 "wan is %s, status 0x%02x\n",
3754                 str_supported(tp_features.wan),
3755                 status);
3756
3757 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3758         if (dbg_wwanemul) {
3759                 tp_features.wan = 1;
3760                 printk(TPACPI_INFO
3761                         "wwan switch emulation enabled\n");
3762         } else
3763 #endif
3764         if (tp_features.wan &&
3765             !(status & TP_ACPI_WANCARD_HWPRESENT)) {
3766                 /* no wan hardware present in system */
3767                 tp_features.wan = 0;
3768                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
3769                            "wan hardware not installed\n");
3770         }
3771
3772         if (!tp_features.wan)
3773                 return 1;
3774
3775         res = tpacpi_new_rfkill(TPACPI_RFK_WWAN_SW_ID,
3776                                 &wan_tprfk_ops,
3777                                 RFKILL_TYPE_WWAN,
3778                                 TPACPI_RFK_WWAN_SW_NAME,
3779                                 true);
3780         if (res)
3781                 return res;
3782
3783         res = sysfs_create_group(&tpacpi_pdev->dev.kobj,
3784                                 &wan_attr_group);
3785
3786         if (res) {
3787                 tpacpi_destroy_rfkill(TPACPI_RFK_WWAN_SW_ID);
3788                 return res;
3789         }
3790
3791         return 0;
3792 }
3793
3794 /* procfs -------------------------------------------------------------- */
3795 static int wan_read(char *p)
3796 {
3797         return tpacpi_rfk_procfs_read(TPACPI_RFK_WWAN_SW_ID, p);
3798 }
3799
3800 static int wan_write(char *buf)
3801 {
3802         return tpacpi_rfk_procfs_write(TPACPI_RFK_WWAN_SW_ID, buf);
3803 }
3804
3805 static struct ibm_struct wan_driver_data = {
3806         .name = "wan",
3807         .read = wan_read,
3808         .write = wan_write,
3809         .exit = wan_exit,
3810         .suspend = wan_suspend,
3811         .shutdown = wan_shutdown,
3812 };
3813
3814 /*************************************************************************
3815  * UWB subdriver
3816  */
3817
3818 enum {
3819         /* ACPI GUWB/SUWB bits */
3820         TP_ACPI_UWB_HWPRESENT   = 0x01, /* UWB hw available */
3821         TP_ACPI_UWB_RADIOSSW    = 0x02, /* UWB radio enabled */
3822 };
3823
3824 #define TPACPI_RFK_UWB_SW_NAME  "tpacpi_uwb_sw"
3825
3826 static int uwb_get_status(void)
3827 {
3828         int status;
3829
3830 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3831         if (dbg_uwbemul)
3832                 return (tpacpi_uwb_emulstate) ?
3833                        TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
3834 #endif
3835
3836         if (!acpi_evalf(hkey_handle, &status, "GUWB", "d"))
3837                 return -EIO;
3838
3839         return ((status & TP_ACPI_UWB_RADIOSSW) != 0) ?
3840                         TPACPI_RFK_RADIO_ON : TPACPI_RFK_RADIO_OFF;
3841 }
3842
3843 static int uwb_set_status(enum tpacpi_rfkill_state state)
3844 {
3845         int status;
3846
3847         vdbg_printk(TPACPI_DBG_RFKILL,
3848                 "will attempt to %s UWB\n",
3849                 (state == TPACPI_RFK_RADIO_ON) ? "enable" : "disable");
3850
3851 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3852         if (dbg_uwbemul) {
3853                 tpacpi_uwb_emulstate = (state == TPACPI_RFK_RADIO_ON);
3854                 return 0;
3855         }
3856 #endif
3857
3858         if (state == TPACPI_RFK_RADIO_ON)
3859                 status = TP_ACPI_UWB_RADIOSSW;
3860         else
3861                 status = 0;
3862
3863         if (!acpi_evalf(hkey_handle, NULL, "SUWB", "vd", status))
3864                 return -EIO;
3865
3866         return 0;
3867 }
3868
3869 /* --------------------------------------------------------------------- */
3870
3871 static const struct tpacpi_rfk_ops uwb_tprfk_ops = {
3872         .get_status = uwb_get_status,
3873         .set_status = uwb_set_status,
3874 };
3875
3876 static void uwb_exit(void)
3877 {
3878         tpacpi_destroy_rfkill(TPACPI_RFK_UWB_SW_ID);
3879 }
3880
3881 static int __init uwb_init(struct ibm_init_struct *iibm)
3882 {
3883         int res;
3884         int status = 0;
3885
3886         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
3887                         "initializing uwb subdriver\n");
3888
3889         TPACPI_ACPIHANDLE_INIT(hkey);
3890
3891         tp_features.uwb = hkey_handle &&
3892             acpi_evalf(hkey_handle, &status, "GUWB", "qd");
3893
3894         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_RFKILL,
3895                 "uwb is %s, status 0x%02x\n",
3896                 str_supported(tp_features.uwb),
3897                 status);
3898
3899 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
3900         if (dbg_uwbemul) {
3901                 tp_features.uwb = 1;
3902                 printk(TPACPI_INFO
3903                         "uwb switch emulation enabled\n");
3904         } else
3905 #endif
3906         if (tp_features.uwb &&
3907             !(status & TP_ACPI_UWB_HWPRESENT)) {
3908                 /* no uwb hardware present in system */
3909                 tp_features.uwb = 0;
3910                 dbg_printk(TPACPI_DBG_INIT,
3911                            "uwb hardware not installed\n");
3912         }
3913
3914         if (!tp_features.uwb)
3915                 return 1;
3916
3917         res = tpacpi_new_rfkill(TPACPI_RFK_UWB_SW_ID,
3918                                 &uwb_tprfk_ops,
3919                                 RFKILL_TYPE_UWB,
3920                                 TPACPI_RFK_UWB_SW_NAME,
3921                                 false);
3922         return res;
3923 }
3924
3925 static struct ibm_struct uwb_driver_data = {
3926         .name = "uwb",
3927         .exit = uwb_exit,
3928         .flags.experimental = 1,
3929 };
3930
3931 /*************************************************************************
3932  * Video subdriver
3933  */
3934
3935 #ifdef CONFIG_THINKPAD_ACPI_VIDEO
3936
3937 enum video_access_mode {
3938         TPACPI_VIDEO_NONE = 0,
3939         TPACPI_VIDEO_570,       /* 570 */
3940         TPACPI_VIDEO_770,       /* 600e/x, 770e, 770x */
3941         TPACPI_VIDEO_NEW,       /* all others */
3942 };
3943
3944 enum {  /* video status flags, based on VIDEO_570 */
3945         TP_ACPI_VIDEO_S_LCD = 0x01,     /* LCD output enabled */
3946         TP_ACPI_VIDEO_S_CRT = 0x02,     /* CRT output enabled */
3947         TP_ACPI_VIDEO_S_DVI = 0x08,     /* DVI output enabled */
3948 };
3949
3950 enum {  /* TPACPI_VIDEO_570 constants */
3951         TP_ACPI_VIDEO_570_PHSCMD = 0x87,        /* unknown magic constant :( */
3952         TP_ACPI_VIDEO_570_PHSMASK = 0x03,       /* PHS bits that map to
3953                                                  * video_status_flags */
3954         TP_ACPI_VIDEO_570_PHS2CMD = 0x8b,       /* unknown magic constant :( */
3955         TP_ACPI_VIDEO_570_PHS2SET = 0x80,       /* unknown magic constant :( */
3956 };
3957
3958 static enum video_access_mode video_supported;
3959 static int video_orig_autosw;
3960
3961 static int video_autosw_get(void);
3962 static int video_autosw_set(int enable);
3963
3964 TPACPI_HANDLE(vid2, root, "\\_SB.PCI0.AGPB.VID");       /* G41 */
3965
3966 static int __init video_init(struct ibm_init_struct *iibm)
3967 {
3968         int ivga;
3969
3970         vdbg_printk(TPACPI_DBG_INIT, "initializing video subdriver\n");
3971
3972         TPACPI_ACPIHANDLE_INIT(vid);
3973         TPACPI_ACPIHANDLE_INIT(vid2);
3974
3975         if (vid2_handle && acpi_evalf(NULL, &ivga, "\\IVGA", "d") && ivga)
3976                 /* G41, assume IVGA doesn't change */
3977                 vid_handle = vid2_handle;
3978
3979         if (!vid_handle)
3980                 /* video switching not supported on R30, R31 */
3981                 video_supported = TPACPI_VIDEO_NONE;
3982         else if (acpi_evalf(vid_handle, &video_orig_autosw, "SWIT", "qd"))
3983                 /* 570 */
3984                 video_supported = TPACPI_VIDEO_570;
3985         else if (acpi_evalf(vid_handle, &video_orig_autosw, "^VADL", "qd"))
3986                 /* 600e/x, 770e, 770x */
3987                 video_supported = TPACPI_VIDEO_770;
3988         else
3989                 /* all others */
3990                 video_supported = TPACPI_VIDEO_NEW;
3991
3992         vdbg_printk(TPACPI_DBG_INIT, "video is %s, mode %d\n",
3993                 str_supported(video_supported != TPACPI_VIDEO_NONE),
3994                 video_supported);
3995
3996         return (video_supported != TPACPI_VIDEO_NONE)? 0 : 1;
3997 }
3998
3999 static void video_exit(void)
4000 {
4001         dbg_printk(TPACPI_DBG_EXIT,
4002                    "restoring original video autoswitch mode\n");
4003         if (video_autosw_set(video_orig_autosw))
4004                 printk(TPACPI_ERR "error while trying to restore original "
4005                         "video autoswitch mode\n");
4006 }
4007
4008 static int video_outputsw_get(void)
4009 {
4010         int status = 0;
4011         int i;
4012
4013         switch (video_supported) {
4014         case TPACPI_VIDEO_570:
4015                 if (!acpi_evalf(NULL, &i, "\\_SB.PHS", "dd",
4016                                  TP_ACPI_VIDEO_570_PHSCMD))
4017                         return -EIO;
4018                 status = i & TP_ACPI_VIDEO_570_PHSMASK;
4019                 break;
4020         case TPACPI_VIDEO_770:
4021                 if (!acpi_evalf(NULL, &i, "\\VCDL", "d"))
4022                         return -EIO;
4023                 if (i)
4024                         status |= TP_ACPI_VIDEO_S_LCD;
4025                 if (!acpi_evalf(NULL, &i, "\\VCDC", "d"))
4026                         return -EIO;
4027                 if (i)
4028                         status |= TP_ACPI_VIDEO_S_CRT;
4029                 break;
4030         case TPACPI_VIDEO_NEW:
4031                 if (!acpi_evalf(NULL, NULL, "\\VUPS", "vd", 1) ||
4032                     !acpi_evalf(NULL, &i, "\\VCDC", "d"))
4033                         return -EIO;
4034                 if (i)
4035                         status |= TP_ACPI_VIDEO_S_CRT;
4036
4037                 if (!acpi_evalf(NULL, NULL, "\\VUPS", "vd", 0) ||
4038                     !acpi_evalf(NULL, &i, "\\VCDL", "d"))
4039                         return -EIO;
4040                 if (i)
4041                         status |= TP_ACPI_VIDEO_S_LCD;
4042                 if (!acpi_evalf(NULL, &i, "\\VCDD", "d"))
4043                         return -EIO;
4044                 if (i)
4045                         status |= TP_ACPI_VIDEO_S_DVI;
4046                 break;
4047         default:
4048                 return -ENOSYS;
4049         }
4050
4051         return status;
4052 }
4053
4054 static int video_outputsw_set(int status)
4055 {
4056         int autosw;
4057         int res = 0;
4058
4059         switch (video_supported) {
4060         case TPACPI_VIDEO_570:
4061                 res = acpi_evalf(NULL, NULL,
4062                                  "\\_SB.PHS2", "vdd",
4063                                  TP_ACPI_VIDEO_570_PHS2CMD,
4064                                  status | TP_ACPI_VIDEO_570_PHS2SET);
4065                 break;
4066         case TPACPI_VIDEO_770:
4067                 autosw = video_autosw_get();
4068                 if (autosw < 0)
4069                         return autosw;
4070
4071                 res = video_autosw_set(1);
4072                 if (res)
4073                         return res;
4074                 res = acpi_evalf(vid_handle, NULL,
4075                                  "ASWT", "vdd", status * 0x100, 0);
4076                 if (!autosw && video_autosw_set(autosw)) {
4077                         printk(TPACPI_ERR
4078                                "video auto-switch left enabled due to error\n");
4079                         return -EIO;
4080                 }
4081                 break;
4082         case TPACPI_VIDEO_NEW:
4083                 res = acpi_evalf(NULL, NULL, "\\VUPS", "vd", 0x80) &&
4084                       acpi_evalf(NULL, NULL, "\\VSDS", "vdd", status, 1);
4085                 break;
4086         default:
4087                 return -ENOSYS;
4088         }
4089
4090         return (res)? 0 : -EIO;
4091 }
4092
4093 static int video_autosw_get(void)
4094 {
4095         int autosw = 0;
4096
4097         switch (video_supported) {
4098         case TPACPI_VIDEO_570:
4099                 if (!acpi_evalf(vid_handle, &autosw, "SWIT", "d"))
4100                         return -EIO;
4101                 break;
4102         case TPACPI_VIDEO_770:
4103         case TPACPI_VIDEO_NEW:
4104                 if (!acpi_evalf(vid_handle, &autosw, "^VDEE", "d"))
4105                         return -EIO;
4106                 break;
4107         default:
4108                 return -ENOSYS;
4109         }
4110
4111         return autosw & 1;
4112 }
4113
4114 static int video_autosw_set(int enable)
4115 {
4116         if (!acpi_evalf(vid_handle, NULL, "_DOS", "vd", (enable)? 1 : 0))
4117                 return -EIO;
4118         return 0;
4119 }
4120
4121 static int video_outputsw_cycle(void)
4122 {
4123         int autosw = video_autosw_get();
4124         int res;
4125
4126         if (autosw < 0)
4127                 return autosw;
4128
4129         switch (video_supported) {
4130         case TPACPI_VIDEO_570:
4131                 res = video_autosw_set(1);
4132                 if (res)
4133                         return res;
4134                 res = acpi_evalf(ec_handle, NULL, "_Q16", "v");
4135                 break;
4136         case TPACPI_VIDEO_770:
4137         case TPACPI_VIDEO_NEW:
4138                 res = video_autosw_set(1);
4139                 if (res)
4140                         return res;
4141                 res = acpi_evalf(vid_handle, NULL, "VSWT", "v");
4142                 break;
4143         default:
4144                 return -ENOSYS;
4145         }
4146         if (!autosw && video_autosw_set(autosw)) {
4147                 printk(TPACPI_ERR
4148                        "video auto-switch left enabled due to error\n");
4149                 return -EIO;
4150         }
4151
4152         return (res)? 0 : -EIO;
4153 }
4154
4155 static int video_expand_toggle(void)
4156 {
4157         switch (video_supported) {
4158         case TPACPI_VIDEO_570:
4159                 return acpi_evalf(ec_handle, NULL, "_Q17", "v")?
4160                         0 : -EIO;
4161         case TPACPI_VIDEO_770:
4162                 return acpi_evalf(vid_handle, NULL, "VEXP", "v")?
4163                         0 : -EIO;
4164         case TPACPI_VIDEO_NEW:
4165                 return acpi_evalf(NULL, NULL, "\\VEXP", "v")?
4166                         0 : -EIO;
4167         default:
4168                 return -ENOSYS;
4169         }
4170         /* not reached */
4171 }
4172
4173 static int video_read(char *p)
4174 {
4175         int status, autosw;
4176         int len = 0;
4177
4178         if (video_supported == TPACPI_VIDEO_NONE) {
4179                 len += sprintf(p + len, "status:\t\tnot supported\n");
4180                 return len;
4181         }
4182
4183         status = video_outputsw_get();
4184         if (status < 0)
4185                 return status;
4186
4187         autosw = video_autosw_get();
4188         if (autosw < 0)
4189                 return autosw;
4190
4191         len += sprintf(p + len, "status:\t\tsupported\n");
4192         len += sprintf(p + len, "lcd:\t\t%s\n", enabled(status, 0));
4193         len += sprintf(p + len, "crt:\t\t%s\n", enabled(status, 1));
4194         if (video_supported == TPACPI_VIDEO_NEW)
4195                 len += sprintf(p + len, "dvi:\t\t%s\n", enabled(status, 3));
4196         len += sprintf(p + len, "auto:\t\t%s\n", enabled(autosw, 0));
4197         len += sprintf(p + len, "commands:\tlcd_enable, lcd_disable\n");
4198         len += sprintf(p + len, "commands:\tcrt_enable, crt_disable\n");
4199         if (video_supported == TPACPI_VIDEO_NEW)
4200                 len += sprintf(p + len, "commands:\tdvi_enable, dvi_disable\n");
4201         len += sprintf(p + len, "commands:\tauto_enable, auto_disable\n");
4202         len += sprintf(p + len, "commands:\tvideo_switch, expand_toggle\n");
4203
4204         return len;
4205 }
4206
4207 static int video_write(char *buf)
4208 {
4209         char *cmd;
4210         int enable, disable, status;
4211         int res;
4212
4213         if (video_supported == TPACPI_VIDEO_NONE)
4214                 return -ENODEV;
4215
4216         enable = 0;
4217         disable = 0;
4218
4219         while ((cmd = next_cmd(&buf))) {
4220                 if (strlencmp(cmd, "lcd_enable") == 0) {
4221                         enable |= TP_ACPI_VIDEO_S_LCD;
4222                 } else if (strlencmp(cmd, "lcd_disable") == 0) {
4223                         disable |= TP_ACPI_VIDEO_S_LCD;
4224                 } else if (strlencmp(cmd, "crt_enable") == 0) {
4225                         enable |= TP_ACPI_VIDEO_S_CRT;
4226                 } else if (strlencmp(cmd, "crt_disable") == 0) {
4227                         disable |= TP_ACPI_VIDEO_S_CRT;
4228                 } else if (video_supported == TPACPI_VIDEO_NEW &&
4229                            strlencmp(cmd, "dvi_enable") == 0) {
4230                         enable |= TP_ACPI_VIDEO_S_DVI;
4231                 } else if (video_supported == TPACPI_VIDEO_NEW &&
4232                            strlencmp(cmd, "dvi_disable") == 0) {
4233                         disable |= TP_ACPI_VIDEO_S_DVI;
4234                 } else if (strlencmp(cmd, "auto_enable") == 0) {
4235                         res = video_autosw_set(1);
4236                         if (res)
4237                                 return res;
4238                 } else if (strlencmp(cmd, "auto_disable") == 0) {
4239                         res = video_autosw_set(0);
4240                         if (res)
4241                                 return res;
4242                 } else if (strlencmp(cmd, "video_switch") == 0) {
4243                         res = video_outputsw_cycle();
4244                         if (res)
4245                                 return res;
4246                 } else if (strlencmp(cmd, "expand_toggle") == 0) {
4247                         res = video_expand_toggle();
4248                         if (res)
4249                                 return res;
4250                 } else
4251                         return -EINVAL;
4252         }
4253
4254         if (enable || disable) {
4255                 status = video_outputsw_get();
4256                 if (status < 0)
4257                         return status;
4258                 res = video_outputsw_set((status & ~disable) | enable);
4259                 if (res)
4260                         return res;
4261         }
4262
4263         return 0;
4264 }
4265
4266 static struct ibm_struct video_driver_data = {
4267         .name = "video",
4268         .read = video_read,
4269         .write = video_write,
4270         .exit = video_exit,
4271 };
4272
4273 #endif /* CONFIG_THINKPAD_ACPI_VIDEO */
4274
4275 /*************************************************************************
4276  * Light (thinklight) subdriver
4277  */
4278
4279 TPACPI_HANDLE(lght, root, "\\LGHT");    /* A21e, A2xm/p, T20-22, X20-21 */
4280 TPACPI_HANDLE(ledb, ec, "LEDB");                /* G4x */
4281
4282 static int light_get_status(void)
4283 {
4284         int status = 0;
4285
4286         if (tp_features.light_status) {
4287                 if (!acpi_evalf(ec_handle, &status, "KBLT", "d"))
4288                         return -EIO;
4289                 return (!!status);
4290         }
4291
4292         return -ENXIO;
4293 }
4294
4295 static int light_set_status(int status)
4296 {
4297         int rc;
4298
4299         if (tp_features.light) {
4300                 if (cmos_handle) {
4301                         rc = acpi_evalf(cmos_handle, NULL, NULL, "vd",
4302                                         (status)?
4303                                                 TP_CMOS_THINKLIGHT_ON :
4304                                                 TP_CMOS_THINKLIGHT_OFF);
4305                 } else {
4306                         rc = acpi_evalf(lght_handle, NULL, NULL, "vd",
4307                                         (status)? 1 : 0);
4308                 }
4309                 return (rc)? 0 : -EIO;
4310         }
4311
4312         return -ENXIO;
4313 }
4314
4315 static void light_set_status_worker(struct work_struct *work)
4316 {
4317         struct tpacpi_led_classdev *data =
4318                         container_of(work, struct tpacpi_led_classdev, work);
4319
4320         if (likely(tpacpi_lifecycle == TPACPI_LIFE_RUNNING))
4321                 light_set_status((data->new_state != TPACPI_LED_OFF));
4322 }
4323
4324 static void light_sysfs_set(struct led_classdev *led_cdev,
4325                         enum led_brightness brightness)
4326 {
4327         struct tpacpi_led_classdev *data =
4328                 container_of(led_cdev,
4329                              struct tpacpi_led_classdev,
4330                              led_classdev);
4331         data->new_state = (brightness != LED_OFF) ?
4332                                 TPACPI_LED_ON : TPACPI_LED_OFF;
4333         queue_work(tpacpi_wq, &data->work);
4334 }
4335
4336 static enum led_brightness light_sysfs_get(struct led_classdev *led_cdev)
4337 {
4338         return (light_get_status() == 1)? LED_FULL : LED_OFF;
4339 }
4340
4341 static struct tpacpi_led_classdev tpacpi_led_thinklight = {
4342         .led_classdev = {
4343                 .name           = "tpacpi::thinklight",
4344                 .brightness_set = &light_sysfs_set,
4345                 .brightness_get = &light_sysfs_get,
4346         }
4347 };
4348
4349 static int __init light_init(struct ibm_init_struct *iibm)
4350 {
4351         int rc;
4352
4353         vdbg_printk(TPACPI_DBG_INIT, "initializing light subdriver\n");
4354
4355         TPACPI_ACPIHANDLE_INIT(ledb);
4356         TPACPI_ACPIHANDLE_INIT(lght);
4357         TPACPI_ACPIHANDLE_INIT(cmos);
4358         INIT_WORK(&tpacpi_led_thinklight.work, light_set_status_worker);
4359
4360         /* light not supported on 570, 600e/x, 770e, 770x, G4x, R30, R31 */
4361         tp_features.light = (cmos_handle || lght_handle) && !ledb_handle;
4362
4363         if (tp_features.light)
4364                 /* light status not supported on
4365                    570, 600e/x, 770e, 770x, G4x, R30, R31, R32, X20 */
4366                 tp_features.light_status =
4367                         acpi_evalf(ec_handle, NULL, "KBLT", "qv");
4368
4369         vdbg_printk(TPACPI_DBG_INIT, "light is %s, light status is %s\n",
4370                 str_supported(tp_features.light),
4371                 str_supported(tp_features.light_status));
4372
4373         if (!tp_features.light)
4374                 return 1;
4375
4376         rc = led_classdev_register(&tpacpi_pdev->dev,
4377                                    &tpacpi_led_thinklight.led_classdev);
4378
4379         if (rc < 0) {
4380                 tp_features.light = 0;
4381                 tp_features.light_status = 0;
4382         } else  {
4383                 rc = 0;
4384         }
4385
4386         return rc;
4387 }
4388
4389 static void light_exit(void)
4390 {
4391         led_classdev_unregister(&tpacpi_led_thinklight.led_classdev);
4392         if (work_pending(&tpacpi_led_thinklight.work))
4393                 flush_workqueue(tpacpi_wq);
4394 }
4395
4396 static int light_read(char *p)
4397 {
4398         int len = 0;
4399         int status;
4400
4401         if (!tp_features.light) {
4402                 len += sprintf(p + len, "status:\t\tnot supported\n");
4403         } else if (!tp_features.light_status) {
4404                 len += sprintf(p + len, "status:\t\tunknown\n");
4405                 len += sprintf(p + len, "commands:\ton, off\n");
4406         } else {
4407                 status = light_get_status();
4408                 if (status < 0)
4409                         return status;
4410                 len += sprintf(p + len, "status:\t\t%s\n", onoff(status, 0));
4411                 len += sprintf(p + len, "commands:\ton, off\n");
4412         }
4413
4414         return len;
4415 }
4416
4417 static int light_write(char *buf)
4418 {
4419         char *cmd;
4420         int newstatus = 0;
4421
4422         if (!tp_features.light)
4423                 return -ENODEV;
4424
4425         while ((cmd = next_cmd(&buf))) {
4426                 if (strlencmp(cmd, "on") == 0) {
4427                         newstatus = 1;
4428                 } else if (strlencmp(cmd, "off") == 0) {
4429                         newstatus = 0;
4430                 } else
4431                         return -EINVAL;
4432         }
4433
4434         return light_set_status(newstatus);
4435 }
4436
4437 static struct ibm_struct light_driver_data = {
4438         .name = "light",
4439         .read = light_read,
4440         .write = light_write,
4441         .exit = light_exit,
4442 };
4443
4444 /*************************************************************************
4445  * Dock subdriver
4446  */
4447
4448 #ifdef CONFIG_THINKPAD_ACPI_DOCK
4449
4450 static void dock_notify(struct ibm_struct *ibm, u32 event);
4451 static int dock_read(char *p);
4452 static int dock_write(char *buf);
4453
4454 TPACPI_HANDLE(dock, root, "\\_SB.GDCK", /* X30, X31, X40 */
4455            "\\_SB.PCI0.DOCK",   /* 600e/x,770e,770x,A2xm/p,T20-22,X20-21 */
4456            "\\_SB.PCI0.PCI1.DOCK",      /* all others */
4457            "\\_SB.PCI.ISA.SLCE",        /* 570 */
4458     );                          /* A21e,G4x,R30,R31,R32,R40,R40e,R50e */
4459
4460 /* don't list other alternatives as we install a notify handler on the 570 */
4461 TPACPI_HANDLE(pci, root, "\\_SB.PCI");  /* 570 */
4462
4463 static const struct acpi_device_id ibm_pci_device_ids[] = {
4464         {PCI_ROOT_HID_STRING, 0},
4465         {"", 0},
4466 };
4467
4468 static struct tp_acpi_drv_struct ibm_dock_acpidriver[2] = {
4469         {
4470          .notify = dock_notify,
4471          .handle = &dock_handle,
4472          .type = ACPI_SYSTEM_NOTIFY,
4473         },
4474         {
4475         /* THIS ONE MUST NEVER BE USED FOR DRIVER AUTOLOADING.
4476          * We just use it to get notifications of dock hotplug
4477          * in very old thinkpads */
4478          .hid = ibm_pci_device_ids,
4479          .notify = dock_notify,
4480          .handle = &pci_handle,
4481          .type = ACPI_SYSTEM_NOTIFY,
4482         },
4483 };
4484
4485 static struct ibm_struct dock_driver_data[2] = {
4486         {
4487          .name = "dock",
4488          .read = dock_read,
4489          .write = dock_write,
4490          .acpi = &ibm_dock_acpidriver[0],
4491         },
4492         {
4493          .name = "dock",
4494          .acpi = &ibm_dock_acpidriver[1],
4495         },
4496 };
4497
4498 #define dock_docked() (_sta(dock_handle) & 1)
4499
4500 static int __init dock_init(struct ibm_init_struct *iibm)
4501 {
4502         vdbg_printk(TPACPI_DBG_INIT, "initializing dock subdriver\n");
4503
4504         TPACPI_ACPIHANDLE_INIT(dock);
4505
4506         vdbg_printk(TPACPI_DBG_INIT, "dock is %s\n",
4507                 str_supported(dock_handle != NULL));
4508
4509         return (dock_handle)? 0 : 1;
4510 }
4511
4512 static int __init dock_init2(struct ibm_init_struct *iibm)
4513 {
4514         int dock2_needed;
4515
4516         vdbg_printk(TPACPI_DBG_INIT, "initializing dock subdriver part 2\n");
4517
4518         if (dock_driver_data[0].flags.acpi_driver_registered &&
4519             dock_driver_data[0].flags.acpi_notify_installed) {
4520                 TPACPI_ACPIHANDLE_INIT(pci);
4521                 dock2_needed = (pci_handle != NULL);
4522                 vdbg_printk(TPACPI_DBG_INIT,
4523                             "dock PCI handler for the TP 570 is %s\n",
4524                             str_supported(dock2_needed));
4525         } else {
4526                 vdbg_printk(TPACPI_DBG_INIT,
4527                 "dock subdriver part 2 not required\n");
4528                 dock2_needed = 0;
4529         }
4530
4531         return (dock2_needed)? 0 : 1;
4532 }
4533
4534 static void dock_notify(struct ibm_struct *ibm, u32 event)
4535 {
4536         int docked = dock_docked();
4537         int pci = ibm->acpi->hid && ibm->acpi->device &&
4538                 acpi_match_device_ids(ibm->acpi->device, ibm_pci_device_ids);
4539         int data;
4540
4541         if (event == 1 && !pci) /* 570 */
4542                 data = 1;       /* button */
4543         else if (event == 1 && pci)     /* 570 */
4544                 data = 3;       /* dock */
4545         else if (event == 3 && docked)
4546                 data = 1;       /* button */
4547         else if (event == 3 && !docked)
4548                 data = 2;       /* undock */
4549         else if (event == 0 && docked)
4550                 data = 3;       /* dock */
4551         else {
4552                 printk(TPACPI_ERR "unknown dock event %d, status %d\n",
4553                        event, _sta(dock_handle));
4554                 data = 0;       /* unknown */
4555         }
4556         acpi_bus_generate_proc_event(ibm->acpi->device, event, data);
4557         acpi_bus_generate_netlink_event(ibm->acpi->device->pnp.device_class,
4558                                           dev_name(&ibm->acpi->device->dev),
4559                                           event, data);
4560 }
4561
4562 static int dock_read(char *p)
4563 {
4564         int len = 0;
4565         int docked = dock_docked();
4566
4567         if (!dock_handle)
4568                 len += sprintf(p + len, "status:\t\tnot supported\n");
4569         else if (!docked)
4570                 len += sprintf(p + len, "status:\t\tundocked\n");
4571         else {
4572                 len += sprintf(p + len, "status:\t\tdocked\n");
4573                 len += sprintf(p + len, "commands:\tdock, undock\n");
4574         }
4575
4576         return len;
4577 }
4578
4579 static int dock_write(char *buf)
4580 {
4581         char *cmd;
4582
4583         if (!dock_docked())
4584                 return -ENODEV;
4585
4586         while ((cmd = next_cmd(&buf))) {
4587                 if (strlencmp(cmd, "undock") == 0) {
4588                         if (!acpi_evalf(dock_handle, NULL, "_DCK", "vd", 0) ||
4589                             !acpi_evalf(dock_handle, NULL, "_EJ0", "vd", 1))
4590                                 return -EIO;
4591                 } else if (strlencmp(cmd, "dock") == 0) {
4592                         if (!acpi_evalf(dock_handle, NULL, "_DCK", "vd", 1))
4593                                 return -EIO;
4594                 } else
4595                         return -EINVAL;
4596         }
4597
4598         return 0;
4599 }
4600
4601 #endif /* CONFIG_THINKPAD_ACPI_DOCK */
4602
4603 /*************************************************************************
4604  * Bay subdriver
4605  */
4606
4607 #ifdef CONFIG_THINKPAD_ACPI_BAY
4608
4609 TPACPI_HANDLE(bay, root, "\\_SB.PCI.IDE.SECN.MAST",     /* 570 */
4610            "\\_SB.PCI0.IDE0.IDES.IDSM", /* 600e/x, 770e, 770x */
4611            "\\_SB.PCI0.SATA.SCND.MSTR", /* T60, X60, Z60 */
4612            "\\_SB.PCI0.IDE0.SCND.MSTR", /* all others */
4613            );                           /* A21e, R30, R31 */
4614 TPACPI_HANDLE(bay_ej, bay, "_EJ3",      /* 600e/x, A2xm/p, A3x */
4615            "_EJ0",              /* all others */
4616            );                   /* 570,A21e,G4x,R30,R31,R32,R40e,R50e */
4617 TPACPI_HANDLE(bay2, root, "\\_SB.PCI0.IDE0.PRIM.SLAV",  /* A3x, R32 */
4618            "\\_SB.PCI0.IDE0.IDEP.IDPS", /* 600e/x, 770e, 770x */
4619            );                           /* all others */
4620 TPACPI_HANDLE(bay2_ej, bay2, "_EJ3",    /* 600e/x, 770e, A3x */
4621            "_EJ0",                      /* 770x */
4622            );                           /* all others */
4623
4624 static int __init bay_init(struct ibm_init_struct *iibm)
4625 {
4626         vdbg_printk(TPACPI_DBG_INIT, "initializing bay subdriver\n");
4627
4628         TPACPI_ACPIHANDLE_INIT(bay);
4629         if (bay_handle)
4630                 TPACPI_ACPIHANDLE_INIT(bay_ej);
4631         TPACPI_ACPIHANDLE_INIT(bay2);
4632         if (bay2_handle)
4633                 TPACPI_ACPIHANDLE_INIT(bay2_ej);
4634
4635         tp_features.bay_status = bay_handle &&
4636                 acpi_evalf(bay_handle, NULL, "_STA", "qv");
4637         tp_features.bay_status2 = bay2_handle &&
4638                 acpi_evalf(bay2_handle, NULL, "_STA", "qv");
4639
4640         tp_features.bay_eject = bay_handle && bay_ej_handle &&
4641                 (strlencmp(bay_ej_path, "_EJ0") == 0 || experimental);
4642         tp_features.bay_eject2 = bay2_handle && bay2_ej_handle &&
4643                 (strlencmp(bay2_ej_path, "_EJ0") == 0 || experimental);
4644
4645         vdbg_printk(TPACPI_DBG_INIT,
4646                 "bay 1: status %s, eject %s; bay 2: status %s, eject %s\n",
4647                 str_supported(tp_features.bay_status),
4648                 str_supported(tp_features.bay_eject),
4649                 str_supported(tp_features.bay_status2),
4650                 str_supported(tp_features.bay_eject2));
4651
4652         return (tp_features.bay_status || tp_features.bay_eject ||
4653                 tp_features.bay_status2 || tp_features.bay_eject2)? 0 : 1;
4654 }
4655
4656 static void bay_notify(struct ibm_struct *ibm, u32 event)
4657 {
4658         acpi_bus_generate_proc_event(ibm->acpi->device, event, 0);
4659         acpi_bus_generate_netlink_event(ibm->acpi->device->pnp.device_class,
4660                                           dev_name(&ibm->acpi->device->dev),
4661                                           event, 0);
4662 }
4663
4664 #define bay_occupied(b) (_sta(b##_handle) & 1)
4665
4666 static int bay_read(char *p)
4667 {
4668         int len = 0;
4669         int occupied = bay_occupied(bay);
4670         int occupied2 = bay_occupied(bay2);
4671         int eject, eject2;
4672
4673         len += sprintf(p + len, "status:\t\t%s\n",
4674                 tp_features.bay_status ?
4675                         (occupied ? "occupied" : "unoccupied") :
4676                                 "not supported");
4677         if (tp_features.bay_status2)
4678                 len += sprintf(p + len, "status2:\t%s\n", occupied2 ?
4679                                "occupied" : "unoccupied");
4680
4681         eject = tp_features.bay_eject && occupied;
4682         eject2 = tp_features.bay_eject2 && occupied2;
4683
4684         if (eject && eject2)
4685                 len += sprintf(p + len, "commands:\teject, eject2\n");
4686         else if (eject)
4687                 len += sprintf(p + len, "commands:\teject\n");
4688         else if (eject2)
4689                 len += sprintf(p + len, "commands:\teject2\n");
4690
4691         return len;
4692 }
4693
4694 static int bay_write(char *buf)
4695 {
4696         char *cmd;
4697
4698         if (!tp_features.bay_eject && !tp_features.bay_eject2)
4699                 return -ENODEV;
4700
4701         while ((cmd = next_cmd(&buf))) {
4702                 if (tp_features.bay_eject && strlencmp(cmd, "eject") == 0) {
4703                         if (!acpi_evalf(bay_ej_handle, NULL, NULL, "vd", 1))
4704                                 return -EIO;
4705                 } else if (tp_features.bay_eject2 &&
4706                            strlencmp(cmd, "eject2") == 0) {
4707                         if (!acpi_evalf(bay2_ej_handle, NULL, NULL, "vd", 1))
4708                                 return -EIO;
4709                 } else
4710                         return -EINVAL;
4711         }
4712
4713         return 0;
4714 }
4715
4716 static struct tp_acpi_drv_struct ibm_bay_acpidriver = {
4717         .notify = bay_notify,
4718         .handle = &bay_handle,
4719         .type = ACPI_SYSTEM_NOTIFY,
4720 };
4721
4722 static struct ibm_struct bay_driver_data = {
4723         .name = "bay",
4724         .read = bay_read,
4725         .write = bay_write,
4726         .acpi = &ibm_bay_acpidriver,
4727 };
4728
4729 #endif /* CONFIG_THINKPAD_ACPI_BAY */
4730
4731 /*************************************************************************
4732  * CMOS subdriver
4733  */
4734
4735 /* sysfs cmos_command -------------------------------------------------- */
4736 static ssize_t cmos_command_store(struct device *dev,
4737                             struct device_attribute *attr,
4738                             const char *buf, size_t count)
4739 {
4740         unsigned long cmos_cmd;
4741         int res;
4742
4743         if (parse_strtoul(buf, 21, &cmos_cmd))
4744                 return -EINVAL;
4745
4746         res = issue_thinkpad_cmos_command(cmos_cmd);
4747         return (res)? res : count;
4748 }
4749
4750 static struct device_attribute dev_attr_cmos_command =
4751         __ATTR(cmos_command, S_IWUSR, NULL, cmos_command_store);
4752
4753 /* --------------------------------------------------------------------- */
4754
4755 static int __init cmos_init(struct ibm_init_struct *iibm)
4756 {
4757         int res;
4758
4759         vdbg_printk(TPACPI_DBG_INIT,
4760                 "initializing cmos commands subdriver\n");
4761
4762         TPACPI_ACPIHANDLE_INIT(cmos);
4763
4764         vdbg_printk(TPACPI_DBG_INIT, "cmos commands are %s\n",
4765                 str_supported(cmos_handle != NULL));
4766
4767         res = device_create_file(&tpacpi_pdev->dev, &dev_attr_cmos_command);
4768         if (res)
4769                 return res;
4770
4771         return (cmos_handle)? 0 : 1;
4772 }
4773
4774 static void cmos_exit(void)
4775 {
4776         device_remove_file(&tpacpi_pdev->dev, &dev_attr_cmos_command);
4777 }
4778
4779 static int cmos_read(char *p)
4780 {
4781         int len = 0;
4782
4783         /* cmos not supported on 570, 600e/x, 770e, 770x, A21e, A2xm/p,
4784            R30, R31, T20-22, X20-21 */
4785         if (!cmos_handle)
4786                 len += sprintf(p + len, "status:\t\tnot supported\n");
4787         else {
4788                 len += sprintf(p + len, "status:\t\tsupported\n");
4789                 len += sprintf(p + len, "commands:\t<cmd> (<cmd> is 0-21)\n");
4790         }
4791
4792         return len;
4793 }
4794
4795 static int cmos_write(char *buf)
4796 {
4797         char *cmd;
4798         int cmos_cmd, res;
4799
4800         while ((cmd = next_cmd(&buf))) {
4801                 if (sscanf(cmd, "%u", &cmos_cmd) == 1 &&
4802                     cmos_cmd >= 0 && cmos_cmd <= 21) {
4803                         /* cmos_cmd set */
4804                 } else
4805                         return -EINVAL;
4806
4807                 res = issue_thinkpad_cmos_command(cmos_cmd);
4808                 if (res)
4809                         return res;
4810         }
4811
4812         return 0;
4813 }
4814
4815 static struct ibm_struct cmos_driver_data = {
4816         .name = "cmos",
4817         .read = cmos_read,
4818         .write = cmos_write,
4819         .exit = cmos_exit,
4820 };
4821
4822 /*************************************************************************
4823  * LED subdriver
4824  */
4825
4826 enum led_access_mode {
4827         TPACPI_LED_NONE = 0,
4828         TPACPI_LED_570, /* 570 */
4829         TPACPI_LED_OLD, /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20-21 */
4830         TPACPI_LED_NEW, /* all others */
4831 };
4832
4833 enum {  /* For TPACPI_LED_OLD */
4834         TPACPI_LED_EC_HLCL = 0x0c,      /* EC reg to get led to power on */
4835         TPACPI_LED_EC_HLBL = 0x0d,      /* EC reg to blink a lit led */
4836         TPACPI_LED_EC_HLMS = 0x0e,      /* EC reg to select led to command */
4837 };
4838
4839 static enum led_access_mode led_supported;
4840
4841 TPACPI_HANDLE(led, ec, "SLED",  /* 570 */
4842            "SYSL",              /* 600e/x, 770e, 770x, A21e, A2xm/p, */
4843                                 /* T20-22, X20-21 */
4844            "LED",               /* all others */
4845            );                   /* R30, R31 */
4846
4847 #define TPACPI_LED_NUMLEDS 16
4848 static struct tpacpi_led_classdev *tpacpi_leds;
4849 static enum led_status_t tpacpi_led_state_cache[TPACPI_LED_NUMLEDS];
4850 static const char * const tpacpi_led_names[TPACPI_LED_NUMLEDS] = {
4851         /* there's a limit of 19 chars + NULL before 2.6.26 */
4852         "tpacpi::power",
4853         "tpacpi:orange:batt",
4854         "tpacpi:green:batt",
4855         "tpacpi::dock_active",
4856         "tpacpi::bay_active",
4857         "tpacpi::dock_batt",
4858         "tpacpi::unknown_led",
4859         "tpacpi::standby",
4860         "tpacpi::dock_status1",
4861         "tpacpi::dock_status2",
4862         "tpacpi::unknown_led2",
4863         "tpacpi::unknown_led3",
4864         "tpacpi::thinkvantage",
4865 };
4866 #define TPACPI_SAFE_LEDS        0x1081U
4867
4868 static inline bool tpacpi_is_led_restricted(const unsigned int led)
4869 {
4870 #ifdef CONFIG_THINKPAD_ACPI_UNSAFE_LEDS
4871         return false;
4872 #else
4873         return (1U & (TPACPI_SAFE_LEDS >> led)) == 0;
4874 #endif
4875 }
4876
4877 static int led_get_status(const unsigned int led)
4878 {
4879         int status;
4880         enum led_status_t led_s;
4881
4882         switch (led_supported) {
4883         case TPACPI_LED_570:
4884                 if (!acpi_evalf(ec_handle,
4885                                 &status, "GLED", "dd", 1 << led))
4886                         return -EIO;
4887                 led_s = (status == 0)?
4888                                 TPACPI_LED_OFF :
4889                                 ((status == 1)?
4890                                         TPACPI_LED_ON :
4891                                         TPACPI_LED_BLINK);
4892                 tpacpi_led_state_cache[led] = led_s;
4893                 return led_s;
4894         default:
4895                 return -ENXIO;
4896         }
4897
4898         /* not reached */
4899 }
4900
4901 static int led_set_status(const unsigned int led,
4902                           const enum led_status_t ledstatus)
4903 {
4904         /* off, on, blink. Index is led_status_t */
4905         static const unsigned int led_sled_arg1[] = { 0, 1, 3 };
4906         static const unsigned int led_led_arg1[] = { 0, 0x80, 0xc0 };
4907
4908         int rc = 0;
4909
4910         switch (led_supported) {
4911         case TPACPI_LED_570:
4912                 /* 570 */
4913                 if (unlikely(led > 7))
4914                         return -EINVAL;
4915                 if (unlikely(tpacpi_is_led_restricted(led)))
4916                         return -EPERM;
4917                 if (!acpi_evalf(led_handle, NULL, NULL, "vdd",
4918                                 (1 << led), led_sled_arg1[ledstatus]))
4919                         rc = -EIO;
4920                 break;
4921         case TPACPI_LED_OLD:
4922                 /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20 */
4923                 if (unlikely(led > 7))
4924                         return -EINVAL;
4925                 if (unlikely(tpacpi_is_led_restricted(led)))
4926                         return -EPERM;
4927                 rc = ec_write(TPACPI_LED_EC_HLMS, (1 << led));
4928                 if (rc >= 0)
4929                         rc = ec_write(TPACPI_LED_EC_HLBL,
4930                                       (ledstatus == TPACPI_LED_BLINK) << led);
4931                 if (rc >= 0)
4932                         rc = ec_write(TPACPI_LED_EC_HLCL,
4933                                       (ledstatus != TPACPI_LED_OFF) << led);
4934                 break;
4935         case TPACPI_LED_NEW:
4936                 /* all others */
4937                 if (unlikely(led >= TPACPI_LED_NUMLEDS))
4938                         return -EINVAL;
4939                 if (unlikely(tpacpi_is_led_restricted(led)))
4940                         return -EPERM;
4941                 if (!acpi_evalf(led_handle, NULL, NULL, "vdd",
4942                                 led, led_led_arg1[ledstatus]))
4943                         rc = -EIO;
4944                 break;
4945         default:
4946                 rc = -ENXIO;
4947         }
4948
4949         if (!rc)
4950                 tpacpi_led_state_cache[led] = ledstatus;
4951
4952         return rc;
4953 }
4954
4955 static void led_set_status_worker(struct work_struct *work)
4956 {
4957         struct tpacpi_led_classdev *data =
4958                 container_of(work, struct tpacpi_led_classdev, work);
4959
4960         if (likely(tpacpi_lifecycle == TPACPI_LIFE_RUNNING))
4961                 led_set_status(data->led, data->new_state);
4962 }
4963
4964 static void led_sysfs_set(struct led_classdev *led_cdev,
4965                         enum led_brightness brightness)
4966 {
4967         struct tpacpi_led_classdev *data = container_of(led_cdev,
4968                              struct tpacpi_led_classdev, led_classdev);
4969
4970         if (brightness == LED_OFF)
4971                 data->new_state = TPACPI_LED_OFF;
4972         else if (tpacpi_led_state_cache[data->led] != TPACPI_LED_BLINK)
4973                 data->new_state = TPACPI_LED_ON;
4974         else
4975                 data->new_state = TPACPI_LED_BLINK;
4976
4977         queue_work(tpacpi_wq, &data->work);
4978 }
4979
4980 static int led_sysfs_blink_set(struct led_classdev *led_cdev,
4981                         unsigned long *delay_on, unsigned long *delay_off)
4982 {
4983         struct tpacpi_led_classdev *data = container_of(led_cdev,
4984                              struct tpacpi_led_classdev, led_classdev);
4985
4986         /* Can we choose the flash rate? */
4987         if (*delay_on == 0 && *delay_off == 0) {
4988                 /* yes. set them to the hardware blink rate (1 Hz) */
4989                 *delay_on = 500; /* ms */
4990                 *delay_off = 500; /* ms */
4991         } else if ((*delay_on != 500) || (*delay_off != 500))
4992                 return -EINVAL;
4993
4994         data->new_state = TPACPI_LED_BLINK;
4995         queue_work(tpacpi_wq, &data->work);
4996
4997         return 0;
4998 }
4999
5000 static enum led_brightness led_sysfs_get(struct led_classdev *led_cdev)
5001 {
5002         int rc;
5003
5004         struct tpacpi_led_classdev *data = container_of(led_cdev,
5005                              struct tpacpi_led_classdev, led_classdev);
5006
5007         rc = led_get_status(data->led);
5008
5009         if (rc == TPACPI_LED_OFF || rc < 0)
5010                 rc = LED_OFF;   /* no error handling in led class :( */
5011         else
5012                 rc = LED_FULL;
5013
5014         return rc;
5015 }
5016
5017 static void led_exit(void)
5018 {
5019         unsigned int i;
5020
5021         for (i = 0; i < TPACPI_LED_NUMLEDS; i++) {
5022                 if (tpacpi_leds[i].led_classdev.name)
5023                         led_classdev_unregister(&tpacpi_leds[i].led_classdev);
5024         }
5025
5026         kfree(tpacpi_leds);
5027 }
5028
5029 static int __init tpacpi_init_led(unsigned int led)
5030 {
5031         int rc;
5032
5033         tpacpi_leds[led].led = led;
5034
5035         /* LEDs with no name don't get registered */
5036         if (!tpacpi_led_names[led])
5037                 return 0;
5038
5039         tpacpi_leds[led].led_classdev.brightness_set = &led_sysfs_set;
5040         tpacpi_leds[led].led_classdev.blink_set = &led_sysfs_blink_set;
5041         if (led_supported == TPACPI_LED_570)
5042                 tpacpi_leds[led].led_classdev.brightness_get =
5043                                                 &led_sysfs_get;
5044
5045         tpacpi_leds[led].led_classdev.name = tpacpi_led_names[led];
5046
5047         INIT_WORK(&tpacpi_leds[led].work, led_set_status_worker);
5048
5049         rc = led_classdev_register(&tpacpi_pdev->dev,
5050                                 &tpacpi_leds[led].led_classdev);
5051         if (rc < 0)
5052                 tpacpi_leds[led].led_classdev.name = NULL;
5053
5054         return rc;
5055 }
5056
5057 static const struct tpacpi_quirk led_useful_qtable[] __initconst = {
5058         TPACPI_Q_IBM('1', 'E', 0x009f), /* A30 */
5059         TPACPI_Q_IBM('1', 'N', 0x009f), /* A31 */
5060         TPACPI_Q_IBM('1', 'G', 0x009f), /* A31 */
5061
5062         TPACPI_Q_IBM('1', 'I', 0x0097), /* T30 */
5063         TPACPI_Q_IBM('1', 'R', 0x0097), /* T40, T41, T42, R50, R51 */
5064         TPACPI_Q_IBM('7', '0', 0x0097), /* T43, R52 */
5065         TPACPI_Q_IBM('1', 'Y', 0x0097), /* T43 */
5066         TPACPI_Q_IBM('1', 'W', 0x0097), /* R50e */
5067         TPACPI_Q_IBM('1', 'V', 0x0097), /* R51 */
5068         TPACPI_Q_IBM('7', '8', 0x0097), /* R51e */
5069         TPACPI_Q_IBM('7', '6', 0x0097), /* R52 */
5070
5071         TPACPI_Q_IBM('1', 'K', 0x00bf), /* X30 */
5072         TPACPI_Q_IBM('1', 'Q', 0x00bf), /* X31, X32 */
5073         TPACPI_Q_IBM('1', 'U', 0x00bf), /* X40 */
5074         TPACPI_Q_IBM('7', '4', 0x00bf), /* X41 */
5075         TPACPI_Q_IBM('7', '5', 0x00bf), /* X41t */
5076
5077         TPACPI_Q_IBM('7', '9', 0x1f97), /* T60 (1) */
5078         TPACPI_Q_IBM('7', '7', 0x1f97), /* Z60* (1) */
5079         TPACPI_Q_IBM('7', 'F', 0x1f97), /* Z61* (1) */
5080         TPACPI_Q_IBM('7', 'B', 0x1fb7), /* X60 (1) */
5081
5082         /* (1) - may have excess leds enabled on MSB */
5083
5084         /* Defaults (order matters, keep last, don't reorder!) */
5085         { /* Lenovo */
5086           .vendor = PCI_VENDOR_ID_LENOVO,
5087           .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_ANY,
5088           .quirks = 0x1fffU,
5089         },
5090         { /* IBM ThinkPads with no EC version string */
5091           .vendor = PCI_VENDOR_ID_IBM,
5092           .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_UNKNOWN,
5093           .quirks = 0x00ffU,
5094         },
5095         { /* IBM ThinkPads with EC version string */
5096           .vendor = PCI_VENDOR_ID_IBM,
5097           .bios = TPACPI_MATCH_ANY, .ec = TPACPI_MATCH_ANY,
5098           .quirks = 0x00bfU,
5099         },
5100 };
5101
5102 #undef TPACPI_LEDQ_IBM
5103 #undef TPACPI_LEDQ_LNV
5104
5105 static int __init led_init(struct ibm_init_struct *iibm)
5106 {
5107         unsigned int i;
5108         int rc;
5109         unsigned long useful_leds;
5110
5111         vdbg_printk(TPACPI_DBG_INIT, "initializing LED subdriver\n");
5112
5113         TPACPI_ACPIHANDLE_INIT(led);
5114
5115         if (!led_handle)
5116                 /* led not supported on R30, R31 */
5117                 led_supported = TPACPI_LED_NONE;
5118         else if (strlencmp(led_path, "SLED") == 0)
5119                 /* 570 */
5120                 led_supported = TPACPI_LED_570;
5121         else if (strlencmp(led_path, "SYSL") == 0)
5122                 /* 600e/x, 770e, 770x, A21e, A2xm/p, T20-22, X20-21 */
5123                 led_supported = TPACPI_LED_OLD;
5124         else
5125                 /* all others */
5126                 led_supported = TPACPI_LED_NEW;
5127
5128         vdbg_printk(TPACPI_DBG_INIT, "LED commands are %s, mode %d\n",
5129                 str_supported(led_supported), led_supported);
5130
5131         if (led_supported == TPACPI_LED_NONE)
5132                 return 1;
5133
5134         tpacpi_leds = kzalloc(sizeof(*tpacpi_leds) * TPACPI_LED_NUMLEDS,
5135                               GFP_KERNEL);
5136         if (!tpacpi_leds) {
5137                 printk(TPACPI_ERR "Out of memory for LED data\n");
5138                 return -ENOMEM;
5139         }
5140
5141         useful_leds = tpacpi_check_quirks(led_useful_qtable,
5142                                           ARRAY_SIZE(led_useful_qtable));
5143
5144         for (i = 0; i < TPACPI_LED_NUMLEDS; i++) {
5145                 if (!tpacpi_is_led_restricted(i) &&
5146                     test_bit(i, &useful_leds)) {
5147                         rc = tpacpi_init_led(i);
5148                         if (rc < 0) {
5149                                 led_exit();
5150                                 return rc;
5151                         }
5152                 }
5153         }
5154
5155 #ifdef CONFIG_THINKPAD_ACPI_UNSAFE_LEDS
5156         printk(TPACPI_NOTICE
5157                 "warning: userspace override of important "
5158                 "firmware LEDs is enabled\n");
5159 #endif
5160         return 0;
5161 }
5162
5163 #define str_led_status(s) \
5164         ((s) == TPACPI_LED_OFF ? "off" : \
5165                 ((s) == TPACPI_LED_ON ? "on" : "blinking"))
5166
5167 static int led_read(char *p)
5168 {
5169         int len = 0;
5170
5171         if (!led_supported) {
5172                 len += sprintf(p + len, "status:\t\tnot supported\n");
5173                 return len;
5174         }
5175         len += sprintf(p + len, "status:\t\tsupported\n");
5176
5177         if (led_supported == TPACPI_LED_570) {
5178                 /* 570 */
5179                 int i, status;
5180                 for (i = 0; i < 8; i++) {
5181                         status = led_get_status(i);
5182                         if (status < 0)
5183                                 return -EIO;
5184                         len += sprintf(p + len, "%d:\t\t%s\n",
5185                                        i, str_led_status(status));
5186                 }
5187         }
5188
5189         len += sprintf(p + len, "commands:\t"
5190                        "<led> on, <led> off, <led> blink (<led> is 0-15)\n");
5191
5192         return len;
5193 }
5194
5195 static int led_write(char *buf)
5196 {
5197         char *cmd;
5198         int led, rc;
5199         enum led_status_t s;
5200
5201         if (!led_supported)
5202                 return -ENODEV;
5203
5204         while ((cmd = next_cmd(&buf))) {
5205                 if (sscanf(cmd, "%d", &led) != 1 || led < 0 || led > 15)
5206                         return -EINVAL;
5207
5208                 if (strstr(cmd, "off")) {
5209                         s = TPACPI_LED_OFF;
5210                 } else if (strstr(cmd, "on")) {
5211                         s = TPACPI_LED_ON;
5212                 } else if (strstr(cmd, "blink")) {
5213                         s = TPACPI_LED_BLINK;
5214                 } else {
5215                         return -EINVAL;
5216                 }
5217
5218                 rc = led_set_status(led, s);
5219                 if (rc < 0)
5220                         return rc;
5221         }
5222
5223         return 0;
5224 }
5225
5226 static struct ibm_struct led_driver_data = {
5227         .name = "led",
5228         .read = led_read,
5229         .write = led_write,
5230         .exit = led_exit,
5231 };
5232
5233 /*************************************************************************
5234  * Beep subdriver
5235  */
5236
5237 TPACPI_HANDLE(beep, ec, "BEEP");        /* all except R30, R31 */
5238
5239 #define TPACPI_BEEP_Q1 0x0001
5240
5241 static const struct tpacpi_quirk beep_quirk_table[] __initconst = {
5242         TPACPI_Q_IBM('I', 'M', TPACPI_BEEP_Q1), /* 570 */
5243         TPACPI_Q_IBM('I', 'U', TPACPI_BEEP_Q1), /* 570E - unverified */
5244 };
5245
5246 static int __init beep_init(struct ibm_init_struct *iibm)
5247 {
5248         unsigned long quirks;
5249
5250         vdbg_printk(TPACPI_DBG_INIT, "initializing beep subdriver\n");
5251
5252         TPACPI_ACPIHANDLE_INIT(beep);
5253
5254         vdbg_printk(TPACPI_DBG_INIT, "beep is %s\n",
5255                 str_supported(beep_handle != NULL));
5256
5257         quirks = tpacpi_check_quirks(beep_quirk_table,
5258                                      ARRAY_SIZE(beep_quirk_table));
5259
5260         tp_features.beep_needs_two_args = !!(quirks & TPACPI_BEEP_Q1);
5261
5262         return (beep_handle)? 0 : 1;
5263 }
5264
5265 static int beep_read(char *p)
5266 {
5267         int len = 0;
5268
5269         if (!beep_handle)
5270                 len += sprintf(p + len, "status:\t\tnot supported\n");
5271         else {
5272                 len += sprintf(p + len, "status:\t\tsupported\n");
5273                 len += sprintf(p + len, "commands:\t<cmd> (<cmd> is 0-17)\n");
5274         }
5275
5276         return len;
5277 }
5278
5279 static int beep_write(char *buf)
5280 {
5281         char *cmd;
5282         int beep_cmd;
5283
5284         if (!beep_handle)
5285                 return -ENODEV;
5286
5287         while ((cmd = next_cmd(&buf))) {
5288                 if (sscanf(cmd, "%u", &beep_cmd) == 1 &&
5289                     beep_cmd >= 0 && beep_cmd <= 17) {
5290                         /* beep_cmd set */
5291                 } else
5292                         return -EINVAL;
5293                 if (tp_features.beep_needs_two_args) {
5294                         if (!acpi_evalf(beep_handle, NULL, NULL, "vdd",
5295                                         beep_cmd, 0))
5296                                 return -EIO;
5297                 } else {
5298                         if (!acpi_evalf(beep_handle, NULL, NULL, "vd",
5299                                         beep_cmd))
5300                                 return -EIO;
5301                 }
5302         }
5303
5304         return 0;
5305 }
5306
5307 static struct ibm_struct beep_driver_data = {
5308         .name = "beep",
5309         .read = beep_read,
5310         .write = beep_write,
5311 };
5312
5313 /*************************************************************************
5314  * Thermal subdriver
5315  */
5316
5317 enum thermal_access_mode {
5318         TPACPI_THERMAL_NONE = 0,        /* No thermal support */
5319         TPACPI_THERMAL_ACPI_TMP07,      /* Use ACPI TMP0-7 */
5320         TPACPI_THERMAL_ACPI_UPDT,       /* Use ACPI TMP0-7 with UPDT */
5321         TPACPI_THERMAL_TPEC_8,          /* Use ACPI EC regs, 8 sensors */
5322         TPACPI_THERMAL_TPEC_16,         /* Use ACPI EC regs, 16 sensors */
5323 };
5324
5325 enum { /* TPACPI_THERMAL_TPEC_* */
5326         TP_EC_THERMAL_TMP0 = 0x78,      /* ACPI EC regs TMP 0..7 */
5327         TP_EC_THERMAL_TMP8 = 0xC0,      /* ACPI EC regs TMP 8..15 */
5328         TP_EC_THERMAL_TMP_NA = -128,    /* ACPI EC sensor not available */
5329 };
5330
5331 #define TPACPI_MAX_THERMAL_SENSORS 16   /* Max thermal sensors supported */
5332 struct ibm_thermal_sensors_struct {
5333         s32 temp[TPACPI_MAX_THERMAL_SENSORS];
5334 };
5335
5336 static enum thermal_access_mode thermal_read_mode;
5337
5338 /* idx is zero-based */
5339 static int thermal_get_sensor(int idx, s32 *value)
5340 {
5341         int t;
5342         s8 tmp;
5343         char tmpi[5];
5344
5345         t = TP_EC_THERMAL_TMP0;
5346
5347         switch (thermal_read_mode) {
5348 #if TPACPI_MAX_THERMAL_SENSORS >= 16
5349         case TPACPI_THERMAL_TPEC_16:
5350                 if (idx >= 8 && idx <= 15) {
5351                         t = TP_EC_THERMAL_TMP8;
5352                         idx -= 8;
5353                 }
5354                 /* fallthrough */
5355 #endif
5356         case TPACPI_THERMAL_TPEC_8:
5357                 if (idx <= 7) {
5358                         if (!acpi_ec_read(t + idx, &tmp))
5359                                 return -EIO;
5360                         *value = tmp * 1000;
5361                         return 0;
5362                 }
5363                 break;
5364
5365         case TPACPI_THERMAL_ACPI_UPDT:
5366                 if (idx <= 7) {
5367                         snprintf(tmpi, sizeof(tmpi), "TMP%c", '0' + idx);
5368                         if (!acpi_evalf(ec_handle, NULL, "UPDT", "v"))
5369                                 return -EIO;
5370                         if (!acpi_evalf(ec_handle, &t, tmpi, "d"))
5371                                 return -EIO;
5372                         *value = (t - 2732) * 100;
5373                         return 0;
5374                 }
5375                 break;
5376
5377         case TPACPI_THERMAL_ACPI_TMP07:
5378                 if (idx <= 7) {
5379                         snprintf(tmpi, sizeof(tmpi), "TMP%c", '0' + idx);
5380                         if (!acpi_evalf(ec_handle, &t, tmpi, "d"))
5381                                 return -EIO;
5382                         if (t > 127 || t < -127)
5383                                 t = TP_EC_THERMAL_TMP_NA;
5384                         *value = t * 1000;
5385                         return 0;
5386                 }
5387                 break;
5388
5389         case TPACPI_THERMAL_NONE:
5390         default:
5391                 return -ENOSYS;
5392         }
5393
5394         return -EINVAL;
5395 }
5396
5397 static int thermal_get_sensors(struct ibm_thermal_sensors_struct *s)
5398 {
5399         int res, i;
5400         int n;
5401
5402         n = 8;
5403         i = 0;
5404
5405         if (!s)
5406                 return -EINVAL;
5407
5408         if (thermal_read_mode == TPACPI_THERMAL_TPEC_16)
5409                 n = 16;
5410
5411         for (i = 0 ; i < n; i++) {
5412                 res = thermal_get_sensor(i, &s->temp[i]);
5413                 if (res)
5414                         return res;
5415         }
5416
5417         return n;
5418 }
5419
5420 /* sysfs temp##_input -------------------------------------------------- */
5421
5422 static ssize_t thermal_temp_input_show(struct device *dev,
5423                            struct device_attribute *attr,
5424                            char *buf)
5425 {
5426         struct sensor_device_attribute *sensor_attr =
5427                                         to_sensor_dev_attr(attr);
5428         int idx = sensor_attr->index;
5429         s32 value;
5430         int res;
5431
5432         res = thermal_get_sensor(idx, &value);
5433         if (res)
5434                 return res;
5435         if (value == TP_EC_THERMAL_TMP_NA * 1000)
5436                 return -ENXIO;
5437
5438         return snprintf(buf, PAGE_SIZE, "%d\n", value);
5439 }
5440
5441 #define THERMAL_SENSOR_ATTR_TEMP(_idxA, _idxB) \
5442          SENSOR_ATTR(temp##_idxA##_input, S_IRUGO, \
5443                      thermal_temp_input_show, NULL, _idxB)
5444
5445 static struct sensor_device_attribute sensor_dev_attr_thermal_temp_input[] = {
5446         THERMAL_SENSOR_ATTR_TEMP(1, 0),
5447         THERMAL_SENSOR_ATTR_TEMP(2, 1),
5448         THERMAL_SENSOR_ATTR_TEMP(3, 2),
5449         THERMAL_SENSOR_ATTR_TEMP(4, 3),
5450         THERMAL_SENSOR_ATTR_TEMP(5, 4),
5451         THERMAL_SENSOR_ATTR_TEMP(6, 5),
5452         THERMAL_SENSOR_ATTR_TEMP(7, 6),
5453         THERMAL_SENSOR_ATTR_TEMP(8, 7),
5454         THERMAL_SENSOR_ATTR_TEMP(9, 8),
5455         THERMAL_SENSOR_ATTR_TEMP(10, 9),
5456         THERMAL_SENSOR_ATTR_TEMP(11, 10),
5457         THERMAL_SENSOR_ATTR_TEMP(12, 11),
5458         THERMAL_SENSOR_ATTR_TEMP(13, 12),
5459         THERMAL_SENSOR_ATTR_TEMP(14, 13),
5460         THERMAL_SENSOR_ATTR_TEMP(15, 14),
5461         THERMAL_SENSOR_ATTR_TEMP(16, 15),
5462 };
5463
5464 #define THERMAL_ATTRS(X) \
5465         &sensor_dev_attr_thermal_temp_input[X].dev_attr.attr
5466
5467 static struct attribute *thermal_temp_input_attr[] = {
5468         THERMAL_ATTRS(8),
5469         THERMAL_ATTRS(9),
5470         THERMAL_ATTRS(10),
5471         THERMAL_ATTRS(11),
5472         THERMAL_ATTRS(12),
5473         THERMAL_ATTRS(13),
5474         THERMAL_ATTRS(14),
5475         THERMAL_ATTRS(15),
5476         THERMAL_ATTRS(0),
5477         THERMAL_ATTRS(1),
5478         THERMAL_ATTRS(2),
5479         THERMAL_ATTRS(3),
5480         THERMAL_ATTRS(4),
5481         THERMAL_ATTRS(5),
5482         THERMAL_ATTRS(6),
5483         THERMAL_ATTRS(7),
5484         NULL
5485 };
5486
5487 static const struct attribute_group thermal_temp_input16_group = {
5488         .attrs = thermal_temp_input_attr
5489 };
5490
5491 static const struct attribute_group thermal_temp_input8_group = {
5492         .attrs = &thermal_temp_input_attr[8]
5493 };
5494
5495 #undef THERMAL_SENSOR_ATTR_TEMP
5496 #undef THERMAL_ATTRS
5497
5498 /* --------------------------------------------------------------------- */
5499
5500 static int __init thermal_init(struct ibm_init_struct *iibm)
5501 {
5502         u8 t, ta1, ta2;
5503         int i;
5504         int acpi_tmp7;
5505         int res;
5506
5507         vdbg_printk(TPACPI_DBG_INIT, "initializing thermal subdriver\n");
5508
5509         acpi_tmp7 = acpi_evalf(ec_handle, NULL, "TMP7", "qv");
5510
5511         if (thinkpad_id.ec_model) {
5512                 /*
5513                  * Direct EC access mode: sensors at registers
5514                  * 0x78-0x7F, 0xC0-0xC7.  Registers return 0x00 for
5515                  * non-implemented, thermal sensors return 0x80 when
5516                  * not available
5517                  */
5518
5519                 ta1 = ta2 = 0;
5520                 for (i = 0; i < 8; i++) {
5521                         if (acpi_ec_read(TP_EC_THERMAL_TMP0 + i, &t)) {
5522                                 ta1 |= t;
5523                         } else {
5524                                 ta1 = 0;
5525                                 break;
5526                         }
5527                         if (acpi_ec_read(TP_EC_THERMAL_TMP8 + i, &t)) {
5528                                 ta2 |= t;
5529                         } else {
5530                                 ta1 = 0;
5531                                 break;
5532                         }
5533                 }
5534                 if (ta1 == 0) {
5535                         /* This is sheer paranoia, but we handle it anyway */
5536                         if (acpi_tmp7) {
5537                                 printk(TPACPI_ERR
5538                                        "ThinkPad ACPI EC access misbehaving, "
5539                                        "falling back to ACPI TMPx access "
5540                                        "mode\n");
5541                                 thermal_read_mode = TPACPI_THERMAL_ACPI_TMP07;
5542                         } else {
5543                                 printk(TPACPI_ERR
5544                                        "ThinkPad ACPI EC access misbehaving, "
5545                                        "disabling thermal sensors access\n");
5546                                 thermal_read_mode = TPACPI_THERMAL_NONE;
5547                         }
5548                 } else {
5549                         thermal_read_mode =
5550                             (ta2 != 0) ?
5551                             TPACPI_THERMAL_TPEC_16 : TPACPI_THERMAL_TPEC_8;
5552                 }
5553         } else if (acpi_tmp7) {
5554                 if (acpi_evalf(ec_handle, NULL, "UPDT", "qv")) {
5555                         /* 600e/x, 770e, 770x */
5556                         thermal_read_mode = TPACPI_THERMAL_ACPI_UPDT;
5557                 } else {
5558                         /* Standard ACPI TMPx access, max 8 sensors */
5559                         thermal_read_mode = TPACPI_THERMAL_ACPI_TMP07;
5560                 }
5561         } else {
5562                 /* temperatures not supported on 570, G4x, R30, R31, R32 */
5563                 thermal_read_mode = TPACPI_THERMAL_NONE;
5564         }
5565
5566         vdbg_printk(TPACPI_DBG_INIT, "thermal is %s, mode %d\n",
5567                 str_supported(thermal_read_mode != TPACPI_THERMAL_NONE),
5568                 thermal_read_mode);
5569
5570         switch (thermal_read_mode) {
5571         case TPACPI_THERMAL_TPEC_16:
5572                 res = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
5573                                 &thermal_temp_input16_group);
5574                 if (res)
5575                         return res;
5576                 break;
5577         case TPACPI_THERMAL_TPEC_8:
5578         case TPACPI_THERMAL_ACPI_TMP07:
5579         case TPACPI_THERMAL_ACPI_UPDT:
5580                 res = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
5581                                 &thermal_temp_input8_group);
5582                 if (res)
5583                         return res;
5584                 break;
5585         case TPACPI_THERMAL_NONE:
5586         default:
5587                 return 1;
5588         }
5589
5590         return 0;
5591 }
5592
5593 static void thermal_exit(void)
5594 {
5595         switch (thermal_read_mode) {
5596         case TPACPI_THERMAL_TPEC_16:
5597                 sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
5598                                    &thermal_temp_input16_group);
5599                 break;
5600         case TPACPI_THERMAL_TPEC_8:
5601         case TPACPI_THERMAL_ACPI_TMP07:
5602         case TPACPI_THERMAL_ACPI_UPDT:
5603                 sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
5604                                    &thermal_temp_input16_group);
5605                 break;
5606         case TPACPI_THERMAL_NONE:
5607         default:
5608                 break;
5609         }
5610 }
5611
5612 static int thermal_read(char *p)
5613 {
5614         int len = 0;
5615         int n, i;
5616         struct ibm_thermal_sensors_struct t;
5617
5618         n = thermal_get_sensors(&t);
5619         if (unlikely(n < 0))
5620                 return n;
5621
5622         len += sprintf(p + len, "temperatures:\t");
5623
5624         if (n > 0) {
5625                 for (i = 0; i < (n - 1); i++)
5626                         len += sprintf(p + len, "%d ", t.temp[i] / 1000);
5627                 len += sprintf(p + len, "%d\n", t.temp[i] / 1000);
5628         } else
5629                 len += sprintf(p + len, "not supported\n");
5630
5631         return len;
5632 }
5633
5634 static struct ibm_struct thermal_driver_data = {
5635         .name = "thermal",
5636         .read = thermal_read,
5637         .exit = thermal_exit,
5638 };
5639
5640 /*************************************************************************
5641  * EC Dump subdriver
5642  */
5643
5644 static u8 ecdump_regs[256];
5645
5646 static int ecdump_read(char *p)
5647 {
5648         int len = 0;
5649         int i, j;
5650         u8 v;
5651
5652         len += sprintf(p + len, "EC      "
5653                        " +00 +01 +02 +03 +04 +05 +06 +07"
5654                        " +08 +09 +0a +0b +0c +0d +0e +0f\n");
5655         for (i = 0; i < 256; i += 16) {
5656                 len += sprintf(p + len, "EC 0x%02x:", i);
5657                 for (j = 0; j < 16; j++) {
5658                         if (!acpi_ec_read(i + j, &v))
5659                                 break;
5660                         if (v != ecdump_regs[i + j])
5661                                 len += sprintf(p + len, " *%02x", v);
5662                         else
5663                                 len += sprintf(p + len, "  %02x", v);
5664                         ecdump_regs[i + j] = v;
5665                 }
5666                 len += sprintf(p + len, "\n");
5667                 if (j != 16)
5668                         break;
5669         }
5670
5671         /* These are way too dangerous to advertise openly... */
5672 #if 0
5673         len += sprintf(p + len, "commands:\t0x<offset> 0x<value>"
5674                        " (<offset> is 00-ff, <value> is 00-ff)\n");
5675         len += sprintf(p + len, "commands:\t0x<offset> <value>  "
5676                        " (<offset> is 00-ff, <value> is 0-255)\n");
5677 #endif
5678         return len;
5679 }
5680
5681 static int ecdump_write(char *buf)
5682 {
5683         char *cmd;
5684         int i, v;
5685
5686         while ((cmd = next_cmd(&buf))) {
5687                 if (sscanf(cmd, "0x%x 0x%x", &i, &v) == 2) {
5688                         /* i and v set */
5689                 } else if (sscanf(cmd, "0x%x %u", &i, &v) == 2) {
5690                         /* i and v set */
5691                 } else
5692                         return -EINVAL;
5693                 if (i >= 0 && i < 256 && v >= 0 && v < 256) {
5694                         if (!acpi_ec_write(i, v))
5695                                 return -EIO;
5696                 } else
5697                         return -EINVAL;
5698         }
5699
5700         return 0;
5701 }
5702
5703 static struct ibm_struct ecdump_driver_data = {
5704         .name = "ecdump",
5705         .read = ecdump_read,
5706         .write = ecdump_write,
5707         .flags.experimental = 1,
5708 };
5709
5710 /*************************************************************************
5711  * Backlight/brightness subdriver
5712  */
5713
5714 #define TPACPI_BACKLIGHT_DEV_NAME "thinkpad_screen"
5715
5716 /*
5717  * ThinkPads can read brightness from two places: EC HBRV (0x31), or
5718  * CMOS NVRAM byte 0x5E, bits 0-3.
5719  *
5720  * EC HBRV (0x31) has the following layout
5721  *   Bit 7: unknown function
5722  *   Bit 6: unknown function
5723  *   Bit 5: Z: honour scale changes, NZ: ignore scale changes
5724  *   Bit 4: must be set to zero to avoid problems
5725  *   Bit 3-0: backlight brightness level
5726  *
5727  * brightness_get_raw returns status data in the HBRV layout
5728  *
5729  * WARNING: The X61 has been verified to use HBRV for something else, so
5730  * this should be used _only_ on IBM ThinkPads, and maybe with some careful
5731  * testing on the very early *60 Lenovo models...
5732  */
5733
5734 enum {
5735         TP_EC_BACKLIGHT = 0x31,
5736
5737         /* TP_EC_BACKLIGHT bitmasks */
5738         TP_EC_BACKLIGHT_LVLMSK = 0x1F,
5739         TP_EC_BACKLIGHT_CMDMSK = 0xE0,
5740         TP_EC_BACKLIGHT_MAPSW = 0x20,
5741 };
5742
5743 enum tpacpi_brightness_access_mode {
5744         TPACPI_BRGHT_MODE_AUTO = 0,     /* Not implemented yet */
5745         TPACPI_BRGHT_MODE_EC,           /* EC control */
5746         TPACPI_BRGHT_MODE_UCMS_STEP,    /* UCMS step-based control */
5747         TPACPI_BRGHT_MODE_ECNVRAM,      /* EC control w/ NVRAM store */
5748         TPACPI_BRGHT_MODE_MAX
5749 };
5750
5751 static struct backlight_device *ibm_backlight_device;
5752
5753 static enum tpacpi_brightness_access_mode brightness_mode =
5754                 TPACPI_BRGHT_MODE_MAX;
5755
5756 static unsigned int brightness_enable = 2; /* 2 = auto, 0 = no, 1 = yes */
5757
5758 static struct mutex brightness_mutex;
5759
5760 /* NVRAM brightness access,
5761  * call with brightness_mutex held! */
5762 static unsigned int tpacpi_brightness_nvram_get(void)
5763 {
5764         u8 lnvram;
5765
5766         lnvram = (nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS)
5767                   & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
5768                   >> TP_NVRAM_POS_LEVEL_BRIGHTNESS;
5769         lnvram &= (tp_features.bright_16levels) ? 0x0f : 0x07;
5770
5771         return lnvram;
5772 }
5773
5774 static void tpacpi_brightness_checkpoint_nvram(void)
5775 {
5776         u8 lec = 0;
5777         u8 b_nvram;
5778
5779         if (brightness_mode != TPACPI_BRGHT_MODE_ECNVRAM)
5780                 return;
5781
5782         vdbg_printk(TPACPI_DBG_BRGHT,
5783                 "trying to checkpoint backlight level to NVRAM...\n");
5784
5785         if (mutex_lock_killable(&brightness_mutex) < 0)
5786                 return;
5787
5788         if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec)))
5789                 goto unlock;
5790         lec &= TP_EC_BACKLIGHT_LVLMSK;
5791         b_nvram = nvram_read_byte(TP_NVRAM_ADDR_BRIGHTNESS);
5792
5793         if (lec != ((b_nvram & TP_NVRAM_MASK_LEVEL_BRIGHTNESS)
5794                              >> TP_NVRAM_POS_LEVEL_BRIGHTNESS)) {
5795                 /* NVRAM needs update */
5796                 b_nvram &= ~(TP_NVRAM_MASK_LEVEL_BRIGHTNESS <<
5797                                 TP_NVRAM_POS_LEVEL_BRIGHTNESS);
5798                 b_nvram |= lec;
5799                 nvram_write_byte(b_nvram, TP_NVRAM_ADDR_BRIGHTNESS);
5800                 dbg_printk(TPACPI_DBG_BRGHT,
5801                            "updated NVRAM backlight level to %u (0x%02x)\n",
5802                            (unsigned int) lec, (unsigned int) b_nvram);
5803         } else
5804                 vdbg_printk(TPACPI_DBG_BRGHT,
5805                            "NVRAM backlight level already is %u (0x%02x)\n",
5806                            (unsigned int) lec, (unsigned int) b_nvram);
5807
5808 unlock:
5809         mutex_unlock(&brightness_mutex);
5810 }
5811
5812
5813 /* call with brightness_mutex held! */
5814 static int tpacpi_brightness_get_raw(int *status)
5815 {
5816         u8 lec = 0;
5817
5818         switch (brightness_mode) {
5819         case TPACPI_BRGHT_MODE_UCMS_STEP:
5820                 *status = tpacpi_brightness_nvram_get();
5821                 return 0;
5822         case TPACPI_BRGHT_MODE_EC:
5823         case TPACPI_BRGHT_MODE_ECNVRAM:
5824                 if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec)))
5825                         return -EIO;
5826                 *status = lec;
5827                 return 0;
5828         default:
5829                 return -ENXIO;
5830         }
5831 }
5832
5833 /* call with brightness_mutex held! */
5834 /* do NOT call with illegal backlight level value */
5835 static int tpacpi_brightness_set_ec(unsigned int value)
5836 {
5837         u8 lec = 0;
5838
5839         if (unlikely(!acpi_ec_read(TP_EC_BACKLIGHT, &lec)))
5840                 return -EIO;
5841
5842         if (unlikely(!acpi_ec_write(TP_EC_BACKLIGHT,
5843                                 (lec & TP_EC_BACKLIGHT_CMDMSK) |
5844                                 (value & TP_EC_BACKLIGHT_LVLMSK))))
5845                 return -EIO;
5846
5847         return 0;
5848 }
5849
5850 /* call with brightness_mutex held! */
5851 static int tpacpi_brightness_set_ucmsstep(unsigned int value)
5852 {
5853         int cmos_cmd, inc;
5854         unsigned int current_value, i;
5855
5856         current_value = tpacpi_brightness_nvram_get();
5857
5858         if (value == current_value)
5859                 return 0;
5860
5861         cmos_cmd = (value > current_value) ?
5862                         TP_CMOS_BRIGHTNESS_UP :
5863                         TP_CMOS_BRIGHTNESS_DOWN;
5864         inc = (value > current_value) ? 1 : -1;
5865
5866         for (i = current_value; i != value; i += inc)
5867                 if (issue_thinkpad_cmos_command(cmos_cmd))
5868                         return -EIO;
5869
5870         return 0;
5871 }
5872
5873 /* May return EINTR which can always be mapped to ERESTARTSYS */
5874 static int brightness_set(unsigned int value)
5875 {
5876         int res;
5877
5878         if (value > ((tp_features.bright_16levels)? 15 : 7) ||
5879             value < 0)
5880                 return -EINVAL;
5881
5882         vdbg_printk(TPACPI_DBG_BRGHT,
5883                         "set backlight level to %d\n", value);
5884
5885         res = mutex_lock_killable(&brightness_mutex);
5886         if (res < 0)
5887                 return res;
5888
5889         switch (brightness_mode) {
5890         case TPACPI_BRGHT_MODE_EC:
5891         case TPACPI_BRGHT_MODE_ECNVRAM:
5892                 res = tpacpi_brightness_set_ec(value);
5893                 break;
5894         case TPACPI_BRGHT_MODE_UCMS_STEP:
5895                 res = tpacpi_brightness_set_ucmsstep(value);
5896                 break;
5897         default:
5898                 res = -ENXIO;
5899         }
5900
5901         mutex_unlock(&brightness_mutex);
5902         return res;
5903 }
5904
5905 /* sysfs backlight class ----------------------------------------------- */
5906
5907 static int brightness_update_status(struct backlight_device *bd)
5908 {
5909         unsigned int level =
5910                 (bd->props.fb_blank == FB_BLANK_UNBLANK &&
5911                  bd->props.power == FB_BLANK_UNBLANK) ?
5912                                 bd->props.brightness : 0;
5913
5914         dbg_printk(TPACPI_DBG_BRGHT,
5915                         "backlight: attempt to set level to %d\n",
5916                         level);
5917
5918         /* it is the backlight class's job (caller) to handle
5919          * EINTR and other errors properly */
5920         return brightness_set(level);
5921 }
5922
5923 static int brightness_get(struct backlight_device *bd)
5924 {
5925         int status, res;
5926
5927         res = mutex_lock_killable(&brightness_mutex);
5928         if (res < 0)
5929                 return 0;
5930
5931         res = tpacpi_brightness_get_raw(&status);
5932
5933         mutex_unlock(&brightness_mutex);
5934
5935         if (res < 0)
5936                 return 0;
5937
5938         return status & TP_EC_BACKLIGHT_LVLMSK;
5939 }
5940
5941 static struct backlight_ops ibm_backlight_data = {
5942         .get_brightness = brightness_get,
5943         .update_status  = brightness_update_status,
5944 };
5945
5946 /* --------------------------------------------------------------------- */
5947
5948 static int __init brightness_init(struct ibm_init_struct *iibm)
5949 {
5950         int b;
5951
5952         vdbg_printk(TPACPI_DBG_INIT, "initializing brightness subdriver\n");
5953
5954         mutex_init(&brightness_mutex);
5955
5956         /*
5957          * We always attempt to detect acpi support, so as to switch
5958          * Lenovo Vista BIOS to ACPI brightness mode even if we are not
5959          * going to publish a backlight interface
5960          */
5961         b = tpacpi_check_std_acpi_brightness_support();
5962         if (b > 0) {
5963
5964                 if (acpi_video_backlight_support()) {
5965                         if (brightness_enable > 1) {
5966                                 printk(TPACPI_NOTICE
5967                                        "Standard ACPI backlight interface "
5968                                        "available, not loading native one.\n");
5969                                 return 1;
5970                         } else if (brightness_enable == 1) {
5971                                 printk(TPACPI_NOTICE
5972                                        "Backlight control force enabled, even if standard "
5973                                        "ACPI backlight interface is available\n");
5974                         }
5975                 } else {
5976                         if (brightness_enable > 1) {
5977                                 printk(TPACPI_NOTICE
5978                                        "Standard ACPI backlight interface not "
5979                                        "available, thinkpad_acpi native "
5980                                        "brightness control enabled\n");
5981                         }
5982                 }
5983         }
5984
5985         if (!brightness_enable) {
5986                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_BRGHT,
5987                            "brightness support disabled by "
5988                            "module parameter\n");
5989                 return 1;
5990         }
5991
5992         if (b > 16) {
5993                 printk(TPACPI_ERR
5994                        "Unsupported brightness interface, "
5995                        "please contact %s\n", TPACPI_MAIL);
5996                 return 1;
5997         }
5998         if (b == 16)
5999                 tp_features.bright_16levels = 1;
6000
6001         /*
6002          * Check for module parameter bogosity, note that we
6003          * init brightness_mode to TPACPI_BRGHT_MODE_MAX in order to be
6004          * able to detect "unspecified"
6005          */
6006         if (brightness_mode > TPACPI_BRGHT_MODE_MAX)
6007                 return -EINVAL;
6008
6009         /* TPACPI_BRGHT_MODE_AUTO not implemented yet, just use default */
6010         if (brightness_mode == TPACPI_BRGHT_MODE_AUTO ||
6011             brightness_mode == TPACPI_BRGHT_MODE_MAX) {
6012                 if (thinkpad_id.vendor == PCI_VENDOR_ID_IBM) {
6013                         /*
6014                          * IBM models that define HBRV probably have
6015                          * EC-based backlight level control
6016                          */
6017                         if (acpi_evalf(ec_handle, NULL, "HBRV", "qd"))
6018                                 /* T40-T43, R50-R52, R50e, R51e, X31-X41 */
6019                                 brightness_mode = TPACPI_BRGHT_MODE_ECNVRAM;
6020                         else
6021                                 /* all other IBM ThinkPads */
6022                                 brightness_mode = TPACPI_BRGHT_MODE_UCMS_STEP;
6023                 } else
6024                         /* All Lenovo ThinkPads */
6025                         brightness_mode = TPACPI_BRGHT_MODE_UCMS_STEP;
6026
6027                 dbg_printk(TPACPI_DBG_BRGHT,
6028                            "selected brightness_mode=%d\n",
6029                            brightness_mode);
6030         }
6031
6032         /* Safety */
6033         if (thinkpad_id.vendor != PCI_VENDOR_ID_IBM &&
6034             (brightness_mode == TPACPI_BRGHT_MODE_ECNVRAM ||
6035              brightness_mode == TPACPI_BRGHT_MODE_EC))
6036                 return -EINVAL;
6037
6038         if (tpacpi_brightness_get_raw(&b) < 0)
6039                 return 1;
6040
6041         if (tp_features.bright_16levels)
6042                 printk(TPACPI_INFO
6043                        "detected a 16-level brightness capable ThinkPad\n");
6044
6045         ibm_backlight_device = backlight_device_register(
6046                                         TPACPI_BACKLIGHT_DEV_NAME, NULL, NULL,
6047                                         &ibm_backlight_data);
6048         if (IS_ERR(ibm_backlight_device)) {
6049                 printk(TPACPI_ERR "Could not register backlight device\n");
6050                 return PTR_ERR(ibm_backlight_device);
6051         }
6052         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_BRGHT,
6053                         "brightness is supported\n");
6054
6055         ibm_backlight_device->props.max_brightness =
6056                                 (tp_features.bright_16levels)? 15 : 7;
6057         ibm_backlight_device->props.brightness = b & TP_EC_BACKLIGHT_LVLMSK;
6058         backlight_update_status(ibm_backlight_device);
6059
6060         return 0;
6061 }
6062
6063 static void brightness_suspend(pm_message_t state)
6064 {
6065         tpacpi_brightness_checkpoint_nvram();
6066 }
6067
6068 static void brightness_shutdown(void)
6069 {
6070         tpacpi_brightness_checkpoint_nvram();
6071 }
6072
6073 static void brightness_exit(void)
6074 {
6075         if (ibm_backlight_device) {
6076                 vdbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_BRGHT,
6077                             "calling backlight_device_unregister()\n");
6078                 backlight_device_unregister(ibm_backlight_device);
6079         }
6080
6081         tpacpi_brightness_checkpoint_nvram();
6082 }
6083
6084 static int brightness_read(char *p)
6085 {
6086         int len = 0;
6087         int level;
6088
6089         level = brightness_get(NULL);
6090         if (level < 0) {
6091                 len += sprintf(p + len, "level:\t\tunreadable\n");
6092         } else {
6093                 len += sprintf(p + len, "level:\t\t%d\n", level);
6094                 len += sprintf(p + len, "commands:\tup, down\n");
6095                 len += sprintf(p + len, "commands:\tlevel <level>"
6096                                " (<level> is 0-%d)\n",
6097                                (tp_features.bright_16levels) ? 15 : 7);
6098         }
6099
6100         return len;
6101 }
6102
6103 static int brightness_write(char *buf)
6104 {
6105         int level;
6106         int rc;
6107         char *cmd;
6108         int max_level = (tp_features.bright_16levels) ? 15 : 7;
6109
6110         level = brightness_get(NULL);
6111         if (level < 0)
6112                 return level;
6113
6114         while ((cmd = next_cmd(&buf))) {
6115                 if (strlencmp(cmd, "up") == 0) {
6116                         if (level < max_level)
6117                                 level++;
6118                 } else if (strlencmp(cmd, "down") == 0) {
6119                         if (level > 0)
6120                                 level--;
6121                 } else if (sscanf(cmd, "level %d", &level) == 1 &&
6122                            level >= 0 && level <= max_level) {
6123                         /* new level set */
6124                 } else
6125                         return -EINVAL;
6126         }
6127
6128         tpacpi_disclose_usertask("procfs brightness",
6129                         "set level to %d\n", level);
6130
6131         /*
6132          * Now we know what the final level should be, so we try to set it.
6133          * Doing it this way makes the syscall restartable in case of EINTR
6134          */
6135         rc = brightness_set(level);
6136         return (rc == -EINTR)? ERESTARTSYS : rc;
6137 }
6138
6139 static struct ibm_struct brightness_driver_data = {
6140         .name = "brightness",
6141         .read = brightness_read,
6142         .write = brightness_write,
6143         .exit = brightness_exit,
6144         .suspend = brightness_suspend,
6145         .shutdown = brightness_shutdown,
6146 };
6147
6148 /*************************************************************************
6149  * Volume subdriver
6150  */
6151
6152 static int volume_offset = 0x30;
6153
6154 static int volume_read(char *p)
6155 {
6156         int len = 0;
6157         u8 level;
6158
6159         if (!acpi_ec_read(volume_offset, &level)) {
6160                 len += sprintf(p + len, "level:\t\tunreadable\n");
6161         } else {
6162                 len += sprintf(p + len, "level:\t\t%d\n", level & 0xf);
6163                 len += sprintf(p + len, "mute:\t\t%s\n", onoff(level, 6));
6164                 len += sprintf(p + len, "commands:\tup, down, mute\n");
6165                 len += sprintf(p + len, "commands:\tlevel <level>"
6166                                " (<level> is 0-15)\n");
6167         }
6168
6169         return len;
6170 }
6171
6172 static int volume_write(char *buf)
6173 {
6174         int cmos_cmd, inc, i;
6175         u8 level, mute;
6176         int new_level, new_mute;
6177         char *cmd;
6178
6179         while ((cmd = next_cmd(&buf))) {
6180                 if (!acpi_ec_read(volume_offset, &level))
6181                         return -EIO;
6182                 new_mute = mute = level & 0x40;
6183                 new_level = level = level & 0xf;
6184
6185                 if (strlencmp(cmd, "up") == 0) {
6186                         if (mute)
6187                                 new_mute = 0;
6188                         else
6189                                 new_level = level == 15 ? 15 : level + 1;
6190                 } else if (strlencmp(cmd, "down") == 0) {
6191                         if (mute)
6192                                 new_mute = 0;
6193                         else
6194                                 new_level = level == 0 ? 0 : level - 1;
6195                 } else if (sscanf(cmd, "level %d", &new_level) == 1 &&
6196                            new_level >= 0 && new_level <= 15) {
6197                         /* new_level set */
6198                 } else if (strlencmp(cmd, "mute") == 0) {
6199                         new_mute = 0x40;
6200                 } else
6201                         return -EINVAL;
6202
6203                 if (new_level != level) {
6204                         /* mute doesn't change */
6205
6206                         cmos_cmd = (new_level > level) ?
6207                                         TP_CMOS_VOLUME_UP : TP_CMOS_VOLUME_DOWN;
6208                         inc = new_level > level ? 1 : -1;
6209
6210                         if (mute && (issue_thinkpad_cmos_command(cmos_cmd) ||
6211                                      !acpi_ec_write(volume_offset, level)))
6212                                 return -EIO;
6213
6214                         for (i = level; i != new_level; i += inc)
6215                                 if (issue_thinkpad_cmos_command(cmos_cmd) ||
6216                                     !acpi_ec_write(volume_offset, i + inc))
6217                                         return -EIO;
6218
6219                         if (mute &&
6220                             (issue_thinkpad_cmos_command(TP_CMOS_VOLUME_MUTE) ||
6221                              !acpi_ec_write(volume_offset, new_level + mute))) {
6222                                 return -EIO;
6223                         }
6224                 }
6225
6226                 if (new_mute != mute) {
6227                         /* level doesn't change */
6228
6229                         cmos_cmd = (new_mute) ?
6230                                    TP_CMOS_VOLUME_MUTE : TP_CMOS_VOLUME_UP;
6231
6232                         if (issue_thinkpad_cmos_command(cmos_cmd) ||
6233                             !acpi_ec_write(volume_offset, level + new_mute))
6234                                 return -EIO;
6235                 }
6236         }
6237
6238         return 0;
6239 }
6240
6241 static struct ibm_struct volume_driver_data = {
6242         .name = "volume",
6243         .read = volume_read,
6244         .write = volume_write,
6245 };
6246
6247 /*************************************************************************
6248  * Fan subdriver
6249  */
6250
6251 /*
6252  * FAN ACCESS MODES
6253  *
6254  * TPACPI_FAN_RD_ACPI_GFAN:
6255  *      ACPI GFAN method: returns fan level
6256  *
6257  *      see TPACPI_FAN_WR_ACPI_SFAN
6258  *      EC 0x2f (HFSP) not available if GFAN exists
6259  *
6260  * TPACPI_FAN_WR_ACPI_SFAN:
6261  *      ACPI SFAN method: sets fan level, 0 (stop) to 7 (max)
6262  *
6263  *      EC 0x2f (HFSP) might be available *for reading*, but do not use
6264  *      it for writing.
6265  *
6266  * TPACPI_FAN_WR_TPEC:
6267  *      ThinkPad EC register 0x2f (HFSP): fan control loop mode
6268  *      Supported on almost all ThinkPads
6269  *
6270  *      Fan speed changes of any sort (including those caused by the
6271  *      disengaged mode) are usually done slowly by the firmware as the
6272  *      maximum ammount of fan duty cycle change per second seems to be
6273  *      limited.
6274  *
6275  *      Reading is not available if GFAN exists.
6276  *      Writing is not available if SFAN exists.
6277  *
6278  *      Bits
6279  *       7      automatic mode engaged;
6280  *              (default operation mode of the ThinkPad)
6281  *              fan level is ignored in this mode.
6282  *       6      full speed mode (takes precedence over bit 7);
6283  *              not available on all thinkpads.  May disable
6284  *              the tachometer while the fan controller ramps up
6285  *              the speed (which can take up to a few *minutes*).
6286  *              Speeds up fan to 100% duty-cycle, which is far above
6287  *              the standard RPM levels.  It is not impossible that
6288  *              it could cause hardware damage.
6289  *      5-3     unused in some models.  Extra bits for fan level
6290  *              in others, but still useless as all values above
6291  *              7 map to the same speed as level 7 in these models.
6292  *      2-0     fan level (0..7 usually)
6293  *                      0x00 = stop
6294  *                      0x07 = max (set when temperatures critical)
6295  *              Some ThinkPads may have other levels, see
6296  *              TPACPI_FAN_WR_ACPI_FANS (X31/X40/X41)
6297  *
6298  *      FIRMWARE BUG: on some models, EC 0x2f might not be initialized at
6299  *      boot. Apparently the EC does not intialize it, so unless ACPI DSDT
6300  *      does so, its initial value is meaningless (0x07).
6301  *
6302  *      For firmware bugs, refer to:
6303  *      http://thinkwiki.org/wiki/Embedded_Controller_Firmware#Firmware_Issues
6304  *
6305  *      ----
6306  *
6307  *      ThinkPad EC register 0x84 (LSB), 0x85 (MSB):
6308  *      Main fan tachometer reading (in RPM)
6309  *
6310  *      This register is present on all ThinkPads with a new-style EC, and
6311  *      it is known not to be present on the A21m/e, and T22, as there is
6312  *      something else in offset 0x84 according to the ACPI DSDT.  Other
6313  *      ThinkPads from this same time period (and earlier) probably lack the
6314  *      tachometer as well.
6315  *
6316  *      Unfortunately a lot of ThinkPads with new-style ECs but whose firmware
6317  *      was never fixed by IBM to report the EC firmware version string
6318  *      probably support the tachometer (like the early X models), so
6319  *      detecting it is quite hard.  We need more data to know for sure.
6320  *
6321  *      FIRMWARE BUG: always read 0x84 first, otherwise incorrect readings
6322  *      might result.
6323  *
6324  *      FIRMWARE BUG: may go stale while the EC is switching to full speed
6325  *      mode.
6326  *
6327  *      For firmware bugs, refer to:
6328  *      http://thinkwiki.org/wiki/Embedded_Controller_Firmware#Firmware_Issues
6329  *
6330  *      ----
6331  *
6332  *      ThinkPad EC register 0x31 bit 0 (only on select models)
6333  *
6334  *      When bit 0 of EC register 0x31 is zero, the tachometer registers
6335  *      show the speed of the main fan.  When bit 0 of EC register 0x31
6336  *      is one, the tachometer registers show the speed of the auxiliary
6337  *      fan.
6338  *
6339  *      Fan control seems to affect both fans, regardless of the state
6340  *      of this bit.
6341  *
6342  *      So far, only the firmware for the X60/X61 non-tablet versions
6343  *      seem to support this (firmware TP-7M).
6344  *
6345  * TPACPI_FAN_WR_ACPI_FANS:
6346  *      ThinkPad X31, X40, X41.  Not available in the X60.
6347  *
6348  *      FANS ACPI handle: takes three arguments: low speed, medium speed,
6349  *      high speed.  ACPI DSDT seems to map these three speeds to levels
6350  *      as follows: STOP LOW LOW MED MED HIGH HIGH HIGH HIGH
6351  *      (this map is stored on FAN0..FAN8 as "0,1,1,2,2,3,3,3,3")
6352  *
6353  *      The speeds are stored on handles
6354  *      (FANA:FAN9), (FANC:FANB), (FANE:FAND).
6355  *
6356  *      There are three default speed sets, acessible as handles:
6357  *      FS1L,FS1M,FS1H; FS2L,FS2M,FS2H; FS3L,FS3M,FS3H
6358  *
6359  *      ACPI DSDT switches which set is in use depending on various
6360  *      factors.
6361  *
6362  *      TPACPI_FAN_WR_TPEC is also available and should be used to
6363  *      command the fan.  The X31/X40/X41 seems to have 8 fan levels,
6364  *      but the ACPI tables just mention level 7.
6365  */
6366
6367 enum {                                  /* Fan control constants */
6368         fan_status_offset = 0x2f,       /* EC register 0x2f */
6369         fan_rpm_offset = 0x84,          /* EC register 0x84: LSB, 0x85 MSB (RPM)
6370                                          * 0x84 must be read before 0x85 */
6371         fan_select_offset = 0x31,       /* EC register 0x31 (Firmware 7M)
6372                                            bit 0 selects which fan is active */
6373
6374         TP_EC_FAN_FULLSPEED = 0x40,     /* EC fan mode: full speed */
6375         TP_EC_FAN_AUTO      = 0x80,     /* EC fan mode: auto fan control */
6376
6377         TPACPI_FAN_LAST_LEVEL = 0x100,  /* Use cached last-seen fan level */
6378 };
6379
6380 enum fan_status_access_mode {
6381         TPACPI_FAN_NONE = 0,            /* No fan status or control */
6382         TPACPI_FAN_RD_ACPI_GFAN,        /* Use ACPI GFAN */
6383         TPACPI_FAN_RD_TPEC,             /* Use ACPI EC regs 0x2f, 0x84-0x85 */
6384 };
6385
6386 enum fan_control_access_mode {
6387         TPACPI_FAN_WR_NONE = 0,         /* No fan control */
6388         TPACPI_FAN_WR_ACPI_SFAN,        /* Use ACPI SFAN */
6389         TPACPI_FAN_WR_TPEC,             /* Use ACPI EC reg 0x2f */
6390         TPACPI_FAN_WR_ACPI_FANS,        /* Use ACPI FANS and EC reg 0x2f */
6391 };
6392
6393 enum fan_control_commands {
6394         TPACPI_FAN_CMD_SPEED    = 0x0001,       /* speed command */
6395         TPACPI_FAN_CMD_LEVEL    = 0x0002,       /* level command  */
6396         TPACPI_FAN_CMD_ENABLE   = 0x0004,       /* enable/disable cmd,
6397                                                  * and also watchdog cmd */
6398 };
6399
6400 static int fan_control_allowed;
6401
6402 static enum fan_status_access_mode fan_status_access_mode;
6403 static enum fan_control_access_mode fan_control_access_mode;
6404 static enum fan_control_commands fan_control_commands;
6405
6406 static u8 fan_control_initial_status;
6407 static u8 fan_control_desired_level;
6408 static u8 fan_control_resume_level;
6409 static int fan_watchdog_maxinterval;
6410
6411 static struct mutex fan_mutex;
6412
6413 static void fan_watchdog_fire(struct work_struct *ignored);
6414 static DECLARE_DELAYED_WORK(fan_watchdog_task, fan_watchdog_fire);
6415
6416 TPACPI_HANDLE(fans, ec, "FANS");        /* X31, X40, X41 */
6417 TPACPI_HANDLE(gfan, ec, "GFAN", /* 570 */
6418            "\\FSPD",            /* 600e/x, 770e, 770x */
6419            );                   /* all others */
6420 TPACPI_HANDLE(sfan, ec, "SFAN", /* 570 */
6421            "JFNS",              /* 770x-JL */
6422            );                   /* all others */
6423
6424 /*
6425  * Unitialized HFSP quirk: ACPI DSDT and EC fail to initialize the
6426  * HFSP register at boot, so it contains 0x07 but the Thinkpad could
6427  * be in auto mode (0x80).
6428  *
6429  * This is corrected by any write to HFSP either by the driver, or
6430  * by the firmware.
6431  *
6432  * We assume 0x07 really means auto mode while this quirk is active,
6433  * as this is far more likely than the ThinkPad being in level 7,
6434  * which is only used by the firmware during thermal emergencies.
6435  *
6436  * Enable for TP-1Y (T43), TP-78 (R51e), TP-76 (R52),
6437  * TP-70 (T43, R52), which are known to be buggy.
6438  */
6439
6440 static void fan_quirk1_setup(void)
6441 {
6442         if (fan_control_initial_status == 0x07) {
6443                 printk(TPACPI_NOTICE
6444                        "fan_init: initial fan status is unknown, "
6445                        "assuming it is in auto mode\n");
6446                 tp_features.fan_ctrl_status_undef = 1;
6447         }
6448 }
6449
6450 static void fan_quirk1_handle(u8 *fan_status)
6451 {
6452         if (unlikely(tp_features.fan_ctrl_status_undef)) {
6453                 if (*fan_status != fan_control_initial_status) {
6454                         /* something changed the HFSP regisnter since
6455                          * driver init time, so it is not undefined
6456                          * anymore */
6457                         tp_features.fan_ctrl_status_undef = 0;
6458                 } else {
6459                         /* Return most likely status. In fact, it
6460                          * might be the only possible status */
6461                         *fan_status = TP_EC_FAN_AUTO;
6462                 }
6463         }
6464 }
6465
6466 /* Select main fan on X60/X61, NOOP on others */
6467 static bool fan_select_fan1(void)
6468 {
6469         if (tp_features.second_fan) {
6470                 u8 val;
6471
6472                 if (ec_read(fan_select_offset, &val) < 0)
6473                         return false;
6474                 val &= 0xFEU;
6475                 if (ec_write(fan_select_offset, val) < 0)
6476                         return false;
6477         }
6478         return true;
6479 }
6480
6481 /* Select secondary fan on X60/X61 */
6482 static bool fan_select_fan2(void)
6483 {
6484         u8 val;
6485
6486         if (!tp_features.second_fan)
6487                 return false;
6488
6489         if (ec_read(fan_select_offset, &val) < 0)
6490                 return false;
6491         val |= 0x01U;
6492         if (ec_write(fan_select_offset, val) < 0)
6493                 return false;
6494
6495         return true;
6496 }
6497
6498 /*
6499  * Call with fan_mutex held
6500  */
6501 static void fan_update_desired_level(u8 status)
6502 {
6503         if ((status &
6504              (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) == 0) {
6505                 if (status > 7)
6506                         fan_control_desired_level = 7;
6507                 else
6508                         fan_control_desired_level = status;
6509         }
6510 }
6511
6512 static int fan_get_status(u8 *status)
6513 {
6514         u8 s;
6515
6516         /* TODO:
6517          * Add TPACPI_FAN_RD_ACPI_FANS ? */
6518
6519         switch (fan_status_access_mode) {
6520         case TPACPI_FAN_RD_ACPI_GFAN:
6521                 /* 570, 600e/x, 770e, 770x */
6522
6523                 if (unlikely(!acpi_evalf(gfan_handle, &s, NULL, "d")))
6524                         return -EIO;
6525
6526                 if (likely(status))
6527                         *status = s & 0x07;
6528
6529                 break;
6530
6531         case TPACPI_FAN_RD_TPEC:
6532                 /* all except 570, 600e/x, 770e, 770x */
6533                 if (unlikely(!acpi_ec_read(fan_status_offset, &s)))
6534                         return -EIO;
6535
6536                 if (likely(status)) {
6537                         *status = s;
6538                         fan_quirk1_handle(status);
6539                 }
6540
6541                 break;
6542
6543         default:
6544                 return -ENXIO;
6545         }
6546
6547         return 0;
6548 }
6549
6550 static int fan_get_status_safe(u8 *status)
6551 {
6552         int rc;
6553         u8 s;
6554
6555         if (mutex_lock_killable(&fan_mutex))
6556                 return -ERESTARTSYS;
6557         rc = fan_get_status(&s);
6558         if (!rc)
6559                 fan_update_desired_level(s);
6560         mutex_unlock(&fan_mutex);
6561
6562         if (status)
6563                 *status = s;
6564
6565         return rc;
6566 }
6567
6568 static int fan_get_speed(unsigned int *speed)
6569 {
6570         u8 hi, lo;
6571
6572         switch (fan_status_access_mode) {
6573         case TPACPI_FAN_RD_TPEC:
6574                 /* all except 570, 600e/x, 770e, 770x */
6575                 if (unlikely(!fan_select_fan1()))
6576                         return -EIO;
6577                 if (unlikely(!acpi_ec_read(fan_rpm_offset, &lo) ||
6578                              !acpi_ec_read(fan_rpm_offset + 1, &hi)))
6579                         return -EIO;
6580
6581                 if (likely(speed))
6582                         *speed = (hi << 8) | lo;
6583
6584                 break;
6585
6586         default:
6587                 return -ENXIO;
6588         }
6589
6590         return 0;
6591 }
6592
6593 static int fan2_get_speed(unsigned int *speed)
6594 {
6595         u8 hi, lo;
6596         bool rc;
6597
6598         switch (fan_status_access_mode) {
6599         case TPACPI_FAN_RD_TPEC:
6600                 /* all except 570, 600e/x, 770e, 770x */
6601                 if (unlikely(!fan_select_fan2()))
6602                         return -EIO;
6603                 rc = !acpi_ec_read(fan_rpm_offset, &lo) ||
6604                              !acpi_ec_read(fan_rpm_offset + 1, &hi);
6605                 fan_select_fan1(); /* play it safe */
6606                 if (rc)
6607                         return -EIO;
6608
6609                 if (likely(speed))
6610                         *speed = (hi << 8) | lo;
6611
6612                 break;
6613
6614         default:
6615                 return -ENXIO;
6616         }
6617
6618         return 0;
6619 }
6620
6621 static int fan_set_level(int level)
6622 {
6623         if (!fan_control_allowed)
6624                 return -EPERM;
6625
6626         switch (fan_control_access_mode) {
6627         case TPACPI_FAN_WR_ACPI_SFAN:
6628                 if (level >= 0 && level <= 7) {
6629                         if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", level))
6630                                 return -EIO;
6631                 } else
6632                         return -EINVAL;
6633                 break;
6634
6635         case TPACPI_FAN_WR_ACPI_FANS:
6636         case TPACPI_FAN_WR_TPEC:
6637                 if (!(level & TP_EC_FAN_AUTO) &&
6638                     !(level & TP_EC_FAN_FULLSPEED) &&
6639                     ((level < 0) || (level > 7)))
6640                         return -EINVAL;
6641
6642                 /* safety net should the EC not support AUTO
6643                  * or FULLSPEED mode bits and just ignore them */
6644                 if (level & TP_EC_FAN_FULLSPEED)
6645                         level |= 7;     /* safety min speed 7 */
6646                 else if (level & TP_EC_FAN_AUTO)
6647                         level |= 4;     /* safety min speed 4 */
6648
6649                 if (!acpi_ec_write(fan_status_offset, level))
6650                         return -EIO;
6651                 else
6652                         tp_features.fan_ctrl_status_undef = 0;
6653                 break;
6654
6655         default:
6656                 return -ENXIO;
6657         }
6658
6659         vdbg_printk(TPACPI_DBG_FAN,
6660                 "fan control: set fan control register to 0x%02x\n", level);
6661         return 0;
6662 }
6663
6664 static int fan_set_level_safe(int level)
6665 {
6666         int rc;
6667
6668         if (!fan_control_allowed)
6669                 return -EPERM;
6670
6671         if (mutex_lock_killable(&fan_mutex))
6672                 return -ERESTARTSYS;
6673
6674         if (level == TPACPI_FAN_LAST_LEVEL)
6675                 level = fan_control_desired_level;
6676
6677         rc = fan_set_level(level);
6678         if (!rc)
6679                 fan_update_desired_level(level);
6680
6681         mutex_unlock(&fan_mutex);
6682         return rc;
6683 }
6684
6685 static int fan_set_enable(void)
6686 {
6687         u8 s;
6688         int rc;
6689
6690         if (!fan_control_allowed)
6691                 return -EPERM;
6692
6693         if (mutex_lock_killable(&fan_mutex))
6694                 return -ERESTARTSYS;
6695
6696         switch (fan_control_access_mode) {
6697         case TPACPI_FAN_WR_ACPI_FANS:
6698         case TPACPI_FAN_WR_TPEC:
6699                 rc = fan_get_status(&s);
6700                 if (rc < 0)
6701                         break;
6702
6703                 /* Don't go out of emergency fan mode */
6704                 if (s != 7) {
6705                         s &= 0x07;
6706                         s |= TP_EC_FAN_AUTO | 4; /* min fan speed 4 */
6707                 }
6708
6709                 if (!acpi_ec_write(fan_status_offset, s))
6710                         rc = -EIO;
6711                 else {
6712                         tp_features.fan_ctrl_status_undef = 0;
6713                         rc = 0;
6714                 }
6715                 break;
6716
6717         case TPACPI_FAN_WR_ACPI_SFAN:
6718                 rc = fan_get_status(&s);
6719                 if (rc < 0)
6720                         break;
6721
6722                 s &= 0x07;
6723
6724                 /* Set fan to at least level 4 */
6725                 s |= 4;
6726
6727                 if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", s))
6728                         rc = -EIO;
6729                 else
6730                         rc = 0;
6731                 break;
6732
6733         default:
6734                 rc = -ENXIO;
6735         }
6736
6737         mutex_unlock(&fan_mutex);
6738
6739         if (!rc)
6740                 vdbg_printk(TPACPI_DBG_FAN,
6741                         "fan control: set fan control register to 0x%02x\n",
6742                         s);
6743         return rc;
6744 }
6745
6746 static int fan_set_disable(void)
6747 {
6748         int rc;
6749
6750         if (!fan_control_allowed)
6751                 return -EPERM;
6752
6753         if (mutex_lock_killable(&fan_mutex))
6754                 return -ERESTARTSYS;
6755
6756         rc = 0;
6757         switch (fan_control_access_mode) {
6758         case TPACPI_FAN_WR_ACPI_FANS:
6759         case TPACPI_FAN_WR_TPEC:
6760                 if (!acpi_ec_write(fan_status_offset, 0x00))
6761                         rc = -EIO;
6762                 else {
6763                         fan_control_desired_level = 0;
6764                         tp_features.fan_ctrl_status_undef = 0;
6765                 }
6766                 break;
6767
6768         case TPACPI_FAN_WR_ACPI_SFAN:
6769                 if (!acpi_evalf(sfan_handle, NULL, NULL, "vd", 0x00))
6770                         rc = -EIO;
6771                 else
6772                         fan_control_desired_level = 0;
6773                 break;
6774
6775         default:
6776                 rc = -ENXIO;
6777         }
6778
6779         if (!rc)
6780                 vdbg_printk(TPACPI_DBG_FAN,
6781                         "fan control: set fan control register to 0\n");
6782
6783         mutex_unlock(&fan_mutex);
6784         return rc;
6785 }
6786
6787 static int fan_set_speed(int speed)
6788 {
6789         int rc;
6790
6791         if (!fan_control_allowed)
6792                 return -EPERM;
6793
6794         if (mutex_lock_killable(&fan_mutex))
6795                 return -ERESTARTSYS;
6796
6797         rc = 0;
6798         switch (fan_control_access_mode) {
6799         case TPACPI_FAN_WR_ACPI_FANS:
6800                 if (speed >= 0 && speed <= 65535) {
6801                         if (!acpi_evalf(fans_handle, NULL, NULL, "vddd",
6802                                         speed, speed, speed))
6803                                 rc = -EIO;
6804                 } else
6805                         rc = -EINVAL;
6806                 break;
6807
6808         default:
6809                 rc = -ENXIO;
6810         }
6811
6812         mutex_unlock(&fan_mutex);
6813         return rc;
6814 }
6815
6816 static void fan_watchdog_reset(void)
6817 {
6818         static int fan_watchdog_active;
6819
6820         if (fan_control_access_mode == TPACPI_FAN_WR_NONE)
6821                 return;
6822
6823         if (fan_watchdog_active)
6824                 cancel_delayed_work(&fan_watchdog_task);
6825
6826         if (fan_watchdog_maxinterval > 0 &&
6827             tpacpi_lifecycle != TPACPI_LIFE_EXITING) {
6828                 fan_watchdog_active = 1;
6829                 if (!queue_delayed_work(tpacpi_wq, &fan_watchdog_task,
6830                                 msecs_to_jiffies(fan_watchdog_maxinterval
6831                                                  * 1000))) {
6832                         printk(TPACPI_ERR
6833                                "failed to queue the fan watchdog, "
6834                                "watchdog will not trigger\n");
6835                 }
6836         } else
6837                 fan_watchdog_active = 0;
6838 }
6839
6840 static void fan_watchdog_fire(struct work_struct *ignored)
6841 {
6842         int rc;
6843
6844         if (tpacpi_lifecycle != TPACPI_LIFE_RUNNING)
6845                 return;
6846
6847         printk(TPACPI_NOTICE "fan watchdog: enabling fan\n");
6848         rc = fan_set_enable();
6849         if (rc < 0) {
6850                 printk(TPACPI_ERR "fan watchdog: error %d while enabling fan, "
6851                         "will try again later...\n", -rc);
6852                 /* reschedule for later */
6853                 fan_watchdog_reset();
6854         }
6855 }
6856
6857 /*
6858  * SYSFS fan layout: hwmon compatible (device)
6859  *
6860  * pwm*_enable:
6861  *      0: "disengaged" mode
6862  *      1: manual mode
6863  *      2: native EC "auto" mode (recommended, hardware default)
6864  *
6865  * pwm*: set speed in manual mode, ignored otherwise.
6866  *      0 is level 0; 255 is level 7. Intermediate points done with linear
6867  *      interpolation.
6868  *
6869  * fan*_input: tachometer reading, RPM
6870  *
6871  *
6872  * SYSFS fan layout: extensions
6873  *
6874  * fan_watchdog (driver):
6875  *      fan watchdog interval in seconds, 0 disables (default), max 120
6876  */
6877
6878 /* sysfs fan pwm1_enable ----------------------------------------------- */
6879 static ssize_t fan_pwm1_enable_show(struct device *dev,
6880                                     struct device_attribute *attr,
6881                                     char *buf)
6882 {
6883         int res, mode;
6884         u8 status;
6885
6886         res = fan_get_status_safe(&status);
6887         if (res)
6888                 return res;
6889
6890         if (status & TP_EC_FAN_FULLSPEED) {
6891                 mode = 0;
6892         } else if (status & TP_EC_FAN_AUTO) {
6893                 mode = 2;
6894         } else
6895                 mode = 1;
6896
6897         return snprintf(buf, PAGE_SIZE, "%d\n", mode);
6898 }
6899
6900 static ssize_t fan_pwm1_enable_store(struct device *dev,
6901                                      struct device_attribute *attr,
6902                                      const char *buf, size_t count)
6903 {
6904         unsigned long t;
6905         int res, level;
6906
6907         if (parse_strtoul(buf, 2, &t))
6908                 return -EINVAL;
6909
6910         tpacpi_disclose_usertask("hwmon pwm1_enable",
6911                         "set fan mode to %lu\n", t);
6912
6913         switch (t) {
6914         case 0:
6915                 level = TP_EC_FAN_FULLSPEED;
6916                 break;
6917         case 1:
6918                 level = TPACPI_FAN_LAST_LEVEL;
6919                 break;
6920         case 2:
6921                 level = TP_EC_FAN_AUTO;
6922                 break;
6923         case 3:
6924                 /* reserved for software-controlled auto mode */
6925                 return -ENOSYS;
6926         default:
6927                 return -EINVAL;
6928         }
6929
6930         res = fan_set_level_safe(level);
6931         if (res == -ENXIO)
6932                 return -EINVAL;
6933         else if (res < 0)
6934                 return res;
6935
6936         fan_watchdog_reset();
6937
6938         return count;
6939 }
6940
6941 static struct device_attribute dev_attr_fan_pwm1_enable =
6942         __ATTR(pwm1_enable, S_IWUSR | S_IRUGO,
6943                 fan_pwm1_enable_show, fan_pwm1_enable_store);
6944
6945 /* sysfs fan pwm1 ------------------------------------------------------ */
6946 static ssize_t fan_pwm1_show(struct device *dev,
6947                              struct device_attribute *attr,
6948                              char *buf)
6949 {
6950         int res;
6951         u8 status;
6952
6953         res = fan_get_status_safe(&status);
6954         if (res)
6955                 return res;
6956
6957         if ((status &
6958              (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) != 0)
6959                 status = fan_control_desired_level;
6960
6961         if (status > 7)
6962                 status = 7;
6963
6964         return snprintf(buf, PAGE_SIZE, "%u\n", (status * 255) / 7);
6965 }
6966
6967 static ssize_t fan_pwm1_store(struct device *dev,
6968                               struct device_attribute *attr,
6969                               const char *buf, size_t count)
6970 {
6971         unsigned long s;
6972         int rc;
6973         u8 status, newlevel;
6974
6975         if (parse_strtoul(buf, 255, &s))
6976                 return -EINVAL;
6977
6978         tpacpi_disclose_usertask("hwmon pwm1",
6979                         "set fan speed to %lu\n", s);
6980
6981         /* scale down from 0-255 to 0-7 */
6982         newlevel = (s >> 5) & 0x07;
6983
6984         if (mutex_lock_killable(&fan_mutex))
6985                 return -ERESTARTSYS;
6986
6987         rc = fan_get_status(&status);
6988         if (!rc && (status &
6989                     (TP_EC_FAN_AUTO | TP_EC_FAN_FULLSPEED)) == 0) {
6990                 rc = fan_set_level(newlevel);
6991                 if (rc == -ENXIO)
6992                         rc = -EINVAL;
6993                 else if (!rc) {
6994                         fan_update_desired_level(newlevel);
6995                         fan_watchdog_reset();
6996                 }
6997         }
6998
6999         mutex_unlock(&fan_mutex);
7000         return (rc)? rc : count;
7001 }
7002
7003 static struct device_attribute dev_attr_fan_pwm1 =
7004         __ATTR(pwm1, S_IWUSR | S_IRUGO,
7005                 fan_pwm1_show, fan_pwm1_store);
7006
7007 /* sysfs fan fan1_input ------------------------------------------------ */
7008 static ssize_t fan_fan1_input_show(struct device *dev,
7009                            struct device_attribute *attr,
7010                            char *buf)
7011 {
7012         int res;
7013         unsigned int speed;
7014
7015         res = fan_get_speed(&speed);
7016         if (res < 0)
7017                 return res;
7018
7019         return snprintf(buf, PAGE_SIZE, "%u\n", speed);
7020 }
7021
7022 static struct device_attribute dev_attr_fan_fan1_input =
7023         __ATTR(fan1_input, S_IRUGO,
7024                 fan_fan1_input_show, NULL);
7025
7026 /* sysfs fan fan2_input ------------------------------------------------ */
7027 static ssize_t fan_fan2_input_show(struct device *dev,
7028                            struct device_attribute *attr,
7029                            char *buf)
7030 {
7031         int res;
7032         unsigned int speed;
7033
7034         res = fan2_get_speed(&speed);
7035         if (res < 0)
7036                 return res;
7037
7038         return snprintf(buf, PAGE_SIZE, "%u\n", speed);
7039 }
7040
7041 static struct device_attribute dev_attr_fan_fan2_input =
7042         __ATTR(fan2_input, S_IRUGO,
7043                 fan_fan2_input_show, NULL);
7044
7045 /* sysfs fan fan_watchdog (hwmon driver) ------------------------------- */
7046 static ssize_t fan_fan_watchdog_show(struct device_driver *drv,
7047                                      char *buf)
7048 {
7049         return snprintf(buf, PAGE_SIZE, "%u\n", fan_watchdog_maxinterval);
7050 }
7051
7052 static ssize_t fan_fan_watchdog_store(struct device_driver *drv,
7053                                       const char *buf, size_t count)
7054 {
7055         unsigned long t;
7056
7057         if (parse_strtoul(buf, 120, &t))
7058                 return -EINVAL;
7059
7060         if (!fan_control_allowed)
7061                 return -EPERM;
7062
7063         fan_watchdog_maxinterval = t;
7064         fan_watchdog_reset();
7065
7066         tpacpi_disclose_usertask("fan_watchdog", "set to %lu\n", t);
7067
7068         return count;
7069 }
7070
7071 static DRIVER_ATTR(fan_watchdog, S_IWUSR | S_IRUGO,
7072                 fan_fan_watchdog_show, fan_fan_watchdog_store);
7073
7074 /* --------------------------------------------------------------------- */
7075 static struct attribute *fan_attributes[] = {
7076         &dev_attr_fan_pwm1_enable.attr, &dev_attr_fan_pwm1.attr,
7077         &dev_attr_fan_fan1_input.attr,
7078         NULL, /* for fan2_input */
7079         NULL
7080 };
7081
7082 static const struct attribute_group fan_attr_group = {
7083         .attrs = fan_attributes,
7084 };
7085
7086 #define TPACPI_FAN_Q1   0x0001          /* Unitialized HFSP */
7087 #define TPACPI_FAN_2FAN 0x0002          /* EC 0x31 bit 0 selects fan2 */
7088
7089 #define TPACPI_FAN_QI(__id1, __id2, __quirks)   \
7090         { .vendor = PCI_VENDOR_ID_IBM,          \
7091           .bios = TPACPI_MATCH_ANY,             \
7092           .ec = TPID(__id1, __id2),             \
7093           .quirks = __quirks }
7094
7095 #define TPACPI_FAN_QL(__id1, __id2, __quirks)   \
7096         { .vendor = PCI_VENDOR_ID_LENOVO,       \
7097           .bios = TPACPI_MATCH_ANY,             \
7098           .ec = TPID(__id1, __id2),             \
7099           .quirks = __quirks }
7100
7101 static const struct tpacpi_quirk fan_quirk_table[] __initconst = {
7102         TPACPI_FAN_QI('1', 'Y', TPACPI_FAN_Q1),
7103         TPACPI_FAN_QI('7', '8', TPACPI_FAN_Q1),
7104         TPACPI_FAN_QI('7', '6', TPACPI_FAN_Q1),
7105         TPACPI_FAN_QI('7', '0', TPACPI_FAN_Q1),
7106         TPACPI_FAN_QL('7', 'M', TPACPI_FAN_2FAN),
7107 };
7108
7109 #undef TPACPI_FAN_QL
7110 #undef TPACPI_FAN_QI
7111
7112 static int __init fan_init(struct ibm_init_struct *iibm)
7113 {
7114         int rc;
7115         unsigned long quirks;
7116
7117         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN,
7118                         "initializing fan subdriver\n");
7119
7120         mutex_init(&fan_mutex);
7121         fan_status_access_mode = TPACPI_FAN_NONE;
7122         fan_control_access_mode = TPACPI_FAN_WR_NONE;
7123         fan_control_commands = 0;
7124         fan_watchdog_maxinterval = 0;
7125         tp_features.fan_ctrl_status_undef = 0;
7126         tp_features.second_fan = 0;
7127         fan_control_desired_level = 7;
7128
7129         TPACPI_ACPIHANDLE_INIT(fans);
7130         TPACPI_ACPIHANDLE_INIT(gfan);
7131         TPACPI_ACPIHANDLE_INIT(sfan);
7132
7133         quirks = tpacpi_check_quirks(fan_quirk_table,
7134                                      ARRAY_SIZE(fan_quirk_table));
7135
7136         if (gfan_handle) {
7137                 /* 570, 600e/x, 770e, 770x */
7138                 fan_status_access_mode = TPACPI_FAN_RD_ACPI_GFAN;
7139         } else {
7140                 /* all other ThinkPads: note that even old-style
7141                  * ThinkPad ECs supports the fan control register */
7142                 if (likely(acpi_ec_read(fan_status_offset,
7143                                         &fan_control_initial_status))) {
7144                         fan_status_access_mode = TPACPI_FAN_RD_TPEC;
7145                         if (quirks & TPACPI_FAN_Q1)
7146                                 fan_quirk1_setup();
7147                         if (quirks & TPACPI_FAN_2FAN) {
7148                                 tp_features.second_fan = 1;
7149                                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN,
7150                                         "secondary fan support enabled\n");
7151                         }
7152                 } else {
7153                         printk(TPACPI_ERR
7154                                "ThinkPad ACPI EC access misbehaving, "
7155                                "fan status and control unavailable\n");
7156                         return 1;
7157                 }
7158         }
7159
7160         if (sfan_handle) {
7161                 /* 570, 770x-JL */
7162                 fan_control_access_mode = TPACPI_FAN_WR_ACPI_SFAN;
7163                 fan_control_commands |=
7164                     TPACPI_FAN_CMD_LEVEL | TPACPI_FAN_CMD_ENABLE;
7165         } else {
7166                 if (!gfan_handle) {
7167                         /* gfan without sfan means no fan control */
7168                         /* all other models implement TP EC 0x2f control */
7169
7170                         if (fans_handle) {
7171                                 /* X31, X40, X41 */
7172                                 fan_control_access_mode =
7173                                     TPACPI_FAN_WR_ACPI_FANS;
7174                                 fan_control_commands |=
7175                                     TPACPI_FAN_CMD_SPEED |
7176                                     TPACPI_FAN_CMD_LEVEL |
7177                                     TPACPI_FAN_CMD_ENABLE;
7178                         } else {
7179                                 fan_control_access_mode = TPACPI_FAN_WR_TPEC;
7180                                 fan_control_commands |=
7181                                     TPACPI_FAN_CMD_LEVEL |
7182                                     TPACPI_FAN_CMD_ENABLE;
7183                         }
7184                 }
7185         }
7186
7187         vdbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN,
7188                 "fan is %s, modes %d, %d\n",
7189                 str_supported(fan_status_access_mode != TPACPI_FAN_NONE ||
7190                   fan_control_access_mode != TPACPI_FAN_WR_NONE),
7191                 fan_status_access_mode, fan_control_access_mode);
7192
7193         /* fan control master switch */
7194         if (!fan_control_allowed) {
7195                 fan_control_access_mode = TPACPI_FAN_WR_NONE;
7196                 fan_control_commands = 0;
7197                 dbg_printk(TPACPI_DBG_INIT | TPACPI_DBG_FAN,
7198                            "fan control features disabled by parameter\n");
7199         }
7200
7201         /* update fan_control_desired_level */
7202         if (fan_status_access_mode != TPACPI_FAN_NONE)
7203                 fan_get_status_safe(NULL);
7204
7205         if (fan_status_access_mode != TPACPI_FAN_NONE ||
7206             fan_control_access_mode != TPACPI_FAN_WR_NONE) {
7207                 if (tp_features.second_fan) {
7208                         /* attach second fan tachometer */
7209                         fan_attributes[ARRAY_SIZE(fan_attributes)-2] =
7210                                         &dev_attr_fan_fan2_input.attr;
7211                 }
7212                 rc = sysfs_create_group(&tpacpi_sensors_pdev->dev.kobj,
7213                                          &fan_attr_group);
7214                 if (rc < 0)
7215                         return rc;
7216
7217                 rc = driver_create_file(&tpacpi_hwmon_pdriver.driver,
7218                                         &driver_attr_fan_watchdog);
7219                 if (rc < 0) {
7220                         sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj,
7221                                         &fan_attr_group);
7222                         return rc;
7223                 }
7224                 return 0;
7225         } else
7226                 return 1;
7227 }
7228
7229 static void fan_exit(void)
7230 {
7231         vdbg_printk(TPACPI_DBG_EXIT | TPACPI_DBG_FAN,
7232                     "cancelling any pending fan watchdog tasks\n");
7233
7234         /* FIXME: can we really do this unconditionally? */
7235         sysfs_remove_group(&tpacpi_sensors_pdev->dev.kobj, &fan_attr_group);
7236         driver_remove_file(&tpacpi_hwmon_pdriver.driver,
7237                            &driver_attr_fan_watchdog);
7238
7239         cancel_delayed_work(&fan_watchdog_task);
7240         flush_workqueue(tpacpi_wq);
7241 }
7242
7243 static void fan_suspend(pm_message_t state)
7244 {
7245         int rc;
7246
7247         if (!fan_control_allowed)
7248                 return;
7249
7250         /* Store fan status in cache */
7251         fan_control_resume_level = 0;
7252         rc = fan_get_status_safe(&fan_control_resume_level);
7253         if (rc < 0)
7254                 printk(TPACPI_NOTICE
7255                         "failed to read fan level for later "
7256                         "restore during resume: %d\n", rc);
7257
7258         /* if it is undefined, don't attempt to restore it.
7259          * KEEP THIS LAST */
7260         if (tp_features.fan_ctrl_status_undef)
7261                 fan_control_resume_level = 0;
7262 }
7263
7264 static void fan_resume(void)
7265 {
7266         u8 current_level = 7;
7267         bool do_set = false;
7268         int rc;
7269
7270         /* DSDT *always* updates status on resume */
7271         tp_features.fan_ctrl_status_undef = 0;
7272
7273         if (!fan_control_allowed ||
7274             !fan_control_resume_level ||
7275             (fan_get_status_safe(&current_level) < 0))
7276                 return;
7277
7278         switch (fan_control_access_mode) {
7279         case TPACPI_FAN_WR_ACPI_SFAN:
7280                 /* never decrease fan level */
7281                 do_set = (fan_control_resume_level > current_level);
7282                 break;
7283         case TPACPI_FAN_WR_ACPI_FANS:
7284         case TPACPI_FAN_WR_TPEC:
7285                 /* never decrease fan level, scale is:
7286                  * TP_EC_FAN_FULLSPEED > 7 >= TP_EC_FAN_AUTO
7287                  *
7288                  * We expect the firmware to set either 7 or AUTO, but we
7289                  * handle FULLSPEED out of paranoia.
7290                  *
7291                  * So, we can safely only restore FULLSPEED or 7, anything
7292                  * else could slow the fan.  Restoring AUTO is useless, at
7293                  * best that's exactly what the DSDT already set (it is the
7294                  * slower it uses).
7295                  *
7296                  * Always keep in mind that the DSDT *will* have set the
7297                  * fans to what the vendor supposes is the best level.  We
7298                  * muck with it only to speed the fan up.
7299                  */
7300                 if (fan_control_resume_level != 7 &&
7301                     !(fan_control_resume_level & TP_EC_FAN_FULLSPEED))
7302                         return;
7303                 else
7304                         do_set = !(current_level & TP_EC_FAN_FULLSPEED) &&
7305                                  (current_level != fan_control_resume_level);
7306                 break;
7307         default:
7308                 return;
7309         }
7310         if (do_set) {
7311                 printk(TPACPI_NOTICE
7312                         "restoring fan level to 0x%02x\n",
7313                         fan_control_resume_level);
7314                 rc = fan_set_level_safe(fan_control_resume_level);
7315                 if (rc < 0)
7316                         printk(TPACPI_NOTICE
7317                                 "failed to restore fan level: %d\n", rc);
7318         }
7319 }
7320
7321 static int fan_read(char *p)
7322 {
7323         int len = 0;
7324         int rc;
7325         u8 status;
7326         unsigned int speed = 0;
7327
7328         switch (fan_status_access_mode) {
7329         case TPACPI_FAN_RD_ACPI_GFAN:
7330                 /* 570, 600e/x, 770e, 770x */
7331                 rc = fan_get_status_safe(&status);
7332                 if (rc < 0)
7333                         return rc;
7334
7335                 len += sprintf(p + len, "status:\t\t%s\n"
7336                                "level:\t\t%d\n",
7337                                (status != 0) ? "enabled" : "disabled", status);
7338                 break;
7339
7340         case TPACPI_FAN_RD_TPEC:
7341                 /* all except 570, 600e/x, 770e, 770x */
7342                 rc = fan_get_status_safe(&status);
7343                 if (rc < 0)
7344                         return rc;
7345
7346                 len += sprintf(p + len, "status:\t\t%s\n",
7347                                (status != 0) ? "enabled" : "disabled");
7348
7349                 rc = fan_get_speed(&speed);
7350                 if (rc < 0)
7351                         return rc;
7352
7353                 len += sprintf(p + len, "speed:\t\t%d\n", speed);
7354
7355                 if (status & TP_EC_FAN_FULLSPEED)
7356                         /* Disengaged mode takes precedence */
7357                         len += sprintf(p + len, "level:\t\tdisengaged\n");
7358                 else if (status & TP_EC_FAN_AUTO)
7359                         len += sprintf(p + len, "level:\t\tauto\n");
7360                 else
7361                         len += sprintf(p + len, "level:\t\t%d\n", status);
7362                 break;
7363
7364         case TPACPI_FAN_NONE:
7365         default:
7366                 len += sprintf(p + len, "status:\t\tnot supported\n");
7367         }
7368
7369         if (fan_control_commands & TPACPI_FAN_CMD_LEVEL) {
7370                 len += sprintf(p + len, "commands:\tlevel <level>");
7371
7372                 switch (fan_control_access_mode) {
7373                 case TPACPI_FAN_WR_ACPI_SFAN:
7374                         len += sprintf(p + len, " (<level> is 0-7)\n");
7375                         break;
7376
7377                 default:
7378                         len += sprintf(p + len, " (<level> is 0-7, "
7379                                        "auto, disengaged, full-speed)\n");
7380                         break;
7381                 }
7382         }
7383
7384         if (fan_control_commands & TPACPI_FAN_CMD_ENABLE)
7385                 len += sprintf(p + len, "commands:\tenable, disable\n"
7386                                "commands:\twatchdog <timeout> (<timeout> "
7387                                "is 0 (off), 1-120 (seconds))\n");
7388
7389         if (fan_control_commands & TPACPI_FAN_CMD_SPEED)
7390                 len += sprintf(p + len, "commands:\tspeed <speed>"
7391                                " (<speed> is 0-65535)\n");
7392
7393         return len;
7394 }
7395
7396 static int fan_write_cmd_level(const char *cmd, int *rc)
7397 {
7398         int level;
7399
7400         if (strlencmp(cmd, "level auto") == 0)
7401                 level = TP_EC_FAN_AUTO;
7402         else if ((strlencmp(cmd, "level disengaged") == 0) |
7403                         (strlencmp(cmd, "level full-speed") == 0))
7404                 level = TP_EC_FAN_FULLSPEED;
7405         else if (sscanf(cmd, "level %d", &level) != 1)
7406                 return 0;
7407
7408         *rc = fan_set_level_safe(level);
7409         if (*rc == -ENXIO)
7410                 printk(TPACPI_ERR "level command accepted for unsupported "
7411                        "access mode %d", fan_control_access_mode);
7412         else if (!*rc)
7413                 tpacpi_disclose_usertask("procfs fan",
7414                         "set level to %d\n", level);
7415
7416         return 1;
7417 }
7418
7419 static int fan_write_cmd_enable(const char *cmd, int *rc)
7420 {
7421         if (strlencmp(cmd, "enable") != 0)
7422                 return 0;
7423
7424         *rc = fan_set_enable();
7425         if (*rc == -ENXIO)
7426                 printk(TPACPI_ERR "enable command accepted for unsupported "
7427                        "access mode %d", fan_control_access_mode);
7428         else if (!*rc)
7429                 tpacpi_disclose_usertask("procfs fan", "enable\n");
7430
7431         return 1;
7432 }
7433
7434 static int fan_write_cmd_disable(const char *cmd, int *rc)
7435 {
7436         if (strlencmp(cmd, "disable") != 0)
7437                 return 0;
7438
7439         *rc = fan_set_disable();
7440         if (*rc == -ENXIO)
7441                 printk(TPACPI_ERR "disable command accepted for unsupported "
7442                        "access mode %d", fan_control_access_mode);
7443         else if (!*rc)
7444                 tpacpi_disclose_usertask("procfs fan", "disable\n");
7445
7446         return 1;
7447 }
7448
7449 static int fan_write_cmd_speed(const char *cmd, int *rc)
7450 {
7451         int speed;
7452
7453         /* TODO:
7454          * Support speed <low> <medium> <high> ? */
7455
7456         if (sscanf(cmd, "speed %d", &speed) != 1)
7457                 return 0;
7458
7459         *rc = fan_set_speed(speed);
7460         if (*rc == -ENXIO)
7461                 printk(TPACPI_ERR "speed command accepted for unsupported "
7462                        "access mode %d", fan_control_access_mode);
7463         else if (!*rc)
7464                 tpacpi_disclose_usertask("procfs fan",
7465                         "set speed to %d\n", speed);
7466
7467         return 1;
7468 }
7469
7470 static int fan_write_cmd_watchdog(const char *cmd, int *rc)
7471 {
7472         int interval;
7473
7474         if (sscanf(cmd, "watchdog %d", &interval) != 1)
7475                 return 0;
7476
7477         if (interval < 0 || interval > 120)
7478                 *rc = -EINVAL;
7479         else {
7480                 fan_watchdog_maxinterval = interval;
7481                 tpacpi_disclose_usertask("procfs fan",
7482                         "set watchdog timer to %d\n",
7483                         interval);
7484         }
7485
7486         return 1;
7487 }
7488
7489 static int fan_write(char *buf)
7490 {
7491         char *cmd;
7492         int rc = 0;
7493
7494         while (!rc && (cmd = next_cmd(&buf))) {
7495                 if (!((fan_control_commands & TPACPI_FAN_CMD_LEVEL) &&
7496                       fan_write_cmd_level(cmd, &rc)) &&
7497                     !((fan_control_commands & TPACPI_FAN_CMD_ENABLE) &&
7498                       (fan_write_cmd_enable(cmd, &rc) ||
7499                        fan_write_cmd_disable(cmd, &rc) ||
7500                        fan_write_cmd_watchdog(cmd, &rc))) &&
7501                     !((fan_control_commands & TPACPI_FAN_CMD_SPEED) &&
7502                       fan_write_cmd_speed(cmd, &rc))
7503                     )
7504                         rc = -EINVAL;
7505                 else if (!rc)
7506                         fan_watchdog_reset();
7507         }
7508
7509         return rc;
7510 }
7511
7512 static struct ibm_struct fan_driver_data = {
7513         .name = "fan",
7514         .read = fan_read,
7515         .write = fan_write,
7516         .exit = fan_exit,
7517         .suspend = fan_suspend,
7518         .resume = fan_resume,
7519 };
7520
7521 /****************************************************************************
7522  ****************************************************************************
7523  *
7524  * Infrastructure
7525  *
7526  ****************************************************************************
7527  ****************************************************************************/
7528
7529 /* sysfs name ---------------------------------------------------------- */
7530 static ssize_t thinkpad_acpi_pdev_name_show(struct device *dev,
7531                            struct device_attribute *attr,
7532                            char *buf)
7533 {
7534         return snprintf(buf, PAGE_SIZE, "%s\n", TPACPI_NAME);
7535 }
7536
7537 static struct device_attribute dev_attr_thinkpad_acpi_pdev_name =
7538         __ATTR(name, S_IRUGO, thinkpad_acpi_pdev_name_show, NULL);
7539
7540 /* --------------------------------------------------------------------- */
7541
7542 /* /proc support */
7543 static struct proc_dir_entry *proc_dir;
7544
7545 /*
7546  * Module and infrastructure proble, init and exit handling
7547  */
7548
7549 static int force_load;
7550
7551 #ifdef CONFIG_THINKPAD_ACPI_DEBUG
7552 static const char * __init str_supported(int is_supported)
7553 {
7554         static char text_unsupported[] __initdata = "not supported";
7555
7556         return (is_supported)? &text_unsupported[4] : &text_unsupported[0];
7557 }
7558 #endif /* CONFIG_THINKPAD_ACPI_DEBUG */
7559
7560 static void ibm_exit(struct ibm_struct *ibm)
7561 {
7562         dbg_printk(TPACPI_DBG_EXIT, "removing %s\n", ibm->name);
7563
7564         list_del_init(&ibm->all_drivers);
7565
7566         if (ibm->flags.acpi_notify_installed) {
7567                 dbg_printk(TPACPI_DBG_EXIT,
7568                         "%s: acpi_remove_notify_handler\n", ibm->name);
7569                 BUG_ON(!ibm->acpi);
7570                 acpi_remove_notify_handler(*ibm->acpi->handle,
7571                                            ibm->acpi->type,
7572                                            dispatch_acpi_notify);
7573                 ibm->flags.acpi_notify_installed = 0;
7574                 ibm->flags.acpi_notify_installed = 0;
7575         }
7576
7577         if (ibm->flags.proc_created) {
7578                 dbg_printk(TPACPI_DBG_EXIT,
7579                         "%s: remove_proc_entry\n", ibm->name);
7580                 remove_proc_entry(ibm->name, proc_dir);
7581                 ibm->flags.proc_created = 0;
7582         }
7583
7584         if (ibm->flags.acpi_driver_registered) {
7585                 dbg_printk(TPACPI_DBG_EXIT,
7586                         "%s: acpi_bus_unregister_driver\n", ibm->name);
7587                 BUG_ON(!ibm->acpi);
7588                 acpi_bus_unregister_driver(ibm->acpi->driver);
7589                 kfree(ibm->acpi->driver);
7590                 ibm->acpi->driver = NULL;
7591                 ibm->flags.acpi_driver_registered = 0;
7592         }
7593
7594         if (ibm->flags.init_called && ibm->exit) {
7595                 ibm->exit();
7596                 ibm->flags.init_called = 0;
7597         }
7598
7599         dbg_printk(TPACPI_DBG_INIT, "finished removing %s\n", ibm->name);
7600 }
7601
7602 static int __init ibm_init(struct ibm_init_struct *iibm)
7603 {
7604         int ret;
7605         struct ibm_struct *ibm = iibm->data;
7606         struct proc_dir_entry *entry;
7607
7608         BUG_ON(ibm == NULL);
7609
7610         INIT_LIST_HEAD(&ibm->all_drivers);
7611
7612         if (ibm->flags.experimental && !experimental)
7613                 return 0;
7614
7615         dbg_printk(TPACPI_DBG_INIT,
7616                 "probing for %s\n", ibm->name);
7617
7618         if (iibm->init) {
7619                 ret = iibm->init(iibm);
7620                 if (ret > 0)
7621                         return 0;       /* probe failed */
7622                 if (ret)
7623                         return ret;
7624
7625                 ibm->flags.init_called = 1;
7626         }
7627
7628         if (ibm->acpi) {
7629                 if (ibm->acpi->hid) {
7630                         ret = register_tpacpi_subdriver(ibm);
7631                         if (ret)
7632                                 goto err_out;
7633                 }
7634
7635                 if (ibm->acpi->notify) {
7636                         ret = setup_acpi_notify(ibm);
7637                         if (ret == -ENODEV) {
7638                                 printk(TPACPI_NOTICE "disabling subdriver %s\n",
7639                                         ibm->name);
7640                                 ret = 0;
7641                                 goto err_out;
7642                         }
7643                         if (ret < 0)
7644                                 goto err_out;
7645                 }
7646         }
7647
7648         dbg_printk(TPACPI_DBG_INIT,
7649                 "%s installed\n", ibm->name);
7650
7651         if (ibm->read) {
7652                 entry = create_proc_entry(ibm->name,
7653                                           S_IFREG | S_IRUGO | S_IWUSR,
7654                                           proc_dir);
7655                 if (!entry) {
7656                         printk(TPACPI_ERR "unable to create proc entry %s\n",
7657                                ibm->name);
7658                         ret = -ENODEV;
7659                         goto err_out;
7660                 }
7661                 entry->data = ibm;
7662                 entry->read_proc = &dispatch_procfs_read;
7663                 if (ibm->write)
7664                         entry->write_proc = &dispatch_procfs_write;
7665                 ibm->flags.proc_created = 1;
7666         }
7667
7668         list_add_tail(&ibm->all_drivers, &tpacpi_all_drivers);
7669
7670         return 0;
7671
7672 err_out:
7673         dbg_printk(TPACPI_DBG_INIT,
7674                 "%s: at error exit path with result %d\n",
7675                 ibm->name, ret);
7676
7677         ibm_exit(ibm);
7678         return (ret < 0)? ret : 0;
7679 }
7680
7681 /* Probing */
7682
7683 static bool __pure __init tpacpi_is_fw_digit(const char c)
7684 {
7685         return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z');
7686 }
7687
7688 /* Most models: xxyTkkWW (#.##c); Ancient 570/600 and -SL lacks (#.##c) */
7689 static bool __pure __init tpacpi_is_valid_fw_id(const char* const s,
7690                                                 const char t)
7691 {
7692         return s && strlen(s) >= 8 &&
7693                 tpacpi_is_fw_digit(s[0]) &&
7694                 tpacpi_is_fw_digit(s[1]) &&
7695                 s[2] == t && s[3] == 'T' &&
7696                 tpacpi_is_fw_digit(s[4]) &&
7697                 tpacpi_is_fw_digit(s[5]) &&
7698                 s[6] == 'W' && s[7] == 'W';
7699 }
7700
7701 /* returns 0 - probe ok, or < 0 - probe error.
7702  * Probe ok doesn't mean thinkpad found.
7703  * On error, kfree() cleanup on tp->* is not performed, caller must do it */
7704 static int __must_check __init get_thinkpad_model_data(
7705                                                 struct thinkpad_id_data *tp)
7706 {
7707         const struct dmi_device *dev = NULL;
7708         char ec_fw_string[18];
7709         char const *s;
7710
7711         if (!tp)
7712                 return -EINVAL;
7713
7714         memset(tp, 0, sizeof(*tp));
7715
7716         if (dmi_name_in_vendors("IBM"))
7717                 tp->vendor = PCI_VENDOR_ID_IBM;
7718         else if (dmi_name_in_vendors("LENOVO"))
7719                 tp->vendor = PCI_VENDOR_ID_LENOVO;
7720         else
7721                 return 0;
7722
7723         s = dmi_get_system_info(DMI_BIOS_VERSION);
7724         tp->bios_version_str = kstrdup(s, GFP_KERNEL);
7725         if (s && !tp->bios_version_str)
7726                 return -ENOMEM;
7727
7728         /* Really ancient ThinkPad 240X will fail this, which is fine */
7729         if (!tpacpi_is_valid_fw_id(tp->bios_version_str, 'E'))
7730                 return 0;
7731
7732         tp->bios_model = tp->bios_version_str[0]
7733                          | (tp->bios_version_str[1] << 8);
7734         tp->bios_release = (tp->bios_version_str[4] << 8)
7735                          | tp->bios_version_str[5];
7736
7737         /*
7738          * ThinkPad T23 or newer, A31 or newer, R50e or newer,
7739          * X32 or newer, all Z series;  Some models must have an
7740          * up-to-date BIOS or they will not be detected.
7741          *
7742          * See http://thinkwiki.org/wiki/List_of_DMI_IDs
7743          */
7744         while ((dev = dmi_find_device(DMI_DEV_TYPE_OEM_STRING, NULL, dev))) {
7745                 if (sscanf(dev->name,
7746                            "IBM ThinkPad Embedded Controller -[%17c",
7747                            ec_fw_string) == 1) {
7748                         ec_fw_string[sizeof(ec_fw_string) - 1] = 0;
7749                         ec_fw_string[strcspn(ec_fw_string, " ]")] = 0;
7750
7751                         tp->ec_version_str = kstrdup(ec_fw_string, GFP_KERNEL);
7752                         if (!tp->ec_version_str)
7753                                 return -ENOMEM;
7754
7755                         if (tpacpi_is_valid_fw_id(ec_fw_string, 'H')) {
7756                                 tp->ec_model = ec_fw_string[0]
7757                                                 | (ec_fw_string[1] << 8);
7758                                 tp->ec_release = (ec_fw_string[4] << 8)
7759                                                 | ec_fw_string[5];
7760                         } else {
7761                                 printk(TPACPI_NOTICE
7762                                         "ThinkPad firmware release %s "
7763                                         "doesn't match the known patterns\n",
7764                                         ec_fw_string);
7765                                 printk(TPACPI_NOTICE
7766                                         "please report this to %s\n",
7767                                         TPACPI_MAIL);
7768                         }
7769                         break;
7770                 }
7771         }
7772
7773         s = dmi_get_system_info(DMI_PRODUCT_VERSION);
7774         if (s && !strnicmp(s, "ThinkPad", 8)) {
7775                 tp->model_str = kstrdup(s, GFP_KERNEL);
7776                 if (!tp->model_str)
7777                         return -ENOMEM;
7778         }
7779
7780         s = dmi_get_system_info(DMI_PRODUCT_NAME);
7781         tp->nummodel_str = kstrdup(s, GFP_KERNEL);
7782         if (s && !tp->nummodel_str)
7783                 return -ENOMEM;
7784
7785         return 0;
7786 }
7787
7788 static int __init probe_for_thinkpad(void)
7789 {
7790         int is_thinkpad;
7791
7792         if (acpi_disabled)
7793                 return -ENODEV;
7794
7795         /*
7796          * Non-ancient models have better DMI tagging, but very old models
7797          * don't.
7798          */
7799         is_thinkpad = (thinkpad_id.model_str != NULL);
7800
7801         /* ec is required because many other handles are relative to it */
7802         TPACPI_ACPIHANDLE_INIT(ec);
7803         if (!ec_handle) {
7804                 if (is_thinkpad)
7805                         printk(TPACPI_ERR
7806                                 "Not yet supported ThinkPad detected!\n");
7807                 return -ENODEV;
7808         }
7809
7810         /*
7811          * Risks a regression on very old machines, but reduces potential
7812          * false positives a damn great deal
7813          */
7814         if (!is_thinkpad)
7815                 is_thinkpad = (thinkpad_id.vendor == PCI_VENDOR_ID_IBM);
7816
7817         if (!is_thinkpad && !force_load)
7818                 return -ENODEV;
7819
7820         return 0;
7821 }
7822
7823
7824 /* Module init, exit, parameters */
7825
7826 static struct ibm_init_struct ibms_init[] __initdata = {
7827         {
7828                 .init = thinkpad_acpi_driver_init,
7829                 .data = &thinkpad_acpi_driver_data,
7830         },
7831         {
7832                 .init = hotkey_init,
7833                 .data = &hotkey_driver_data,
7834         },
7835         {
7836                 .init = bluetooth_init,
7837                 .data = &bluetooth_driver_data,
7838         },
7839         {
7840                 .init = wan_init,
7841                 .data = &wan_driver_data,
7842         },
7843         {
7844                 .init = uwb_init,
7845                 .data = &uwb_driver_data,
7846         },
7847 #ifdef CONFIG_THINKPAD_ACPI_VIDEO
7848         {
7849                 .init = video_init,
7850                 .data = &video_driver_data,
7851         },
7852 #endif
7853         {
7854                 .init = light_init,
7855                 .data = &light_driver_data,
7856         },
7857 #ifdef CONFIG_THINKPAD_ACPI_DOCK
7858         {
7859                 .init = dock_init,
7860                 .data = &dock_driver_data[0],
7861         },
7862         {
7863                 .init = dock_init2,
7864                 .data = &dock_driver_data[1],
7865         },
7866 #endif
7867 #ifdef CONFIG_THINKPAD_ACPI_BAY
7868         {
7869                 .init = bay_init,
7870                 .data = &bay_driver_data,
7871         },
7872 #endif
7873         {
7874                 .init = cmos_init,
7875                 .data = &cmos_driver_data,
7876         },
7877         {
7878                 .init = led_init,
7879                 .data = &led_driver_data,
7880         },
7881         {
7882                 .init = beep_init,
7883                 .data = &beep_driver_data,
7884         },
7885         {
7886                 .init = thermal_init,
7887                 .data = &thermal_driver_data,
7888         },
7889         {
7890                 .data = &ecdump_driver_data,
7891         },
7892         {
7893                 .init = brightness_init,
7894                 .data = &brightness_driver_data,
7895         },
7896         {
7897                 .data = &volume_driver_data,
7898         },
7899         {
7900                 .init = fan_init,
7901                 .data = &fan_driver_data,
7902         },
7903 };
7904
7905 static int __init set_ibm_param(const char *val, struct kernel_param *kp)
7906 {
7907         unsigned int i;
7908         struct ibm_struct *ibm;
7909
7910         if (!kp || !kp->name || !val)
7911                 return -EINVAL;
7912
7913         for (i = 0; i < ARRAY_SIZE(ibms_init); i++) {
7914                 ibm = ibms_init[i].data;
7915                 WARN_ON(ibm == NULL);
7916
7917                 if (!ibm || !ibm->name)
7918                         continue;
7919
7920                 if (strcmp(ibm->name, kp->name) == 0 && ibm->write) {
7921                         if (strlen(val) > sizeof(ibms_init[i].param) - 2)
7922                                 return -ENOSPC;
7923                         strcpy(ibms_init[i].param, val);
7924                         strcat(ibms_init[i].param, ",");
7925                         return 0;
7926                 }
7927         }
7928
7929         return -EINVAL;
7930 }
7931
7932 module_param(experimental, int, 0);
7933 MODULE_PARM_DESC(experimental,
7934                  "Enables experimental features when non-zero");
7935
7936 module_param_named(debug, dbg_level, uint, 0);
7937 MODULE_PARM_DESC(debug, "Sets debug level bit-mask");
7938
7939 module_param(force_load, bool, 0);
7940 MODULE_PARM_DESC(force_load,
7941                  "Attempts to load the driver even on a "
7942                  "mis-identified ThinkPad when true");
7943
7944 module_param_named(fan_control, fan_control_allowed, bool, 0);
7945 MODULE_PARM_DESC(fan_control,
7946                  "Enables setting fan parameters features when true");
7947
7948 module_param_named(brightness_mode, brightness_mode, uint, 0);
7949 MODULE_PARM_DESC(brightness_mode,
7950                  "Selects brightness control strategy: "
7951                  "0=auto, 1=EC, 2=UCMS, 3=EC+NVRAM");
7952
7953 module_param(brightness_enable, uint, 0);
7954 MODULE_PARM_DESC(brightness_enable,
7955                  "Enables backlight control when 1, disables when 0");
7956
7957 module_param(hotkey_report_mode, uint, 0);
7958 MODULE_PARM_DESC(hotkey_report_mode,
7959                  "used for backwards compatibility with userspace, "
7960                  "see documentation");
7961
7962 #define TPACPI_PARAM(feature) \
7963         module_param_call(feature, set_ibm_param, NULL, NULL, 0); \
7964         MODULE_PARM_DESC(feature, "Simulates thinkpad-acpi procfs command " \
7965                          "at module load, see documentation")
7966
7967 TPACPI_PARAM(hotkey);
7968 TPACPI_PARAM(bluetooth);
7969 TPACPI_PARAM(video);
7970 TPACPI_PARAM(light);
7971 #ifdef CONFIG_THINKPAD_ACPI_DOCK
7972 TPACPI_PARAM(dock);
7973 #endif
7974 #ifdef CONFIG_THINKPAD_ACPI_BAY
7975 TPACPI_PARAM(bay);
7976 #endif /* CONFIG_THINKPAD_ACPI_BAY */
7977 TPACPI_PARAM(cmos);
7978 TPACPI_PARAM(led);
7979 TPACPI_PARAM(beep);
7980 TPACPI_PARAM(ecdump);
7981 TPACPI_PARAM(brightness);
7982 TPACPI_PARAM(volume);
7983 TPACPI_PARAM(fan);
7984
7985 #ifdef CONFIG_THINKPAD_ACPI_DEBUGFACILITIES
7986 module_param(dbg_wlswemul, uint, 0);
7987 MODULE_PARM_DESC(dbg_wlswemul, "Enables WLSW emulation");
7988 module_param_named(wlsw_state, tpacpi_wlsw_emulstate, bool, 0);
7989 MODULE_PARM_DESC(wlsw_state,
7990                  "Initial state of the emulated WLSW switch");
7991
7992 module_param(dbg_bluetoothemul, uint, 0);
7993 MODULE_PARM_DESC(dbg_bluetoothemul, "Enables bluetooth switch emulation");
7994 module_param_named(bluetooth_state, tpacpi_bluetooth_emulstate, bool, 0);
7995 MODULE_PARM_DESC(bluetooth_state,
7996                  "Initial state of the emulated bluetooth switch");
7997
7998 module_param(dbg_wwanemul, uint, 0);
7999 MODULE_PARM_DESC(dbg_wwanemul, "Enables WWAN switch emulation");
8000 module_param_named(wwan_state, tpacpi_wwan_emulstate, bool, 0);
8001 MODULE_PARM_DESC(wwan_state,
8002                  "Initial state of the emulated WWAN switch");
8003
8004 module_param(dbg_uwbemul, uint, 0);
8005 MODULE_PARM_DESC(dbg_uwbemul, "Enables UWB switch emulation");
8006 module_param_named(uwb_state, tpacpi_uwb_emulstate, bool, 0);
8007 MODULE_PARM_DESC(uwb_state,
8008                  "Initial state of the emulated UWB switch");
8009 #endif
8010
8011 static void thinkpad_acpi_module_exit(void)
8012 {
8013         struct ibm_struct *ibm, *itmp;
8014
8015         tpacpi_lifecycle = TPACPI_LIFE_EXITING;
8016
8017         list_for_each_entry_safe_reverse(ibm, itmp,
8018                                          &tpacpi_all_drivers,
8019                                          all_drivers) {
8020                 ibm_exit(ibm);
8021         }
8022
8023         dbg_printk(TPACPI_DBG_INIT, "finished subdriver exit path...\n");
8024
8025         if (tpacpi_inputdev) {
8026                 if (tp_features.input_device_registered)
8027                         input_unregister_device(tpacpi_inputdev);
8028                 else
8029                         input_free_device(tpacpi_inputdev);
8030         }
8031
8032         if (tpacpi_hwmon)
8033                 hwmon_device_unregister(tpacpi_hwmon);
8034
8035         if (tp_features.sensors_pdev_attrs_registered)
8036                 device_remove_file(&tpacpi_sensors_pdev->dev,
8037                                    &dev_attr_thinkpad_acpi_pdev_name);
8038         if (tpacpi_sensors_pdev)
8039                 platform_device_unregister(tpacpi_sensors_pdev);
8040         if (tpacpi_pdev)
8041                 platform_device_unregister(tpacpi_pdev);
8042
8043         if (tp_features.sensors_pdrv_attrs_registered)
8044                 tpacpi_remove_driver_attributes(&tpacpi_hwmon_pdriver.driver);
8045         if (tp_features.platform_drv_attrs_registered)
8046                 tpacpi_remove_driver_attributes(&tpacpi_pdriver.driver);
8047
8048         if (tp_features.sensors_pdrv_registered)
8049                 platform_driver_unregister(&tpacpi_hwmon_pdriver);
8050
8051         if (tp_features.platform_drv_registered)
8052                 platform_driver_unregister(&tpacpi_pdriver);
8053
8054         if (proc_dir)
8055                 remove_proc_entry(TPACPI_PROC_DIR, acpi_root_dir);
8056
8057         if (tpacpi_wq)
8058                 destroy_workqueue(tpacpi_wq);
8059
8060         kfree(thinkpad_id.bios_version_str);
8061         kfree(thinkpad_id.ec_version_str);
8062         kfree(thinkpad_id.model_str);
8063 }
8064
8065
8066 static int __init thinkpad_acpi_module_init(void)
8067 {
8068         int ret, i;
8069
8070         tpacpi_lifecycle = TPACPI_LIFE_INIT;
8071
8072         /* Parameter checking */
8073         if (hotkey_report_mode > 2)
8074                 return -EINVAL;
8075
8076         /* Driver-level probe */
8077
8078         ret = get_thinkpad_model_data(&thinkpad_id);
8079         if (ret) {
8080                 printk(TPACPI_ERR
8081                         "unable to get DMI data: %d\n", ret);
8082                 thinkpad_acpi_module_exit();
8083                 return ret;
8084         }
8085         ret = probe_for_thinkpad();
8086         if (ret) {
8087                 thinkpad_acpi_module_exit();
8088                 return ret;
8089         }
8090
8091         /* Driver initialization */
8092
8093         TPACPI_ACPIHANDLE_INIT(ecrd);
8094         TPACPI_ACPIHANDLE_INIT(ecwr);
8095
8096         tpacpi_wq = create_singlethread_workqueue(TPACPI_WORKQUEUE_NAME);
8097         if (!tpacpi_wq) {
8098                 thinkpad_acpi_module_exit();
8099                 return -ENOMEM;
8100         }
8101
8102         proc_dir = proc_mkdir(TPACPI_PROC_DIR, acpi_root_dir);
8103         if (!proc_dir) {
8104                 printk(TPACPI_ERR
8105                        "unable to create proc dir " TPACPI_PROC_DIR);
8106                 thinkpad_acpi_module_exit();
8107                 return -ENODEV;
8108         }
8109
8110         ret = platform_driver_register(&tpacpi_pdriver);
8111         if (ret) {
8112                 printk(TPACPI_ERR
8113                        "unable to register main platform driver\n");
8114                 thinkpad_acpi_module_exit();
8115                 return ret;
8116         }
8117         tp_features.platform_drv_registered = 1;
8118
8119         ret = platform_driver_register(&tpacpi_hwmon_pdriver);
8120         if (ret) {
8121                 printk(TPACPI_ERR
8122                        "unable to register hwmon platform driver\n");
8123                 thinkpad_acpi_module_exit();
8124                 return ret;
8125         }
8126         tp_features.sensors_pdrv_registered = 1;
8127
8128         ret = tpacpi_create_driver_attributes(&tpacpi_pdriver.driver);
8129         if (!ret) {
8130                 tp_features.platform_drv_attrs_registered = 1;
8131                 ret = tpacpi_create_driver_attributes(
8132                                         &tpacpi_hwmon_pdriver.driver);
8133         }
8134         if (ret) {
8135                 printk(TPACPI_ERR
8136                        "unable to create sysfs driver attributes\n");
8137                 thinkpad_acpi_module_exit();
8138                 return ret;
8139         }
8140         tp_features.sensors_pdrv_attrs_registered = 1;
8141
8142
8143         /* Device initialization */
8144         tpacpi_pdev = platform_device_register_simple(TPACPI_DRVR_NAME, -1,
8145                                                         NULL, 0);
8146         if (IS_ERR(tpacpi_pdev)) {
8147                 ret = PTR_ERR(tpacpi_pdev);
8148                 tpacpi_pdev = NULL;
8149                 printk(TPACPI_ERR "unable to register platform device\n");
8150                 thinkpad_acpi_module_exit();
8151                 return ret;
8152         }
8153         tpacpi_sensors_pdev = platform_device_register_simple(
8154                                                 TPACPI_HWMON_DRVR_NAME,
8155                                                 -1, NULL, 0);
8156         if (IS_ERR(tpacpi_sensors_pdev)) {
8157                 ret = PTR_ERR(tpacpi_sensors_pdev);
8158                 tpacpi_sensors_pdev = NULL;
8159                 printk(TPACPI_ERR
8160                        "unable to register hwmon platform device\n");
8161                 thinkpad_acpi_module_exit();
8162                 return ret;
8163         }
8164         ret = device_create_file(&tpacpi_sensors_pdev->dev,
8165                                  &dev_attr_thinkpad_acpi_pdev_name);
8166         if (ret) {
8167                 printk(TPACPI_ERR
8168                        "unable to create sysfs hwmon device attributes\n");
8169                 thinkpad_acpi_module_exit();
8170                 return ret;
8171         }
8172         tp_features.sensors_pdev_attrs_registered = 1;
8173         tpacpi_hwmon = hwmon_device_register(&tpacpi_sensors_pdev->dev);
8174         if (IS_ERR(tpacpi_hwmon)) {
8175                 ret = PTR_ERR(tpacpi_hwmon);
8176                 tpacpi_hwmon = NULL;
8177                 printk(TPACPI_ERR "unable to register hwmon device\n");
8178                 thinkpad_acpi_module_exit();
8179                 return ret;
8180         }
8181         mutex_init(&tpacpi_inputdev_send_mutex);
8182         tpacpi_inputdev = input_allocate_device();
8183         if (!tpacpi_inputdev) {
8184                 printk(TPACPI_ERR "unable to allocate input device\n");
8185                 thinkpad_acpi_module_exit();
8186                 return -ENOMEM;
8187         } else {
8188                 /* Prepare input device, but don't register */
8189                 tpacpi_inputdev->name = "ThinkPad Extra Buttons";
8190                 tpacpi_inputdev->phys = TPACPI_DRVR_NAME "/input0";
8191                 tpacpi_inputdev->id.bustype = BUS_HOST;
8192                 tpacpi_inputdev->id.vendor = (thinkpad_id.vendor) ?
8193                                                 thinkpad_id.vendor :
8194                                                 PCI_VENDOR_ID_IBM;
8195                 tpacpi_inputdev->id.product = TPACPI_HKEY_INPUT_PRODUCT;
8196                 tpacpi_inputdev->id.version = TPACPI_HKEY_INPUT_VERSION;
8197         }
8198         for (i = 0; i < ARRAY_SIZE(ibms_init); i++) {
8199                 ret = ibm_init(&ibms_init[i]);
8200                 if (ret >= 0 && *ibms_init[i].param)
8201                         ret = ibms_init[i].data->write(ibms_init[i].param);
8202                 if (ret < 0) {
8203                         thinkpad_acpi_module_exit();
8204                         return ret;
8205                 }
8206         }
8207         ret = input_register_device(tpacpi_inputdev);
8208         if (ret < 0) {
8209                 printk(TPACPI_ERR "unable to register input device\n");
8210                 thinkpad_acpi_module_exit();
8211                 return ret;
8212         } else {
8213                 tp_features.input_device_registered = 1;
8214         }
8215
8216         tpacpi_lifecycle = TPACPI_LIFE_RUNNING;
8217         return 0;
8218 }
8219
8220 MODULE_ALIAS(TPACPI_DRVR_SHORTNAME);
8221
8222 /*
8223  * This will autoload the driver in almost every ThinkPad
8224  * in widespread use.
8225  *
8226  * Only _VERY_ old models, like the 240, 240x and 570 lack
8227  * the HKEY event interface.
8228  */
8229 MODULE_DEVICE_TABLE(acpi, ibm_htk_device_ids);
8230
8231 /*
8232  * DMI matching for module autoloading
8233  *
8234  * See http://thinkwiki.org/wiki/List_of_DMI_IDs
8235  * See http://thinkwiki.org/wiki/BIOS_Upgrade_Downloads
8236  *
8237  * Only models listed in thinkwiki will be supported, so add yours
8238  * if it is not there yet.
8239  */
8240 #define IBM_BIOS_MODULE_ALIAS(__type) \
8241         MODULE_ALIAS("dmi:bvnIBM:bvr" __type "ET??WW*")
8242
8243 /* Ancient thinkpad BIOSes have to be identified by
8244  * BIOS type or model number, and there are far less
8245  * BIOS types than model numbers... */
8246 IBM_BIOS_MODULE_ALIAS("I[MU]");         /* 570, 570e */
8247
8248 MODULE_AUTHOR("Borislav Deianov <borislav@users.sf.net>");
8249 MODULE_AUTHOR("Henrique de Moraes Holschuh <hmh@hmh.eng.br>");
8250 MODULE_DESCRIPTION(TPACPI_DESC);
8251 MODULE_VERSION(TPACPI_VERSION);
8252 MODULE_LICENSE("GPL");
8253
8254 module_init(thinkpad_acpi_module_init);
8255 module_exit(thinkpad_acpi_module_exit);