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