1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * MacBook (Pro) SPI keyboard and touchpad driver
4  *
5  * Copyright (c) 2015-2018 Federico Lorenzi
6  * Copyright (c) 2017-2018 Ronald Tschalär
7  */
8 
9 /*
10  * The keyboard and touchpad controller on the MacBookAir6, MacBookPro12,
11  * MacBook8 and newer can be driven either by USB or SPI. However the USB
12  * pins are only connected on the MacBookAir6 and 7 and the MacBookPro12.
13  * All others need this driver. The interface is selected using ACPI methods:
14  *
15  * * UIEN ("USB Interface Enable"): If invoked with argument 1, disables SPI
16  *   and enables USB. If invoked with argument 0, disables USB.
17  * * UIST ("USB Interface Status"): Returns 1 if USB is enabled, 0 otherwise.
18  * * SIEN ("SPI Interface Enable"): If invoked with argument 1, disables USB
19  *   and enables SPI. If invoked with argument 0, disables SPI.
20  * * SIST ("SPI Interface Status"): Returns 1 if SPI is enabled, 0 otherwise.
21  * * ISOL: Resets the four GPIO pins used for SPI. Intended to be invoked with
22  *   argument 1, then once more with argument 0.
23  *
24  * UIEN and UIST are only provided on models where the USB pins are connected.
25  *
26  * SPI-based Protocol
27  * ------------------
28  *
29  * The device and driver exchange messages (struct message); each message is
30  * encapsulated in one or more packets (struct spi_packet). There are two types
31  * of exchanges: reads, and writes. A read is signaled by a GPE, upon which one
32  * message can be read from the device. A write exchange consists of writing a
33  * command message, immediately reading a short status packet, and then, upon
34  * receiving a GPE, reading the response message. Write exchanges cannot be
35  * interleaved, i.e. a new write exchange must not be started till the previous
36  * write exchange is complete. Whether a received message is part of a read or
37  * write exchange is indicated in the encapsulating packet's flags field.
38  *
39  * A single message may be too large to fit in a single packet (which has a
40  * fixed, 256-byte size). In that case it will be split over multiple,
41  * consecutive packets.
42  */
43 
44 #include <linux/acpi.h>
45 #include <linux/crc16.h>
46 #include <linux/debugfs.h>
47 #include <linux/delay.h>
48 #include <linux/efi.h>
49 #include <linux/input.h>
50 #include <linux/input/mt.h>
51 #include <linux/ktime.h>
52 #include <linux/leds.h>
53 #include <linux/module.h>
54 #include <linux/spinlock.h>
55 #include <linux/spi/spi.h>
56 #include <linux/wait.h>
57 #include <linux/workqueue.h>
58 
59 #include <asm/barrier.h>
60 #include <asm/unaligned.h>
61 
62 #define CREATE_TRACE_POINTS
63 #include "applespi.h"
64 #include "applespi_trace.h"
65 
66 #define APPLESPI_PACKET_SIZE	256
67 #define APPLESPI_STATUS_SIZE	4
68 
69 #define PACKET_TYPE_READ	0x20
70 #define PACKET_TYPE_WRITE	0x40
71 #define PACKET_DEV_KEYB		0x01
72 #define PACKET_DEV_TPAD		0x02
73 #define PACKET_DEV_INFO		0xd0
74 
75 #define MAX_ROLLOVER		6
76 
77 #define MAX_FINGERS		11
78 #define MAX_FINGER_ORIENTATION	16384
79 #define MAX_PKTS_PER_MSG	2
80 
81 #define KBD_BL_LEVEL_MIN	32U
82 #define KBD_BL_LEVEL_MAX	255U
83 #define KBD_BL_LEVEL_SCALE	1000000U
84 #define KBD_BL_LEVEL_ADJ	\
85 	((KBD_BL_LEVEL_MAX - KBD_BL_LEVEL_MIN) * KBD_BL_LEVEL_SCALE / 255U)
86 
87 #define EFI_BL_LEVEL_NAME	L"KeyboardBacklightLevel"
88 #define EFI_BL_LEVEL_GUID	EFI_GUID(0xa076d2af, 0x9678, 0x4386, 0x8b, 0x58, 0x1f, 0xc8, 0xef, 0x04, 0x16, 0x19)
89 
90 #define APPLE_FLAG_FKEY		0x01
91 
92 #define SPI_RW_CHG_DELAY_US	100	/* from experimentation, in µs */
93 
94 #define SYNAPTICS_VENDOR_ID	0x06cb
95 
96 static unsigned int fnmode = 1;
97 module_param(fnmode, uint, 0644);
98 MODULE_PARM_DESC(fnmode, "Mode of Fn key on Apple keyboards (0 = disabled, [1] = fkeyslast, 2 = fkeysfirst)");
99 
100 static unsigned int fnremap;
101 module_param(fnremap, uint, 0644);
102 MODULE_PARM_DESC(fnremap, "Remap Fn key ([0] = no-remap; 1 = left-ctrl, 2 = left-shift, 3 = left-alt, 4 = left-meta, 6 = right-shift, 7 = right-alt, 8 = right-meta)");
103 
104 static bool iso_layout;
105 module_param(iso_layout, bool, 0644);
106 MODULE_PARM_DESC(iso_layout, "Enable/Disable hardcoded ISO-layout of the keyboard. ([0] = disabled, 1 = enabled)");
107 
108 static char touchpad_dimensions[40];
109 module_param_string(touchpad_dimensions, touchpad_dimensions,
110 		    sizeof(touchpad_dimensions), 0444);
111 MODULE_PARM_DESC(touchpad_dimensions, "The pixel dimensions of the touchpad, as XxY+W+H .");
112 
113 /**
114  * struct keyboard_protocol - keyboard message.
115  * message.type = 0x0110, message.length = 0x000a
116  *
117  * @unknown1:		unknown
118  * @modifiers:		bit-set of modifier/control keys pressed
119  * @unknown2:		unknown
120  * @keys_pressed:	the (non-modifier) keys currently pressed
121  * @fn_pressed:		whether the fn key is currently pressed
122  * @crc16:		crc over the whole message struct (message header +
123  *			this struct) minus this @crc16 field
124  */
125 struct keyboard_protocol {
126 	u8			unknown1;
127 	u8			modifiers;
128 	u8			unknown2;
129 	u8			keys_pressed[MAX_ROLLOVER];
130 	u8			fn_pressed;
131 	__le16			crc16;
132 };
133 
134 /**
135  * struct tp_finger - single trackpad finger structure, le16-aligned
136  *
137  * @origin:		zero when switching track finger
138  * @abs_x:		absolute x coordinate
139  * @abs_y:		absolute y coordinate
140  * @rel_x:		relative x coordinate
141  * @rel_y:		relative y coordinate
142  * @tool_major:		tool area, major axis
143  * @tool_minor:		tool area, minor axis
144  * @orientation:	16384 when point, else 15 bit angle
145  * @touch_major:	touch area, major axis
146  * @touch_minor:	touch area, minor axis
147  * @unused:		zeros
148  * @pressure:		pressure on forcetouch touchpad
149  * @multi:		one finger: varies, more fingers: constant
150  * @crc16:		on last finger: crc over the whole message struct
151  *			(i.e. message header + this struct) minus the last
152  *			@crc16 field; unknown on all other fingers.
153  */
154 struct tp_finger {
155 	__le16 origin;
156 	__le16 abs_x;
157 	__le16 abs_y;
158 	__le16 rel_x;
159 	__le16 rel_y;
160 	__le16 tool_major;
161 	__le16 tool_minor;
162 	__le16 orientation;
163 	__le16 touch_major;
164 	__le16 touch_minor;
165 	__le16 unused[2];
166 	__le16 pressure;
167 	__le16 multi;
168 	__le16 crc16;
169 };
170 
171 /**
172  * struct touchpad_protocol - touchpad message.
173  * message.type = 0x0210
174  *
175  * @unknown1:		unknown
176  * @clicked:		1 if a button-click was detected, 0 otherwise
177  * @unknown2:		unknown
178  * @number_of_fingers:	the number of fingers being reported in @fingers
179  * @clicked2:		same as @clicked
180  * @unknown3:		unknown
181  * @fingers:		the data for each finger
182  */
183 struct touchpad_protocol {
184 	u8			unknown1[1];
185 	u8			clicked;
186 	u8			unknown2[28];
187 	u8			number_of_fingers;
188 	u8			clicked2;
189 	u8			unknown3[16];
190 	struct tp_finger	fingers[];
191 };
192 
193 /**
194  * struct command_protocol_tp_info - get touchpad info.
195  * message.type = 0x1020, message.length = 0x0000
196  *
197  * @crc16:		crc over the whole message struct (message header +
198  *			this struct) minus this @crc16 field
199  */
200 struct command_protocol_tp_info {
201 	__le16			crc16;
202 };
203 
204 /**
205  * struct touchpad_info - touchpad info response.
206  * message.type = 0x1020, message.length = 0x006e
207  *
208  * @unknown1:		unknown
209  * @model_flags:	flags (vary by model number, but significance otherwise
210  *			unknown)
211  * @model_no:		the touchpad model number
212  * @unknown2:		unknown
213  * @crc16:		crc over the whole message struct (message header +
214  *			this struct) minus this @crc16 field
215  */
216 struct touchpad_info_protocol {
217 	u8			unknown1[105];
218 	u8			model_flags;
219 	u8			model_no;
220 	u8			unknown2[3];
221 	__le16			crc16;
222 };
223 
224 /**
225  * struct command_protocol_mt_init - initialize multitouch.
226  * message.type = 0x0252, message.length = 0x0002
227  *
228  * @cmd:		value: 0x0102
229  * @crc16:		crc over the whole message struct (message header +
230  *			this struct) minus this @crc16 field
231  */
232 struct command_protocol_mt_init {
233 	__le16			cmd;
234 	__le16			crc16;
235 };
236 
237 /**
238  * struct command_protocol_capsl - toggle caps-lock led
239  * message.type = 0x0151, message.length = 0x0002
240  *
241  * @unknown:		value: 0x01 (length?)
242  * @led:		0 off, 2 on
243  * @crc16:		crc over the whole message struct (message header +
244  *			this struct) minus this @crc16 field
245  */
246 struct command_protocol_capsl {
247 	u8			unknown;
248 	u8			led;
249 	__le16			crc16;
250 };
251 
252 /**
253  * struct command_protocol_bl - set keyboard backlight brightness
254  * message.type = 0xB051, message.length = 0x0006
255  *
256  * @const1:		value: 0x01B0
257  * @level:		the brightness level to set
258  * @const2:		value: 0x0001 (backlight off), 0x01F4 (backlight on)
259  * @crc16:		crc over the whole message struct (message header +
260  *			this struct) minus this @crc16 field
261  */
262 struct command_protocol_bl {
263 	__le16			const1;
264 	__le16			level;
265 	__le16			const2;
266 	__le16			crc16;
267 };
268 
269 /**
270  * struct message - a complete spi message.
271  *
272  * Each message begins with fixed header, followed by a message-type specific
273  * payload, and ends with a 16-bit crc. Because of the varying lengths of the
274  * payload, the crc is defined at the end of each payload struct, rather than
275  * in this struct.
276  *
277  * @type:	the message type
278  * @zero:	always 0
279  * @counter:	incremented on each message, rolls over after 255; there is a
280  *		separate counter for each message type.
281  * @rsp_buf_len:response buffer length (the exact nature of this field is quite
282  *		speculative). On a request/write this is often the same as
283  *		@length, though in some cases it has been seen to be much larger
284  *		(e.g. 0x400); on a response/read this the same as on the
285  *		request; for reads that are not responses it is 0.
286  * @length:	length of the remainder of the data in the whole message
287  *		structure (after re-assembly in case of being split over
288  *		multiple spi-packets), minus the trailing crc. The total size
289  *		of the message struct is therefore @length + 10.
290  */
291 struct message {
292 	__le16		type;
293 	u8		zero;
294 	u8		counter;
295 	__le16		rsp_buf_len;
296 	__le16		length;
297 	union {
298 		struct keyboard_protocol	keyboard;
299 		struct touchpad_protocol	touchpad;
300 		struct touchpad_info_protocol	tp_info;
301 		struct command_protocol_tp_info	tp_info_command;
302 		struct command_protocol_mt_init	init_mt_command;
303 		struct command_protocol_capsl	capsl_command;
304 		struct command_protocol_bl	bl_command;
305 		u8				data[0];
306 	};
307 };
308 
309 /* type + zero + counter + rsp_buf_len + length */
310 #define MSG_HEADER_SIZE		8
311 
312 /**
313  * struct spi_packet - a complete spi packet; always 256 bytes. This carries
314  * the (parts of the) message in the data. But note that this does not
315  * necessarily contain a complete message, as in some cases (e.g. many
316  * fingers pressed) the message is split over multiple packets (see the
317  * @offset, @remaining, and @length fields). In general the data parts in
318  * spi_packet's are concatenated until @remaining is 0, and the result is an
319  * message.
320  *
321  * @flags:	0x40 = write (to device), 0x20 = read (from device); note that
322  *		the response to a write still has 0x40.
323  * @device:	1 = keyboard, 2 = touchpad
324  * @offset:	specifies the offset of this packet's data in the complete
325  *		message; i.e. > 0 indicates this is a continuation packet (in
326  *		the second packet for a message split over multiple packets
327  *		this would then be the same as the @length in the first packet)
328  * @remaining:	number of message bytes remaining in subsequents packets (in
329  *		the first packet of a message split over two packets this would
330  *		then be the same as the @length in the second packet)
331  * @length:	length of the valid data in the @data in this packet
332  * @data:	all or part of a message
333  * @crc16:	crc over this whole structure minus this @crc16 field. This
334  *		covers just this packet, even on multi-packet messages (in
335  *		contrast to the crc in the message).
336  */
337 struct spi_packet {
338 	u8			flags;
339 	u8			device;
340 	__le16			offset;
341 	__le16			remaining;
342 	__le16			length;
343 	u8			data[246];
344 	__le16			crc16;
345 };
346 
347 struct spi_settings {
348 	u64	spi_cs_delay;		/* cs-to-clk delay in us */
349 	u64	reset_a2r_usec;		/* active-to-receive delay? */
350 	u64	reset_rec_usec;		/* ? (cur val: 10) */
351 };
352 
353 /* this mimics struct drm_rect */
354 struct applespi_tp_info {
355 	int	x_min;
356 	int	y_min;
357 	int	x_max;
358 	int	y_max;
359 };
360 
361 struct applespi_data {
362 	struct spi_device		*spi;
363 	struct spi_settings		spi_settings;
364 	struct input_dev		*keyboard_input_dev;
365 	struct input_dev		*touchpad_input_dev;
366 
367 	u8				*tx_buffer;
368 	u8				*tx_status;
369 	u8				*rx_buffer;
370 
371 	u8				*msg_buf;
372 	unsigned int			saved_msg_len;
373 
374 	struct applespi_tp_info		tp_info;
375 
376 	u8				last_keys_pressed[MAX_ROLLOVER];
377 	u8				last_keys_fn_pressed[MAX_ROLLOVER];
378 	u8				last_fn_pressed;
379 	struct input_mt_pos		pos[MAX_FINGERS];
380 	int				slots[MAX_FINGERS];
381 	int				gpe;
382 	acpi_handle			sien;
383 	acpi_handle			sist;
384 
385 	struct spi_transfer		dl_t;
386 	struct spi_transfer		rd_t;
387 	struct spi_message		rd_m;
388 
389 	struct spi_transfer		ww_t;
390 	struct spi_transfer		wd_t;
391 	struct spi_transfer		wr_t;
392 	struct spi_transfer		st_t;
393 	struct spi_message		wr_m;
394 
395 	bool				want_tp_info_cmd;
396 	bool				want_mt_init_cmd;
397 	bool				want_cl_led_on;
398 	bool				have_cl_led_on;
399 	unsigned int			want_bl_level;
400 	unsigned int			have_bl_level;
401 	unsigned int			cmd_msg_cntr;
402 	/* lock to protect the above parameters and flags below */
403 	spinlock_t			cmd_msg_lock;
404 	ktime_t				cmd_msg_queued;
405 	enum applespi_evt_type		cmd_evt_type;
406 
407 	struct led_classdev		backlight_info;
408 
409 	bool				suspended;
410 	bool				drain;
411 	wait_queue_head_t		drain_complete;
412 	bool				read_active;
413 	bool				write_active;
414 
415 	struct work_struct		work;
416 	struct touchpad_info_protocol	rcvd_tp_info;
417 
418 	struct dentry			*debugfs_root;
419 	bool				debug_tp_dim;
420 	char				tp_dim_val[40];
421 	int				tp_dim_min_x;
422 	int				tp_dim_max_x;
423 	int				tp_dim_min_y;
424 	int				tp_dim_max_y;
425 };
426 
427 static const unsigned char applespi_scancodes[] = {
428 	0, 0, 0, 0,
429 	KEY_A, KEY_B, KEY_C, KEY_D, KEY_E, KEY_F, KEY_G, KEY_H, KEY_I, KEY_J,
430 	KEY_K, KEY_L, KEY_M, KEY_N, KEY_O, KEY_P, KEY_Q, KEY_R, KEY_S, KEY_T,
431 	KEY_U, KEY_V, KEY_W, KEY_X, KEY_Y, KEY_Z,
432 	KEY_1, KEY_2, KEY_3, KEY_4, KEY_5, KEY_6, KEY_7, KEY_8, KEY_9, KEY_0,
433 	KEY_ENTER, KEY_ESC, KEY_BACKSPACE, KEY_TAB, KEY_SPACE, KEY_MINUS,
434 	KEY_EQUAL, KEY_LEFTBRACE, KEY_RIGHTBRACE, KEY_BACKSLASH, 0,
435 	KEY_SEMICOLON, KEY_APOSTROPHE, KEY_GRAVE, KEY_COMMA, KEY_DOT, KEY_SLASH,
436 	KEY_CAPSLOCK,
437 	KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6, KEY_F7, KEY_F8, KEY_F9,
438 	KEY_F10, KEY_F11, KEY_F12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
439 	KEY_RIGHT, KEY_LEFT, KEY_DOWN, KEY_UP,
440 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, KEY_102ND,
441 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
442 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, KEY_RO, 0, KEY_YEN, 0, 0, 0, 0, 0,
443 	0, KEY_KATAKANAHIRAGANA, KEY_MUHENKAN
444 };
445 
446 /*
447  * This must have exactly as many entries as there are bits in
448  * struct keyboard_protocol.modifiers .
449  */
450 static const unsigned char applespi_controlcodes[] = {
451 	KEY_LEFTCTRL,
452 	KEY_LEFTSHIFT,
453 	KEY_LEFTALT,
454 	KEY_LEFTMETA,
455 	0,
456 	KEY_RIGHTSHIFT,
457 	KEY_RIGHTALT,
458 	KEY_RIGHTMETA
459 };
460 
461 struct applespi_key_translation {
462 	u16 from;
463 	u16 to;
464 	u8 flags;
465 };
466 
467 static const struct applespi_key_translation applespi_fn_codes[] = {
468 	{ KEY_BACKSPACE, KEY_DELETE },
469 	{ KEY_ENTER,	KEY_INSERT },
470 	{ KEY_F1,	KEY_BRIGHTNESSDOWN,	APPLE_FLAG_FKEY },
471 	{ KEY_F2,	KEY_BRIGHTNESSUP,	APPLE_FLAG_FKEY },
472 	{ KEY_F3,	KEY_SCALE,		APPLE_FLAG_FKEY },
473 	{ KEY_F4,	KEY_DASHBOARD,		APPLE_FLAG_FKEY },
474 	{ KEY_F5,	KEY_KBDILLUMDOWN,	APPLE_FLAG_FKEY },
475 	{ KEY_F6,	KEY_KBDILLUMUP,		APPLE_FLAG_FKEY },
476 	{ KEY_F7,	KEY_PREVIOUSSONG,	APPLE_FLAG_FKEY },
477 	{ KEY_F8,	KEY_PLAYPAUSE,		APPLE_FLAG_FKEY },
478 	{ KEY_F9,	KEY_NEXTSONG,		APPLE_FLAG_FKEY },
479 	{ KEY_F10,	KEY_MUTE,		APPLE_FLAG_FKEY },
480 	{ KEY_F11,	KEY_VOLUMEDOWN,		APPLE_FLAG_FKEY },
481 	{ KEY_F12,	KEY_VOLUMEUP,		APPLE_FLAG_FKEY },
482 	{ KEY_RIGHT,	KEY_END },
483 	{ KEY_LEFT,	KEY_HOME },
484 	{ KEY_DOWN,	KEY_PAGEDOWN },
485 	{ KEY_UP,	KEY_PAGEUP },
486 	{ }
487 };
488 
489 static const struct applespi_key_translation apple_iso_keyboard[] = {
490 	{ KEY_GRAVE,	KEY_102ND },
491 	{ KEY_102ND,	KEY_GRAVE },
492 	{ }
493 };
494 
495 struct applespi_tp_model_info {
496 	u16			model;
497 	struct applespi_tp_info	tp_info;
498 };
499 
500 static const struct applespi_tp_model_info applespi_tp_models[] = {
501 	{
502 		.model = 0x04,	/* MB8 MB9 MB10 */
503 		.tp_info = { -5087, -182, 5579, 6089 },
504 	},
505 	{
506 		.model = 0x05,	/* MBP13,1 MBP13,2 MBP14,1 MBP14,2 */
507 		.tp_info = { -6243, -170, 6749, 7685 },
508 	},
509 	{
510 		.model = 0x06,	/* MBP13,3 MBP14,3 */
511 		.tp_info = { -7456, -163, 7976, 9283 },
512 	},
513 	{}
514 };
515 
516 typedef void (*applespi_trace_fun)(enum applespi_evt_type,
517 				   enum applespi_pkt_type, u8 *, size_t);
518 
applespi_get_trace_fun(enum applespi_evt_type type)519 static applespi_trace_fun applespi_get_trace_fun(enum applespi_evt_type type)
520 {
521 	switch (type) {
522 	case ET_CMD_TP_INI:
523 		return trace_applespi_tp_ini_cmd;
524 	case ET_CMD_BL:
525 		return trace_applespi_backlight_cmd;
526 	case ET_CMD_CL:
527 		return trace_applespi_caps_lock_cmd;
528 	case ET_RD_KEYB:
529 		return trace_applespi_keyboard_data;
530 	case ET_RD_TPAD:
531 		return trace_applespi_touchpad_data;
532 	case ET_RD_UNKN:
533 		return trace_applespi_unknown_data;
534 	default:
535 		WARN_ONCE(1, "Unknown msg type %d", type);
536 		return trace_applespi_unknown_data;
537 	}
538 }
539 
applespi_setup_read_txfrs(struct applespi_data *applespi)540 static void applespi_setup_read_txfrs(struct applespi_data *applespi)
541 {
542 	struct spi_message *msg = &applespi->rd_m;
543 	struct spi_transfer *dl_t = &applespi->dl_t;
544 	struct spi_transfer *rd_t = &applespi->rd_t;
545 
546 	memset(dl_t, 0, sizeof(*dl_t));
547 	memset(rd_t, 0, sizeof(*rd_t));
548 
549 	dl_t->delay_usecs = applespi->spi_settings.spi_cs_delay;
550 
551 	rd_t->rx_buf = applespi->rx_buffer;
552 	rd_t->len = APPLESPI_PACKET_SIZE;
553 
554 	spi_message_init(msg);
555 	spi_message_add_tail(dl_t, msg);
556 	spi_message_add_tail(rd_t, msg);
557 }
558 
applespi_setup_write_txfrs(struct applespi_data *applespi)559 static void applespi_setup_write_txfrs(struct applespi_data *applespi)
560 {
561 	struct spi_message *msg = &applespi->wr_m;
562 	struct spi_transfer *wt_t = &applespi->ww_t;
563 	struct spi_transfer *dl_t = &applespi->wd_t;
564 	struct spi_transfer *wr_t = &applespi->wr_t;
565 	struct spi_transfer *st_t = &applespi->st_t;
566 
567 	memset(wt_t, 0, sizeof(*wt_t));
568 	memset(dl_t, 0, sizeof(*dl_t));
569 	memset(wr_t, 0, sizeof(*wr_t));
570 	memset(st_t, 0, sizeof(*st_t));
571 
572 	/*
573 	 * All we need here is a delay at the beginning of the message before
574 	 * asserting cs. But the current spi API doesn't support this, so we
575 	 * end up with an extra unnecessary (but harmless) cs assertion and
576 	 * deassertion.
577 	 */
578 	wt_t->delay_usecs = SPI_RW_CHG_DELAY_US;
579 	wt_t->cs_change = 1;
580 
581 	dl_t->delay_usecs = applespi->spi_settings.spi_cs_delay;
582 
583 	wr_t->tx_buf = applespi->tx_buffer;
584 	wr_t->len = APPLESPI_PACKET_SIZE;
585 	wr_t->delay_usecs = SPI_RW_CHG_DELAY_US;
586 
587 	st_t->rx_buf = applespi->tx_status;
588 	st_t->len = APPLESPI_STATUS_SIZE;
589 
590 	spi_message_init(msg);
591 	spi_message_add_tail(wt_t, msg);
592 	spi_message_add_tail(dl_t, msg);
593 	spi_message_add_tail(wr_t, msg);
594 	spi_message_add_tail(st_t, msg);
595 }
596 
applespi_async(struct applespi_data *applespi, struct spi_message *message, void (*complete)(void *))597 static int applespi_async(struct applespi_data *applespi,
598 			  struct spi_message *message, void (*complete)(void *))
599 {
600 	message->complete = complete;
601 	message->context = applespi;
602 
603 	return spi_async(applespi->spi, message);
604 }
605 
applespi_check_write_status(struct applespi_data *applespi, int sts)606 static inline bool applespi_check_write_status(struct applespi_data *applespi,
607 					       int sts)
608 {
609 	static u8 status_ok[] = { 0xac, 0x27, 0x68, 0xd5 };
610 
611 	if (sts < 0) {
612 		dev_warn(&applespi->spi->dev, "Error writing to device: %d\n",
613 			 sts);
614 		return false;
615 	}
616 
617 	if (memcmp(applespi->tx_status, status_ok, APPLESPI_STATUS_SIZE)) {
618 		dev_warn(&applespi->spi->dev, "Error writing to device: %*ph\n",
619 			 APPLESPI_STATUS_SIZE, applespi->tx_status);
620 		return false;
621 	}
622 
623 	return true;
624 }
625 
applespi_get_spi_settings(struct applespi_data *applespi)626 static int applespi_get_spi_settings(struct applespi_data *applespi)
627 {
628 	struct acpi_device *adev = ACPI_COMPANION(&applespi->spi->dev);
629 	const union acpi_object *o;
630 	struct spi_settings *settings = &applespi->spi_settings;
631 
632 	if (!acpi_dev_get_property(adev, "spiCSDelay", ACPI_TYPE_BUFFER, &o))
633 		settings->spi_cs_delay = *(u64 *)o->buffer.pointer;
634 	else
635 		dev_warn(&applespi->spi->dev,
636 			 "Property spiCSDelay not found\n");
637 
638 	if (!acpi_dev_get_property(adev, "resetA2RUsec", ACPI_TYPE_BUFFER, &o))
639 		settings->reset_a2r_usec = *(u64 *)o->buffer.pointer;
640 	else
641 		dev_warn(&applespi->spi->dev,
642 			 "Property resetA2RUsec not found\n");
643 
644 	if (!acpi_dev_get_property(adev, "resetRecUsec", ACPI_TYPE_BUFFER, &o))
645 		settings->reset_rec_usec = *(u64 *)o->buffer.pointer;
646 	else
647 		dev_warn(&applespi->spi->dev,
648 			 "Property resetRecUsec not found\n");
649 
650 	dev_dbg(&applespi->spi->dev,
651 		"SPI settings: spi_cs_delay=%llu reset_a2r_usec=%llu reset_rec_usec=%llu\n",
652 		settings->spi_cs_delay, settings->reset_a2r_usec,
653 		settings->reset_rec_usec);
654 
655 	return 0;
656 }
657 
applespi_setup_spi(struct applespi_data *applespi)658 static int applespi_setup_spi(struct applespi_data *applespi)
659 {
660 	int sts;
661 
662 	sts = applespi_get_spi_settings(applespi);
663 	if (sts)
664 		return sts;
665 
666 	spin_lock_init(&applespi->cmd_msg_lock);
667 	init_waitqueue_head(&applespi->drain_complete);
668 
669 	return 0;
670 }
671 
applespi_enable_spi(struct applespi_data *applespi)672 static int applespi_enable_spi(struct applespi_data *applespi)
673 {
674 	acpi_status acpi_sts;
675 	unsigned long long spi_status;
676 
677 	/* check if SPI is already enabled, so we can skip the delay below */
678 	acpi_sts = acpi_evaluate_integer(applespi->sist, NULL, NULL,
679 					 &spi_status);
680 	if (ACPI_SUCCESS(acpi_sts) && spi_status)
681 		return 0;
682 
683 	/* SIEN(1) will enable SPI communication */
684 	acpi_sts = acpi_execute_simple_method(applespi->sien, NULL, 1);
685 	if (ACPI_FAILURE(acpi_sts)) {
686 		dev_err(&applespi->spi->dev, "SIEN failed: %s\n",
687 			acpi_format_exception(acpi_sts));
688 		return -ENODEV;
689 	}
690 
691 	/*
692 	 * Allow the SPI interface to come up before returning. Without this
693 	 * delay, the SPI commands to enable multitouch mode may not reach
694 	 * the trackpad controller, causing pointer movement to break upon
695 	 * resume from sleep.
696 	 */
697 	msleep(50);
698 
699 	return 0;
700 }
701 
702 static int applespi_send_cmd_msg(struct applespi_data *applespi);
703 
applespi_msg_complete(struct applespi_data *applespi, bool is_write_msg, bool is_read_compl)704 static void applespi_msg_complete(struct applespi_data *applespi,
705 				  bool is_write_msg, bool is_read_compl)
706 {
707 	unsigned long flags;
708 
709 	spin_lock_irqsave(&applespi->cmd_msg_lock, flags);
710 
711 	if (is_read_compl)
712 		applespi->read_active = false;
713 	if (is_write_msg)
714 		applespi->write_active = false;
715 
716 	if (applespi->drain && !applespi->write_active)
717 		wake_up_all(&applespi->drain_complete);
718 
719 	if (is_write_msg) {
720 		applespi->cmd_msg_queued = 0;
721 		applespi_send_cmd_msg(applespi);
722 	}
723 
724 	spin_unlock_irqrestore(&applespi->cmd_msg_lock, flags);
725 }
726 
applespi_async_write_complete(void *context)727 static void applespi_async_write_complete(void *context)
728 {
729 	struct applespi_data *applespi = context;
730 	enum applespi_evt_type evt_type = applespi->cmd_evt_type;
731 
732 	applespi_get_trace_fun(evt_type)(evt_type, PT_WRITE,
733 					 applespi->tx_buffer,
734 					 APPLESPI_PACKET_SIZE);
735 	applespi_get_trace_fun(evt_type)(evt_type, PT_STATUS,
736 					 applespi->tx_status,
737 					 APPLESPI_STATUS_SIZE);
738 
739 	if (!applespi_check_write_status(applespi, applespi->wr_m.status)) {
740 		/*
741 		 * If we got an error, we presumably won't get the expected
742 		 * response message either.
743 		 */
744 		applespi_msg_complete(applespi, true, false);
745 	}
746 }
747 
applespi_send_cmd_msg(struct applespi_data *applespi)748 static int applespi_send_cmd_msg(struct applespi_data *applespi)
749 {
750 	u16 crc;
751 	int sts;
752 	struct spi_packet *packet = (struct spi_packet *)applespi->tx_buffer;
753 	struct message *message = (struct message *)packet->data;
754 	u16 msg_len;
755 	u8 device;
756 
757 	/* check if draining */
758 	if (applespi->drain)
759 		return 0;
760 
761 	/* check whether send is in progress */
762 	if (applespi->cmd_msg_queued) {
763 		if (ktime_ms_delta(ktime_get(), applespi->cmd_msg_queued) < 1000)
764 			return 0;
765 
766 		dev_warn(&applespi->spi->dev, "Command %d timed out\n",
767 			 applespi->cmd_evt_type);
768 
769 		applespi->cmd_msg_queued = 0;
770 		applespi->write_active = false;
771 	}
772 
773 	/* set up packet */
774 	memset(packet, 0, APPLESPI_PACKET_SIZE);
775 
776 	/* are we processing init commands? */
777 	if (applespi->want_tp_info_cmd) {
778 		applespi->want_tp_info_cmd = false;
779 		applespi->want_mt_init_cmd = true;
780 		applespi->cmd_evt_type = ET_CMD_TP_INI;
781 
782 		/* build init command */
783 		device = PACKET_DEV_INFO;
784 
785 		message->type = cpu_to_le16(0x1020);
786 		msg_len = sizeof(message->tp_info_command);
787 
788 		message->zero = 0x02;
789 		message->rsp_buf_len = cpu_to_le16(0x0200);
790 
791 	} else if (applespi->want_mt_init_cmd) {
792 		applespi->want_mt_init_cmd = false;
793 		applespi->cmd_evt_type = ET_CMD_TP_INI;
794 
795 		/* build init command */
796 		device = PACKET_DEV_TPAD;
797 
798 		message->type = cpu_to_le16(0x0252);
799 		msg_len = sizeof(message->init_mt_command);
800 
801 		message->init_mt_command.cmd = cpu_to_le16(0x0102);
802 
803 	/* do we need caps-lock command? */
804 	} else if (applespi->want_cl_led_on != applespi->have_cl_led_on) {
805 		applespi->have_cl_led_on = applespi->want_cl_led_on;
806 		applespi->cmd_evt_type = ET_CMD_CL;
807 
808 		/* build led command */
809 		device = PACKET_DEV_KEYB;
810 
811 		message->type = cpu_to_le16(0x0151);
812 		msg_len = sizeof(message->capsl_command);
813 
814 		message->capsl_command.unknown = 0x01;
815 		message->capsl_command.led = applespi->have_cl_led_on ? 2 : 0;
816 
817 	/* do we need backlight command? */
818 	} else if (applespi->want_bl_level != applespi->have_bl_level) {
819 		applespi->have_bl_level = applespi->want_bl_level;
820 		applespi->cmd_evt_type = ET_CMD_BL;
821 
822 		/* build command buffer */
823 		device = PACKET_DEV_KEYB;
824 
825 		message->type = cpu_to_le16(0xB051);
826 		msg_len = sizeof(message->bl_command);
827 
828 		message->bl_command.const1 = cpu_to_le16(0x01B0);
829 		message->bl_command.level =
830 				cpu_to_le16(applespi->have_bl_level);
831 
832 		if (applespi->have_bl_level > 0)
833 			message->bl_command.const2 = cpu_to_le16(0x01F4);
834 		else
835 			message->bl_command.const2 = cpu_to_le16(0x0001);
836 
837 	/* everything's up-to-date */
838 	} else {
839 		return 0;
840 	}
841 
842 	/* finalize packet */
843 	packet->flags = PACKET_TYPE_WRITE;
844 	packet->device = device;
845 	packet->length = cpu_to_le16(MSG_HEADER_SIZE + msg_len);
846 
847 	message->counter = applespi->cmd_msg_cntr++ % (U8_MAX + 1);
848 
849 	message->length = cpu_to_le16(msg_len - 2);
850 	if (!message->rsp_buf_len)
851 		message->rsp_buf_len = message->length;
852 
853 	crc = crc16(0, (u8 *)message, le16_to_cpu(packet->length) - 2);
854 	put_unaligned_le16(crc, &message->data[msg_len - 2]);
855 
856 	crc = crc16(0, (u8 *)packet, sizeof(*packet) - 2);
857 	packet->crc16 = cpu_to_le16(crc);
858 
859 	/* send command */
860 	sts = applespi_async(applespi, &applespi->wr_m,
861 			     applespi_async_write_complete);
862 	if (sts) {
863 		dev_warn(&applespi->spi->dev,
864 			 "Error queueing async write to device: %d\n", sts);
865 		return sts;
866 	}
867 
868 	applespi->cmd_msg_queued = ktime_get_coarse();
869 	applespi->write_active = true;
870 
871 	return 0;
872 }
873 
applespi_init(struct applespi_data *applespi, bool is_resume)874 static void applespi_init(struct applespi_data *applespi, bool is_resume)
875 {
876 	unsigned long flags;
877 
878 	spin_lock_irqsave(&applespi->cmd_msg_lock, flags);
879 
880 	if (is_resume)
881 		applespi->want_mt_init_cmd = true;
882 	else
883 		applespi->want_tp_info_cmd = true;
884 	applespi_send_cmd_msg(applespi);
885 
886 	spin_unlock_irqrestore(&applespi->cmd_msg_lock, flags);
887 }
888 
applespi_set_capsl_led(struct applespi_data *applespi, bool capslock_on)889 static int applespi_set_capsl_led(struct applespi_data *applespi,
890 				  bool capslock_on)
891 {
892 	unsigned long flags;
893 	int sts;
894 
895 	spin_lock_irqsave(&applespi->cmd_msg_lock, flags);
896 
897 	applespi->want_cl_led_on = capslock_on;
898 	sts = applespi_send_cmd_msg(applespi);
899 
900 	spin_unlock_irqrestore(&applespi->cmd_msg_lock, flags);
901 
902 	return sts;
903 }
904 
applespi_set_bl_level(struct led_classdev *led_cdev, enum led_brightness value)905 static void applespi_set_bl_level(struct led_classdev *led_cdev,
906 				  enum led_brightness value)
907 {
908 	struct applespi_data *applespi =
909 		container_of(led_cdev, struct applespi_data, backlight_info);
910 	unsigned long flags;
911 
912 	spin_lock_irqsave(&applespi->cmd_msg_lock, flags);
913 
914 	if (value == 0) {
915 		applespi->want_bl_level = value;
916 	} else {
917 		/*
918 		 * The backlight does not turn on till level 32, so we scale
919 		 * the range here so that from a user's perspective it turns
920 		 * on at 1.
921 		 */
922 		applespi->want_bl_level =
923 			((value * KBD_BL_LEVEL_ADJ) / KBD_BL_LEVEL_SCALE +
924 			 KBD_BL_LEVEL_MIN);
925 	}
926 
927 	applespi_send_cmd_msg(applespi);
928 
929 	spin_unlock_irqrestore(&applespi->cmd_msg_lock, flags);
930 }
931 
applespi_event(struct input_dev *dev, unsigned int type, unsigned int code, int value)932 static int applespi_event(struct input_dev *dev, unsigned int type,
933 			  unsigned int code, int value)
934 {
935 	struct applespi_data *applespi = input_get_drvdata(dev);
936 
937 	switch (type) {
938 	case EV_LED:
939 		applespi_set_capsl_led(applespi, !!test_bit(LED_CAPSL, dev->led));
940 		return 0;
941 	}
942 
943 	return -EINVAL;
944 }
945 
946 /* lifted from the BCM5974 driver and renamed from raw2int */
947 /* convert 16-bit little endian to signed integer */
le16_to_int(__le16 x)948 static inline int le16_to_int(__le16 x)
949 {
950 	return (signed short)le16_to_cpu(x);
951 }
952 
applespi_debug_update_dimensions(struct applespi_data *applespi, const struct tp_finger *f)953 static void applespi_debug_update_dimensions(struct applespi_data *applespi,
954 					     const struct tp_finger *f)
955 {
956 	applespi->tp_dim_min_x = min(applespi->tp_dim_min_x,
957 				     le16_to_int(f->abs_x));
958 	applespi->tp_dim_max_x = max(applespi->tp_dim_max_x,
959 				     le16_to_int(f->abs_x));
960 	applespi->tp_dim_min_y = min(applespi->tp_dim_min_y,
961 				     le16_to_int(f->abs_y));
962 	applespi->tp_dim_max_y = max(applespi->tp_dim_max_y,
963 				     le16_to_int(f->abs_y));
964 }
965 
applespi_tp_dim_open(struct inode *inode, struct file *file)966 static int applespi_tp_dim_open(struct inode *inode, struct file *file)
967 {
968 	struct applespi_data *applespi = inode->i_private;
969 
970 	file->private_data = applespi;
971 
972 	snprintf(applespi->tp_dim_val, sizeof(applespi->tp_dim_val),
973 		 "0x%.4x %dx%d+%u+%u\n",
974 		 applespi->touchpad_input_dev->id.product,
975 		 applespi->tp_dim_min_x, applespi->tp_dim_min_y,
976 		 applespi->tp_dim_max_x - applespi->tp_dim_min_x,
977 		 applespi->tp_dim_max_y - applespi->tp_dim_min_y);
978 
979 	return nonseekable_open(inode, file);
980 }
981 
applespi_tp_dim_read(struct file *file, char __user *buf, size_t len, loff_t *off)982 static ssize_t applespi_tp_dim_read(struct file *file, char __user *buf,
983 				    size_t len, loff_t *off)
984 {
985 	struct applespi_data *applespi = file->private_data;
986 
987 	return simple_read_from_buffer(buf, len, off, applespi->tp_dim_val,
988 				       strlen(applespi->tp_dim_val));
989 }
990 
991 static const struct file_operations applespi_tp_dim_fops = {
992 	.owner = THIS_MODULE,
993 	.open = applespi_tp_dim_open,
994 	.read = applespi_tp_dim_read,
995 	.llseek = no_llseek,
996 };
997 
report_finger_data(struct input_dev *input, int slot, const struct input_mt_pos *pos, const struct tp_finger *f)998 static void report_finger_data(struct input_dev *input, int slot,
999 			       const struct input_mt_pos *pos,
1000 			       const struct tp_finger *f)
1001 {
1002 	input_mt_slot(input, slot);
1003 	input_mt_report_slot_state(input, MT_TOOL_FINGER, true);
1004 
1005 	input_report_abs(input, ABS_MT_TOUCH_MAJOR,
1006 			 le16_to_int(f->touch_major) << 1);
1007 	input_report_abs(input, ABS_MT_TOUCH_MINOR,
1008 			 le16_to_int(f->touch_minor) << 1);
1009 	input_report_abs(input, ABS_MT_WIDTH_MAJOR,
1010 			 le16_to_int(f->tool_major) << 1);
1011 	input_report_abs(input, ABS_MT_WIDTH_MINOR,
1012 			 le16_to_int(f->tool_minor) << 1);
1013 	input_report_abs(input, ABS_MT_ORIENTATION,
1014 			 MAX_FINGER_ORIENTATION - le16_to_int(f->orientation));
1015 	input_report_abs(input, ABS_MT_POSITION_X, pos->x);
1016 	input_report_abs(input, ABS_MT_POSITION_Y, pos->y);
1017 }
1018 
report_tp_state(struct applespi_data *applespi, struct touchpad_protocol *t)1019 static void report_tp_state(struct applespi_data *applespi,
1020 			    struct touchpad_protocol *t)
1021 {
1022 	const struct tp_finger *f;
1023 	struct input_dev *input;
1024 	const struct applespi_tp_info *tp_info = &applespi->tp_info;
1025 	int i, n;
1026 
1027 	/* touchpad_input_dev is set async in worker */
1028 	input = smp_load_acquire(&applespi->touchpad_input_dev);
1029 	if (!input)
1030 		return;	/* touchpad isn't initialized yet */
1031 
1032 	n = 0;
1033 
1034 	for (i = 0; i < t->number_of_fingers; i++) {
1035 		f = &t->fingers[i];
1036 		if (le16_to_int(f->touch_major) == 0)
1037 			continue;
1038 		applespi->pos[n].x = le16_to_int(f->abs_x);
1039 		applespi->pos[n].y = tp_info->y_min + tp_info->y_max -
1040 				     le16_to_int(f->abs_y);
1041 		n++;
1042 
1043 		if (applespi->debug_tp_dim)
1044 			applespi_debug_update_dimensions(applespi, f);
1045 	}
1046 
1047 	input_mt_assign_slots(input, applespi->slots, applespi->pos, n, 0);
1048 
1049 	for (i = 0; i < n; i++)
1050 		report_finger_data(input, applespi->slots[i],
1051 				   &applespi->pos[i], &t->fingers[i]);
1052 
1053 	input_mt_sync_frame(input);
1054 	input_report_key(input, BTN_LEFT, t->clicked);
1055 
1056 	input_sync(input);
1057 }
1058 
1059 static const struct applespi_key_translation *
applespi_find_translation(const struct applespi_key_translation *table, u16 key)1060 applespi_find_translation(const struct applespi_key_translation *table, u16 key)
1061 {
1062 	const struct applespi_key_translation *trans;
1063 
1064 	for (trans = table; trans->from; trans++)
1065 		if (trans->from == key)
1066 			return trans;
1067 
1068 	return NULL;
1069 }
1070 
applespi_translate_fn_key(unsigned int key, int fn_pressed)1071 static unsigned int applespi_translate_fn_key(unsigned int key, int fn_pressed)
1072 {
1073 	const struct applespi_key_translation *trans;
1074 	int do_translate;
1075 
1076 	trans = applespi_find_translation(applespi_fn_codes, key);
1077 	if (trans) {
1078 		if (trans->flags & APPLE_FLAG_FKEY)
1079 			do_translate = (fnmode == 2 && fn_pressed) ||
1080 				       (fnmode == 1 && !fn_pressed);
1081 		else
1082 			do_translate = fn_pressed;
1083 
1084 		if (do_translate)
1085 			key = trans->to;
1086 	}
1087 
1088 	return key;
1089 }
1090 
applespi_translate_iso_layout(unsigned int key)1091 static unsigned int applespi_translate_iso_layout(unsigned int key)
1092 {
1093 	const struct applespi_key_translation *trans;
1094 
1095 	trans = applespi_find_translation(apple_iso_keyboard, key);
1096 	if (trans)
1097 		key = trans->to;
1098 
1099 	return key;
1100 }
1101 
applespi_code_to_key(u8 code, int fn_pressed)1102 static unsigned int applespi_code_to_key(u8 code, int fn_pressed)
1103 {
1104 	unsigned int key = applespi_scancodes[code];
1105 
1106 	if (fnmode)
1107 		key = applespi_translate_fn_key(key, fn_pressed);
1108 	if (iso_layout)
1109 		key = applespi_translate_iso_layout(key);
1110 	return key;
1111 }
1112 
1113 static void
applespi_remap_fn_key(struct keyboard_protocol *keyboard_protocol)1114 applespi_remap_fn_key(struct keyboard_protocol *keyboard_protocol)
1115 {
1116 	unsigned char tmp;
1117 	u8 bit = BIT((fnremap - 1) & 0x07);
1118 
1119 	if (!fnremap || fnremap > ARRAY_SIZE(applespi_controlcodes) ||
1120 	    !applespi_controlcodes[fnremap - 1])
1121 		return;
1122 
1123 	tmp = keyboard_protocol->fn_pressed;
1124 	keyboard_protocol->fn_pressed = !!(keyboard_protocol->modifiers & bit);
1125 	if (tmp)
1126 		keyboard_protocol->modifiers |= bit;
1127 	else
1128 		keyboard_protocol->modifiers &= ~bit;
1129 }
1130 
1131 static void
applespi_handle_keyboard_event(struct applespi_data *applespi, struct keyboard_protocol *keyboard_protocol)1132 applespi_handle_keyboard_event(struct applespi_data *applespi,
1133 			       struct keyboard_protocol *keyboard_protocol)
1134 {
1135 	unsigned int key;
1136 	int i;
1137 
1138 	compiletime_assert(ARRAY_SIZE(applespi_controlcodes) ==
1139 			   sizeof_field(struct keyboard_protocol, modifiers) * 8,
1140 			   "applespi_controlcodes has wrong number of entries");
1141 
1142 	/* check for rollover overflow, which is signalled by all keys == 1 */
1143 	if (!memchr_inv(keyboard_protocol->keys_pressed, 1, MAX_ROLLOVER))
1144 		return;
1145 
1146 	/* remap fn key if desired */
1147 	applespi_remap_fn_key(keyboard_protocol);
1148 
1149 	/* check released keys */
1150 	for (i = 0; i < MAX_ROLLOVER; i++) {
1151 		if (memchr(keyboard_protocol->keys_pressed,
1152 			   applespi->last_keys_pressed[i], MAX_ROLLOVER))
1153 			continue;	/* key is still pressed */
1154 
1155 		key = applespi_code_to_key(applespi->last_keys_pressed[i],
1156 					   applespi->last_keys_fn_pressed[i]);
1157 		input_report_key(applespi->keyboard_input_dev, key, 0);
1158 		applespi->last_keys_fn_pressed[i] = 0;
1159 	}
1160 
1161 	/* check pressed keys */
1162 	for (i = 0; i < MAX_ROLLOVER; i++) {
1163 		if (keyboard_protocol->keys_pressed[i] <
1164 				ARRAY_SIZE(applespi_scancodes) &&
1165 		    keyboard_protocol->keys_pressed[i] > 0) {
1166 			key = applespi_code_to_key(
1167 					keyboard_protocol->keys_pressed[i],
1168 					keyboard_protocol->fn_pressed);
1169 			input_report_key(applespi->keyboard_input_dev, key, 1);
1170 			applespi->last_keys_fn_pressed[i] =
1171 					keyboard_protocol->fn_pressed;
1172 		}
1173 	}
1174 
1175 	/* check control keys */
1176 	for (i = 0; i < ARRAY_SIZE(applespi_controlcodes); i++) {
1177 		if (keyboard_protocol->modifiers & BIT(i))
1178 			input_report_key(applespi->keyboard_input_dev,
1179 					 applespi_controlcodes[i], 1);
1180 		else
1181 			input_report_key(applespi->keyboard_input_dev,
1182 					 applespi_controlcodes[i], 0);
1183 	}
1184 
1185 	/* check function key */
1186 	if (keyboard_protocol->fn_pressed && !applespi->last_fn_pressed)
1187 		input_report_key(applespi->keyboard_input_dev, KEY_FN, 1);
1188 	else if (!keyboard_protocol->fn_pressed && applespi->last_fn_pressed)
1189 		input_report_key(applespi->keyboard_input_dev, KEY_FN, 0);
1190 	applespi->last_fn_pressed = keyboard_protocol->fn_pressed;
1191 
1192 	/* done */
1193 	input_sync(applespi->keyboard_input_dev);
1194 	memcpy(&applespi->last_keys_pressed, keyboard_protocol->keys_pressed,
1195 	       sizeof(applespi->last_keys_pressed));
1196 }
1197 
applespi_find_touchpad_info(u8 model)1198 static const struct applespi_tp_info *applespi_find_touchpad_info(u8 model)
1199 {
1200 	const struct applespi_tp_model_info *info;
1201 
1202 	for (info = applespi_tp_models; info->model; info++) {
1203 		if (info->model == model)
1204 			return &info->tp_info;
1205 	}
1206 
1207 	return NULL;
1208 }
1209 
1210 static int
applespi_register_touchpad_device(struct applespi_data *applespi, struct touchpad_info_protocol *rcvd_tp_info)1211 applespi_register_touchpad_device(struct applespi_data *applespi,
1212 				  struct touchpad_info_protocol *rcvd_tp_info)
1213 {
1214 	const struct applespi_tp_info *tp_info;
1215 	struct input_dev *touchpad_input_dev;
1216 	int sts;
1217 
1218 	/* set up touchpad dimensions */
1219 	tp_info = applespi_find_touchpad_info(rcvd_tp_info->model_no);
1220 	if (!tp_info) {
1221 		dev_warn(&applespi->spi->dev,
1222 			 "Unknown touchpad model %x - falling back to MB8 touchpad\n",
1223 			 rcvd_tp_info->model_no);
1224 		tp_info = &applespi_tp_models[0].tp_info;
1225 	}
1226 
1227 	applespi->tp_info = *tp_info;
1228 
1229 	if (touchpad_dimensions[0]) {
1230 		int x, y, w, h;
1231 
1232 		sts = sscanf(touchpad_dimensions, "%dx%d+%u+%u", &x, &y, &w, &h);
1233 		if (sts == 4) {
1234 			dev_info(&applespi->spi->dev,
1235 				 "Overriding touchpad dimensions from module param\n");
1236 			applespi->tp_info.x_min = x;
1237 			applespi->tp_info.y_min = y;
1238 			applespi->tp_info.x_max = x + w;
1239 			applespi->tp_info.y_max = y + h;
1240 		} else {
1241 			dev_warn(&applespi->spi->dev,
1242 				 "Invalid touchpad dimensions '%s': must be in the form XxY+W+H\n",
1243 				 touchpad_dimensions);
1244 			touchpad_dimensions[0] = '\0';
1245 		}
1246 	}
1247 	if (!touchpad_dimensions[0]) {
1248 		snprintf(touchpad_dimensions, sizeof(touchpad_dimensions),
1249 			 "%dx%d+%u+%u",
1250 			 applespi->tp_info.x_min,
1251 			 applespi->tp_info.y_min,
1252 			 applespi->tp_info.x_max - applespi->tp_info.x_min,
1253 			 applespi->tp_info.y_max - applespi->tp_info.y_min);
1254 	}
1255 
1256 	/* create touchpad input device */
1257 	touchpad_input_dev = devm_input_allocate_device(&applespi->spi->dev);
1258 	if (!touchpad_input_dev) {
1259 		dev_err(&applespi->spi->dev,
1260 			"Failed to allocate touchpad input device\n");
1261 		return -ENOMEM;
1262 	}
1263 
1264 	touchpad_input_dev->name = "Apple SPI Touchpad";
1265 	touchpad_input_dev->phys = "applespi/input1";
1266 	touchpad_input_dev->dev.parent = &applespi->spi->dev;
1267 	touchpad_input_dev->id.bustype = BUS_SPI;
1268 	touchpad_input_dev->id.vendor = SYNAPTICS_VENDOR_ID;
1269 	touchpad_input_dev->id.product =
1270 			rcvd_tp_info->model_no << 8 | rcvd_tp_info->model_flags;
1271 
1272 	/* basic properties */
1273 	input_set_capability(touchpad_input_dev, EV_REL, REL_X);
1274 	input_set_capability(touchpad_input_dev, EV_REL, REL_Y);
1275 
1276 	__set_bit(INPUT_PROP_POINTER, touchpad_input_dev->propbit);
1277 	__set_bit(INPUT_PROP_BUTTONPAD, touchpad_input_dev->propbit);
1278 
1279 	/* finger touch area */
1280 	input_set_abs_params(touchpad_input_dev, ABS_MT_TOUCH_MAJOR,
1281 			     0, 5000, 0, 0);
1282 	input_set_abs_params(touchpad_input_dev, ABS_MT_TOUCH_MINOR,
1283 			     0, 5000, 0, 0);
1284 
1285 	/* finger approach area */
1286 	input_set_abs_params(touchpad_input_dev, ABS_MT_WIDTH_MAJOR,
1287 			     0, 5000, 0, 0);
1288 	input_set_abs_params(touchpad_input_dev, ABS_MT_WIDTH_MINOR,
1289 			     0, 5000, 0, 0);
1290 
1291 	/* finger orientation */
1292 	input_set_abs_params(touchpad_input_dev, ABS_MT_ORIENTATION,
1293 			     -MAX_FINGER_ORIENTATION, MAX_FINGER_ORIENTATION,
1294 			     0, 0);
1295 
1296 	/* finger position */
1297 	input_set_abs_params(touchpad_input_dev, ABS_MT_POSITION_X,
1298 			     applespi->tp_info.x_min, applespi->tp_info.x_max,
1299 			     0, 0);
1300 	input_set_abs_params(touchpad_input_dev, ABS_MT_POSITION_Y,
1301 			     applespi->tp_info.y_min, applespi->tp_info.y_max,
1302 			     0, 0);
1303 
1304 	/* touchpad button */
1305 	input_set_capability(touchpad_input_dev, EV_KEY, BTN_LEFT);
1306 
1307 	/* multitouch */
1308 	sts = input_mt_init_slots(touchpad_input_dev, MAX_FINGERS,
1309 				  INPUT_MT_POINTER | INPUT_MT_DROP_UNUSED |
1310 					INPUT_MT_TRACK);
1311 	if (sts) {
1312 		dev_err(&applespi->spi->dev,
1313 			"failed to initialize slots: %d", sts);
1314 		return sts;
1315 	}
1316 
1317 	/* register input device */
1318 	sts = input_register_device(touchpad_input_dev);
1319 	if (sts) {
1320 		dev_err(&applespi->spi->dev,
1321 			"Unable to register touchpad input device (%d)\n", sts);
1322 		return sts;
1323 	}
1324 
1325 	/* touchpad_input_dev is read async in spi callback */
1326 	smp_store_release(&applespi->touchpad_input_dev, touchpad_input_dev);
1327 
1328 	return 0;
1329 }
1330 
applespi_worker(struct work_struct *work)1331 static void applespi_worker(struct work_struct *work)
1332 {
1333 	struct applespi_data *applespi =
1334 		container_of(work, struct applespi_data, work);
1335 
1336 	applespi_register_touchpad_device(applespi, &applespi->rcvd_tp_info);
1337 }
1338 
applespi_handle_cmd_response(struct applespi_data *applespi, struct spi_packet *packet, struct message *message)1339 static void applespi_handle_cmd_response(struct applespi_data *applespi,
1340 					 struct spi_packet *packet,
1341 					 struct message *message)
1342 {
1343 	if (packet->device == PACKET_DEV_INFO &&
1344 	    le16_to_cpu(message->type) == 0x1020) {
1345 		/*
1346 		 * We're not allowed to sleep here, but registering an input
1347 		 * device can sleep.
1348 		 */
1349 		applespi->rcvd_tp_info = message->tp_info;
1350 		schedule_work(&applespi->work);
1351 		return;
1352 	}
1353 
1354 	if (le16_to_cpu(message->length) != 0x0000) {
1355 		dev_warn_ratelimited(&applespi->spi->dev,
1356 				     "Received unexpected write response: length=%x\n",
1357 				     le16_to_cpu(message->length));
1358 		return;
1359 	}
1360 
1361 	if (packet->device == PACKET_DEV_TPAD &&
1362 	    le16_to_cpu(message->type) == 0x0252 &&
1363 	    le16_to_cpu(message->rsp_buf_len) == 0x0002)
1364 		dev_info(&applespi->spi->dev, "modeswitch done.\n");
1365 }
1366 
applespi_verify_crc(struct applespi_data *applespi, u8 *buffer, size_t buflen)1367 static bool applespi_verify_crc(struct applespi_data *applespi, u8 *buffer,
1368 				size_t buflen)
1369 {
1370 	u16 crc;
1371 
1372 	crc = crc16(0, buffer, buflen);
1373 	if (crc) {
1374 		dev_warn_ratelimited(&applespi->spi->dev,
1375 				     "Received corrupted packet (crc mismatch)\n");
1376 		trace_applespi_bad_crc(ET_RD_CRC, READ, buffer, buflen);
1377 
1378 		return false;
1379 	}
1380 
1381 	return true;
1382 }
1383 
applespi_debug_print_read_packet(struct applespi_data *applespi, struct spi_packet *packet)1384 static void applespi_debug_print_read_packet(struct applespi_data *applespi,
1385 					     struct spi_packet *packet)
1386 {
1387 	unsigned int evt_type;
1388 
1389 	if (packet->flags == PACKET_TYPE_READ &&
1390 	    packet->device == PACKET_DEV_KEYB)
1391 		evt_type = ET_RD_KEYB;
1392 	else if (packet->flags == PACKET_TYPE_READ &&
1393 		 packet->device == PACKET_DEV_TPAD)
1394 		evt_type = ET_RD_TPAD;
1395 	else if (packet->flags == PACKET_TYPE_WRITE)
1396 		evt_type = applespi->cmd_evt_type;
1397 	else
1398 		evt_type = ET_RD_UNKN;
1399 
1400 	applespi_get_trace_fun(evt_type)(evt_type, PT_READ, applespi->rx_buffer,
1401 					 APPLESPI_PACKET_SIZE);
1402 }
1403 
applespi_got_data(struct applespi_data *applespi)1404 static void applespi_got_data(struct applespi_data *applespi)
1405 {
1406 	struct spi_packet *packet;
1407 	struct message *message;
1408 	unsigned int msg_len;
1409 	unsigned int off;
1410 	unsigned int rem;
1411 	unsigned int len;
1412 
1413 	/* process packet header */
1414 	if (!applespi_verify_crc(applespi, applespi->rx_buffer,
1415 				 APPLESPI_PACKET_SIZE)) {
1416 		unsigned long flags;
1417 
1418 		spin_lock_irqsave(&applespi->cmd_msg_lock, flags);
1419 
1420 		if (applespi->drain) {
1421 			applespi->read_active = false;
1422 			applespi->write_active = false;
1423 
1424 			wake_up_all(&applespi->drain_complete);
1425 		}
1426 
1427 		spin_unlock_irqrestore(&applespi->cmd_msg_lock, flags);
1428 
1429 		return;
1430 	}
1431 
1432 	packet = (struct spi_packet *)applespi->rx_buffer;
1433 
1434 	applespi_debug_print_read_packet(applespi, packet);
1435 
1436 	off = le16_to_cpu(packet->offset);
1437 	rem = le16_to_cpu(packet->remaining);
1438 	len = le16_to_cpu(packet->length);
1439 
1440 	if (len > sizeof(packet->data)) {
1441 		dev_warn_ratelimited(&applespi->spi->dev,
1442 				     "Received corrupted packet (invalid packet length %u)\n",
1443 				     len);
1444 		goto msg_complete;
1445 	}
1446 
1447 	/* handle multi-packet messages */
1448 	if (rem > 0 || off > 0) {
1449 		if (off != applespi->saved_msg_len) {
1450 			dev_warn_ratelimited(&applespi->spi->dev,
1451 					     "Received unexpected offset (got %u, expected %u)\n",
1452 					     off, applespi->saved_msg_len);
1453 			goto msg_complete;
1454 		}
1455 
1456 		if (off + rem > MAX_PKTS_PER_MSG * APPLESPI_PACKET_SIZE) {
1457 			dev_warn_ratelimited(&applespi->spi->dev,
1458 					     "Received message too large (size %u)\n",
1459 					     off + rem);
1460 			goto msg_complete;
1461 		}
1462 
1463 		if (off + len > MAX_PKTS_PER_MSG * APPLESPI_PACKET_SIZE) {
1464 			dev_warn_ratelimited(&applespi->spi->dev,
1465 					     "Received message too large (size %u)\n",
1466 					     off + len);
1467 			goto msg_complete;
1468 		}
1469 
1470 		memcpy(applespi->msg_buf + off, &packet->data, len);
1471 		applespi->saved_msg_len += len;
1472 
1473 		if (rem > 0)
1474 			return;
1475 
1476 		message = (struct message *)applespi->msg_buf;
1477 		msg_len = applespi->saved_msg_len;
1478 	} else {
1479 		message = (struct message *)&packet->data;
1480 		msg_len = len;
1481 	}
1482 
1483 	/* got complete message - verify */
1484 	if (!applespi_verify_crc(applespi, (u8 *)message, msg_len))
1485 		goto msg_complete;
1486 
1487 	if (le16_to_cpu(message->length) != msg_len - MSG_HEADER_SIZE - 2) {
1488 		dev_warn_ratelimited(&applespi->spi->dev,
1489 				     "Received corrupted packet (invalid message length %u - expected %u)\n",
1490 				     le16_to_cpu(message->length),
1491 				     msg_len - MSG_HEADER_SIZE - 2);
1492 		goto msg_complete;
1493 	}
1494 
1495 	/* handle message */
1496 	if (packet->flags == PACKET_TYPE_READ &&
1497 	    packet->device == PACKET_DEV_KEYB) {
1498 		applespi_handle_keyboard_event(applespi, &message->keyboard);
1499 
1500 	} else if (packet->flags == PACKET_TYPE_READ &&
1501 		   packet->device == PACKET_DEV_TPAD) {
1502 		struct touchpad_protocol *tp;
1503 		size_t tp_len;
1504 
1505 		tp = &message->touchpad;
1506 		tp_len = struct_size(tp, fingers, tp->number_of_fingers);
1507 
1508 		if (le16_to_cpu(message->length) + 2 != tp_len) {
1509 			dev_warn_ratelimited(&applespi->spi->dev,
1510 					     "Received corrupted packet (invalid message length %u - num-fingers %u, tp-len %zu)\n",
1511 					     le16_to_cpu(message->length),
1512 					     tp->number_of_fingers, tp_len);
1513 			goto msg_complete;
1514 		}
1515 
1516 		if (tp->number_of_fingers > MAX_FINGERS) {
1517 			dev_warn_ratelimited(&applespi->spi->dev,
1518 					     "Number of reported fingers (%u) exceeds max (%u))\n",
1519 					     tp->number_of_fingers,
1520 					     MAX_FINGERS);
1521 			tp->number_of_fingers = MAX_FINGERS;
1522 		}
1523 
1524 		report_tp_state(applespi, tp);
1525 
1526 	} else if (packet->flags == PACKET_TYPE_WRITE) {
1527 		applespi_handle_cmd_response(applespi, packet, message);
1528 	}
1529 
1530 msg_complete:
1531 	applespi->saved_msg_len = 0;
1532 
1533 	applespi_msg_complete(applespi, packet->flags == PACKET_TYPE_WRITE,
1534 			      true);
1535 }
1536 
applespi_async_read_complete(void *context)1537 static void applespi_async_read_complete(void *context)
1538 {
1539 	struct applespi_data *applespi = context;
1540 
1541 	if (applespi->rd_m.status < 0) {
1542 		dev_warn(&applespi->spi->dev, "Error reading from device: %d\n",
1543 			 applespi->rd_m.status);
1544 		/*
1545 		 * We don't actually know if this was a pure read, or a response
1546 		 * to a write. But this is a rare error condition that should
1547 		 * never occur, so clearing both flags to avoid deadlock.
1548 		 */
1549 		applespi_msg_complete(applespi, true, true);
1550 	} else {
1551 		applespi_got_data(applespi);
1552 	}
1553 
1554 	acpi_finish_gpe(NULL, applespi->gpe);
1555 }
1556 
applespi_notify(acpi_handle gpe_device, u32 gpe, void *context)1557 static u32 applespi_notify(acpi_handle gpe_device, u32 gpe, void *context)
1558 {
1559 	struct applespi_data *applespi = context;
1560 	int sts;
1561 	unsigned long flags;
1562 
1563 	trace_applespi_irq_received(ET_RD_IRQ, PT_READ);
1564 
1565 	spin_lock_irqsave(&applespi->cmd_msg_lock, flags);
1566 
1567 	if (!applespi->suspended) {
1568 		sts = applespi_async(applespi, &applespi->rd_m,
1569 				     applespi_async_read_complete);
1570 		if (sts)
1571 			dev_warn(&applespi->spi->dev,
1572 				 "Error queueing async read to device: %d\n",
1573 				 sts);
1574 		else
1575 			applespi->read_active = true;
1576 	}
1577 
1578 	spin_unlock_irqrestore(&applespi->cmd_msg_lock, flags);
1579 
1580 	return ACPI_INTERRUPT_HANDLED;
1581 }
1582 
applespi_get_saved_bl_level(struct applespi_data *applespi)1583 static int applespi_get_saved_bl_level(struct applespi_data *applespi)
1584 {
1585 	struct efivar_entry *efivar_entry;
1586 	u16 efi_data = 0;
1587 	unsigned long efi_data_len;
1588 	int sts;
1589 
1590 	efivar_entry = kmalloc(sizeof(*efivar_entry), GFP_KERNEL);
1591 	if (!efivar_entry)
1592 		return -ENOMEM;
1593 
1594 	memcpy(efivar_entry->var.VariableName, EFI_BL_LEVEL_NAME,
1595 	       sizeof(EFI_BL_LEVEL_NAME));
1596 	efivar_entry->var.VendorGuid = EFI_BL_LEVEL_GUID;
1597 	efi_data_len = sizeof(efi_data);
1598 
1599 	sts = efivar_entry_get(efivar_entry, NULL, &efi_data_len, &efi_data);
1600 	if (sts && sts != -ENOENT)
1601 		dev_warn(&applespi->spi->dev,
1602 			 "Error getting backlight level from EFI vars: %d\n",
1603 			 sts);
1604 
1605 	kfree(efivar_entry);
1606 
1607 	return sts ? sts : efi_data;
1608 }
1609 
applespi_save_bl_level(struct applespi_data *applespi, unsigned int level)1610 static void applespi_save_bl_level(struct applespi_data *applespi,
1611 				   unsigned int level)
1612 {
1613 	efi_guid_t efi_guid;
1614 	u32 efi_attr;
1615 	unsigned long efi_data_len;
1616 	u16 efi_data;
1617 	int sts;
1618 
1619 	/* Save keyboard backlight level */
1620 	efi_guid = EFI_BL_LEVEL_GUID;
1621 	efi_data = (u16)level;
1622 	efi_data_len = sizeof(efi_data);
1623 	efi_attr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS |
1624 		   EFI_VARIABLE_RUNTIME_ACCESS;
1625 
1626 	sts = efivar_entry_set_safe((efi_char16_t *)EFI_BL_LEVEL_NAME, efi_guid,
1627 				    efi_attr, true, efi_data_len, &efi_data);
1628 	if (sts)
1629 		dev_warn(&applespi->spi->dev,
1630 			 "Error saving backlight level to EFI vars: %d\n", sts);
1631 }
1632 
applespi_probe(struct spi_device *spi)1633 static int applespi_probe(struct spi_device *spi)
1634 {
1635 	struct applespi_data *applespi;
1636 	acpi_handle spi_handle = ACPI_HANDLE(&spi->dev);
1637 	acpi_status acpi_sts;
1638 	int sts, i;
1639 	unsigned long long gpe, usb_status;
1640 
1641 	/* check if the USB interface is present and enabled already */
1642 	acpi_sts = acpi_evaluate_integer(spi_handle, "UIST", NULL, &usb_status);
1643 	if (ACPI_SUCCESS(acpi_sts) && usb_status) {
1644 		/* let the USB driver take over instead */
1645 		dev_info(&spi->dev, "USB interface already enabled\n");
1646 		return -ENODEV;
1647 	}
1648 
1649 	/* allocate driver data */
1650 	applespi = devm_kzalloc(&spi->dev, sizeof(*applespi), GFP_KERNEL);
1651 	if (!applespi)
1652 		return -ENOMEM;
1653 
1654 	applespi->spi = spi;
1655 
1656 	INIT_WORK(&applespi->work, applespi_worker);
1657 
1658 	/* store the driver data */
1659 	spi_set_drvdata(spi, applespi);
1660 
1661 	/* create our buffers */
1662 	applespi->tx_buffer = devm_kmalloc(&spi->dev, APPLESPI_PACKET_SIZE,
1663 					   GFP_KERNEL);
1664 	applespi->tx_status = devm_kmalloc(&spi->dev, APPLESPI_STATUS_SIZE,
1665 					   GFP_KERNEL);
1666 	applespi->rx_buffer = devm_kmalloc(&spi->dev, APPLESPI_PACKET_SIZE,
1667 					   GFP_KERNEL);
1668 	applespi->msg_buf = devm_kmalloc_array(&spi->dev, MAX_PKTS_PER_MSG,
1669 					       APPLESPI_PACKET_SIZE,
1670 					       GFP_KERNEL);
1671 
1672 	if (!applespi->tx_buffer || !applespi->tx_status ||
1673 	    !applespi->rx_buffer || !applespi->msg_buf)
1674 		return -ENOMEM;
1675 
1676 	/* set up our spi messages */
1677 	applespi_setup_read_txfrs(applespi);
1678 	applespi_setup_write_txfrs(applespi);
1679 
1680 	/* cache ACPI method handles */
1681 	acpi_sts = acpi_get_handle(spi_handle, "SIEN", &applespi->sien);
1682 	if (ACPI_FAILURE(acpi_sts)) {
1683 		dev_err(&applespi->spi->dev,
1684 			"Failed to get SIEN ACPI method handle: %s\n",
1685 			acpi_format_exception(acpi_sts));
1686 		return -ENODEV;
1687 	}
1688 
1689 	acpi_sts = acpi_get_handle(spi_handle, "SIST", &applespi->sist);
1690 	if (ACPI_FAILURE(acpi_sts)) {
1691 		dev_err(&applespi->spi->dev,
1692 			"Failed to get SIST ACPI method handle: %s\n",
1693 			acpi_format_exception(acpi_sts));
1694 		return -ENODEV;
1695 	}
1696 
1697 	/* switch on the SPI interface */
1698 	sts = applespi_setup_spi(applespi);
1699 	if (sts)
1700 		return sts;
1701 
1702 	sts = applespi_enable_spi(applespi);
1703 	if (sts)
1704 		return sts;
1705 
1706 	/* setup the keyboard input dev */
1707 	applespi->keyboard_input_dev = devm_input_allocate_device(&spi->dev);
1708 
1709 	if (!applespi->keyboard_input_dev)
1710 		return -ENOMEM;
1711 
1712 	applespi->keyboard_input_dev->name = "Apple SPI Keyboard";
1713 	applespi->keyboard_input_dev->phys = "applespi/input0";
1714 	applespi->keyboard_input_dev->dev.parent = &spi->dev;
1715 	applespi->keyboard_input_dev->id.bustype = BUS_SPI;
1716 
1717 	applespi->keyboard_input_dev->evbit[0] =
1718 			BIT_MASK(EV_KEY) | BIT_MASK(EV_LED) | BIT_MASK(EV_REP);
1719 	applespi->keyboard_input_dev->ledbit[0] = BIT_MASK(LED_CAPSL);
1720 
1721 	input_set_drvdata(applespi->keyboard_input_dev, applespi);
1722 	applespi->keyboard_input_dev->event = applespi_event;
1723 
1724 	for (i = 0; i < ARRAY_SIZE(applespi_scancodes); i++)
1725 		if (applespi_scancodes[i])
1726 			input_set_capability(applespi->keyboard_input_dev,
1727 					     EV_KEY, applespi_scancodes[i]);
1728 
1729 	for (i = 0; i < ARRAY_SIZE(applespi_controlcodes); i++)
1730 		if (applespi_controlcodes[i])
1731 			input_set_capability(applespi->keyboard_input_dev,
1732 					     EV_KEY, applespi_controlcodes[i]);
1733 
1734 	for (i = 0; i < ARRAY_SIZE(applespi_fn_codes); i++)
1735 		if (applespi_fn_codes[i].to)
1736 			input_set_capability(applespi->keyboard_input_dev,
1737 					     EV_KEY, applespi_fn_codes[i].to);
1738 
1739 	input_set_capability(applespi->keyboard_input_dev, EV_KEY, KEY_FN);
1740 
1741 	sts = input_register_device(applespi->keyboard_input_dev);
1742 	if (sts) {
1743 		dev_err(&applespi->spi->dev,
1744 			"Unable to register keyboard input device (%d)\n", sts);
1745 		return -ENODEV;
1746 	}
1747 
1748 	/*
1749 	 * The applespi device doesn't send interrupts normally (as is described
1750 	 * in its DSDT), but rather seems to use ACPI GPEs.
1751 	 */
1752 	acpi_sts = acpi_evaluate_integer(spi_handle, "_GPE", NULL, &gpe);
1753 	if (ACPI_FAILURE(acpi_sts)) {
1754 		dev_err(&applespi->spi->dev,
1755 			"Failed to obtain GPE for SPI slave device: %s\n",
1756 			acpi_format_exception(acpi_sts));
1757 		return -ENODEV;
1758 	}
1759 	applespi->gpe = (int)gpe;
1760 
1761 	acpi_sts = acpi_install_gpe_handler(NULL, applespi->gpe,
1762 					    ACPI_GPE_LEVEL_TRIGGERED,
1763 					    applespi_notify, applespi);
1764 	if (ACPI_FAILURE(acpi_sts)) {
1765 		dev_err(&applespi->spi->dev,
1766 			"Failed to install GPE handler for GPE %d: %s\n",
1767 			applespi->gpe, acpi_format_exception(acpi_sts));
1768 		return -ENODEV;
1769 	}
1770 
1771 	applespi->suspended = false;
1772 
1773 	acpi_sts = acpi_enable_gpe(NULL, applespi->gpe);
1774 	if (ACPI_FAILURE(acpi_sts)) {
1775 		dev_err(&applespi->spi->dev,
1776 			"Failed to enable GPE handler for GPE %d: %s\n",
1777 			applespi->gpe, acpi_format_exception(acpi_sts));
1778 		acpi_remove_gpe_handler(NULL, applespi->gpe, applespi_notify);
1779 		return -ENODEV;
1780 	}
1781 
1782 	/* trigger touchpad setup */
1783 	applespi_init(applespi, false);
1784 
1785 	/*
1786 	 * By default this device is not enabled for wakeup; but USB keyboards
1787 	 * generally are, so the expectation is that by default the keyboard
1788 	 * will wake the system.
1789 	 */
1790 	device_wakeup_enable(&spi->dev);
1791 
1792 	/* set up keyboard-backlight */
1793 	sts = applespi_get_saved_bl_level(applespi);
1794 	if (sts >= 0)
1795 		applespi_set_bl_level(&applespi->backlight_info, sts);
1796 
1797 	applespi->backlight_info.name            = "spi::kbd_backlight";
1798 	applespi->backlight_info.default_trigger = "kbd-backlight";
1799 	applespi->backlight_info.brightness_set  = applespi_set_bl_level;
1800 
1801 	sts = devm_led_classdev_register(&spi->dev, &applespi->backlight_info);
1802 	if (sts)
1803 		dev_warn(&applespi->spi->dev,
1804 			 "Unable to register keyboard backlight class dev (%d)\n",
1805 			 sts);
1806 
1807 	/* set up debugfs entries for touchpad dimensions logging */
1808 	applespi->debugfs_root = debugfs_create_dir("applespi", NULL);
1809 
1810 	debugfs_create_bool("enable_tp_dim", 0600, applespi->debugfs_root,
1811 			    &applespi->debug_tp_dim);
1812 
1813 	debugfs_create_file("tp_dim", 0400, applespi->debugfs_root, applespi,
1814 			    &applespi_tp_dim_fops);
1815 
1816 	return 0;
1817 }
1818 
applespi_drain_writes(struct applespi_data *applespi)1819 static void applespi_drain_writes(struct applespi_data *applespi)
1820 {
1821 	unsigned long flags;
1822 
1823 	spin_lock_irqsave(&applespi->cmd_msg_lock, flags);
1824 
1825 	applespi->drain = true;
1826 	wait_event_lock_irq(applespi->drain_complete, !applespi->write_active,
1827 			    applespi->cmd_msg_lock);
1828 
1829 	spin_unlock_irqrestore(&applespi->cmd_msg_lock, flags);
1830 }
1831 
applespi_drain_reads(struct applespi_data *applespi)1832 static void applespi_drain_reads(struct applespi_data *applespi)
1833 {
1834 	unsigned long flags;
1835 
1836 	spin_lock_irqsave(&applespi->cmd_msg_lock, flags);
1837 
1838 	wait_event_lock_irq(applespi->drain_complete, !applespi->read_active,
1839 			    applespi->cmd_msg_lock);
1840 
1841 	applespi->suspended = true;
1842 
1843 	spin_unlock_irqrestore(&applespi->cmd_msg_lock, flags);
1844 }
1845 
applespi_remove(struct spi_device *spi)1846 static int applespi_remove(struct spi_device *spi)
1847 {
1848 	struct applespi_data *applespi = spi_get_drvdata(spi);
1849 
1850 	applespi_drain_writes(applespi);
1851 
1852 	acpi_disable_gpe(NULL, applespi->gpe);
1853 	acpi_remove_gpe_handler(NULL, applespi->gpe, applespi_notify);
1854 	device_wakeup_disable(&spi->dev);
1855 
1856 	applespi_drain_reads(applespi);
1857 
1858 	debugfs_remove_recursive(applespi->debugfs_root);
1859 
1860 	return 0;
1861 }
1862 
applespi_shutdown(struct spi_device *spi)1863 static void applespi_shutdown(struct spi_device *spi)
1864 {
1865 	struct applespi_data *applespi = spi_get_drvdata(spi);
1866 
1867 	applespi_save_bl_level(applespi, applespi->have_bl_level);
1868 }
1869 
applespi_poweroff_late(struct device *dev)1870 static int applespi_poweroff_late(struct device *dev)
1871 {
1872 	struct spi_device *spi = to_spi_device(dev);
1873 	struct applespi_data *applespi = spi_get_drvdata(spi);
1874 
1875 	applespi_save_bl_level(applespi, applespi->have_bl_level);
1876 
1877 	return 0;
1878 }
1879 
applespi_suspend(struct device *dev)1880 static int __maybe_unused applespi_suspend(struct device *dev)
1881 {
1882 	struct spi_device *spi = to_spi_device(dev);
1883 	struct applespi_data *applespi = spi_get_drvdata(spi);
1884 	acpi_status acpi_sts;
1885 	int sts;
1886 
1887 	/* turn off caps-lock - it'll stay on otherwise */
1888 	sts = applespi_set_capsl_led(applespi, false);
1889 	if (sts)
1890 		dev_warn(&applespi->spi->dev,
1891 			 "Failed to turn off caps-lock led (%d)\n", sts);
1892 
1893 	applespi_drain_writes(applespi);
1894 
1895 	/* disable the interrupt */
1896 	acpi_sts = acpi_disable_gpe(NULL, applespi->gpe);
1897 	if (ACPI_FAILURE(acpi_sts))
1898 		dev_err(&applespi->spi->dev,
1899 			"Failed to disable GPE handler for GPE %d: %s\n",
1900 			applespi->gpe, acpi_format_exception(acpi_sts));
1901 
1902 	applespi_drain_reads(applespi);
1903 
1904 	return 0;
1905 }
1906 
applespi_resume(struct device *dev)1907 static int __maybe_unused applespi_resume(struct device *dev)
1908 {
1909 	struct spi_device *spi = to_spi_device(dev);
1910 	struct applespi_data *applespi = spi_get_drvdata(spi);
1911 	acpi_status acpi_sts;
1912 	unsigned long flags;
1913 
1914 	/* ensure our flags and state reflect a newly resumed device */
1915 	spin_lock_irqsave(&applespi->cmd_msg_lock, flags);
1916 
1917 	applespi->drain = false;
1918 	applespi->have_cl_led_on = false;
1919 	applespi->have_bl_level = 0;
1920 	applespi->cmd_msg_queued = 0;
1921 	applespi->read_active = false;
1922 	applespi->write_active = false;
1923 
1924 	applespi->suspended = false;
1925 
1926 	spin_unlock_irqrestore(&applespi->cmd_msg_lock, flags);
1927 
1928 	/* switch on the SPI interface */
1929 	applespi_enable_spi(applespi);
1930 
1931 	/* re-enable the interrupt */
1932 	acpi_sts = acpi_enable_gpe(NULL, applespi->gpe);
1933 	if (ACPI_FAILURE(acpi_sts))
1934 		dev_err(&applespi->spi->dev,
1935 			"Failed to re-enable GPE handler for GPE %d: %s\n",
1936 			applespi->gpe, acpi_format_exception(acpi_sts));
1937 
1938 	/* switch the touchpad into multitouch mode */
1939 	applespi_init(applespi, true);
1940 
1941 	return 0;
1942 }
1943 
1944 static const struct acpi_device_id applespi_acpi_match[] = {
1945 	{ "APP000D", 0 },
1946 	{ }
1947 };
1948 MODULE_DEVICE_TABLE(acpi, applespi_acpi_match);
1949 
1950 static const struct dev_pm_ops applespi_pm_ops = {
1951 	SET_SYSTEM_SLEEP_PM_OPS(applespi_suspend, applespi_resume)
1952 	.poweroff_late	= applespi_poweroff_late,
1953 };
1954 
1955 static struct spi_driver applespi_driver = {
1956 	.driver		= {
1957 		.name			= "applespi",
1958 		.acpi_match_table	= applespi_acpi_match,
1959 		.pm			= &applespi_pm_ops,
1960 	},
1961 	.probe		= applespi_probe,
1962 	.remove		= applespi_remove,
1963 	.shutdown	= applespi_shutdown,
1964 };
1965 
1966 module_spi_driver(applespi_driver)
1967 
1968 MODULE_LICENSE("GPL v2");
1969 MODULE_DESCRIPTION("MacBook(Pro) SPI Keyboard/Touchpad driver");
1970 MODULE_AUTHOR("Federico Lorenzi");
1971 MODULE_AUTHOR("Ronald Tschalär");
1972