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