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