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