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