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