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