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