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