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