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