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