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