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