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