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