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