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