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