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