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