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