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