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