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