]> rtime.felk.cvut.cz Git - zynq/linux.git/blob - drivers/input/keyboard/applespi.c
Input: add Apple SPI keyboard and trackpad driver
[zynq/linux.git] / drivers / input / keyboard / applespi.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * MacBook (Pro) SPI keyboard and touchpad driver
4  *
5  * Copyright (c) 2015-2018 Federico Lorenzi
6  * Copyright (c) 2017-2018 Ronald Tschalär
7  */
8
9 /*
10  * The keyboard and touchpad controller on the MacBookAir6, MacBookPro12,
11  * MacBook8 and newer can be driven either by USB or SPI. However the USB
12  * pins are only connected on the MacBookAir6 and 7 and the MacBookPro12.
13  * All others need this driver. The interface is selected using ACPI methods:
14  *
15  * * UIEN ("USB Interface Enable"): If invoked with argument 1, disables SPI
16  *   and enables USB. If invoked with argument 0, disables USB.
17  * * UIST ("USB Interface Status"): Returns 1 if USB is enabled, 0 otherwise.
18  * * SIEN ("SPI Interface Enable"): If invoked with argument 1, disables USB
19  *   and enables SPI. If invoked with argument 0, disables SPI.
20  * * SIST ("SPI Interface Status"): Returns 1 if SPI is enabled, 0 otherwise.
21  * * ISOL: Resets the four GPIO pins used for SPI. Intended to be invoked with
22  *   argument 1, then once more with argument 0.
23  *
24  * UIEN and UIST are only provided on models where the USB pins are connected.
25  *
26  * SPI-based Protocol
27  * ------------------
28  *
29  * The device and driver exchange messages (struct message); each message is
30  * encapsulated in one or more packets (struct spi_packet). There are two types
31  * of exchanges: reads, and writes. A read is signaled by a GPE, upon which one
32  * message can be read from the device. A write exchange consists of writing a
33  * command message, immediately reading a short status packet, and then, upon
34  * receiving a GPE, reading the response message. Write exchanges cannot be
35  * interleaved, i.e. a new write exchange must not be started till the previous
36  * write exchange is complete. Whether a received message is part of a read or
37  * write exchange is indicated in the encapsulating packet's flags field.
38  *
39  * A single message may be too large to fit in a single packet (which has a
40  * fixed, 256-byte size). In that case it will be split over multiple,
41  * consecutive packets.
42  */
43
44 #include <linux/acpi.h>
45 #include <linux/crc16.h>
46 #include <linux/debugfs.h>
47 #include <linux/delay.h>
48 #include <linux/efi.h>
49 #include <linux/input.h>
50 #include <linux/input/mt.h>
51 #include <linux/leds.h>
52 #include <linux/module.h>
53 #include <linux/spinlock.h>
54 #include <linux/spi/spi.h>
55 #include <linux/wait.h>
56 #include <linux/workqueue.h>
57
58 #include <asm/barrier.h>
59 #include <asm/unaligned.h>
60
61 #define CREATE_TRACE_POINTS
62 #include "applespi.h"
63 #include "applespi_trace.h"
64
65 #define APPLESPI_PACKET_SIZE    256
66 #define APPLESPI_STATUS_SIZE    4
67
68 #define PACKET_TYPE_READ        0x20
69 #define PACKET_TYPE_WRITE       0x40
70 #define PACKET_DEV_KEYB         0x01
71 #define PACKET_DEV_TPAD         0x02
72 #define PACKET_DEV_INFO         0xd0
73
74 #define MAX_ROLLOVER            6
75
76 #define MAX_FINGERS             11
77 #define MAX_FINGER_ORIENTATION  16384
78 #define MAX_PKTS_PER_MSG        2
79
80 #define KBD_BL_LEVEL_MIN        32U
81 #define KBD_BL_LEVEL_MAX        255U
82 #define KBD_BL_LEVEL_SCALE      1000000U
83 #define KBD_BL_LEVEL_ADJ        \
84         ((KBD_BL_LEVEL_MAX - KBD_BL_LEVEL_MIN) * KBD_BL_LEVEL_SCALE / 255U)
85
86 #define EFI_BL_LEVEL_NAME       L"KeyboardBacklightLevel"
87 #define EFI_BL_LEVEL_GUID       EFI_GUID(0xa076d2af, 0x9678, 0x4386, 0x8b, 0x58, 0x1f, 0xc8, 0xef, 0x04, 0x16, 0x19)
88
89 #define APPLE_FLAG_FKEY         0x01
90
91 #define SPI_RW_CHG_DELAY_US     100     /* from experimentation, in µs */
92
93 #define SYNAPTICS_VENDOR_ID     0x06cb
94
95 static unsigned int fnmode = 1;
96 module_param(fnmode, uint, 0644);
97 MODULE_PARM_DESC(fnmode, "Mode of Fn key on Apple keyboards (0 = disabled, [1] = fkeyslast, 2 = fkeysfirst)");
98
99 static unsigned int fnremap;
100 module_param(fnremap, uint, 0644);
101 MODULE_PARM_DESC(fnremap, "Remap Fn key ([0] = no-remap; 1 = left-ctrl, 2 = left-shift, 3 = left-alt, 4 = left-meta, 6 = right-shift, 7 = right-alt, 8 = right-meta)");
102
103 static bool iso_layout;
104 module_param(iso_layout, bool, 0644);
105 MODULE_PARM_DESC(iso_layout, "Enable/Disable hardcoded ISO-layout of the keyboard. ([0] = disabled, 1 = enabled)");
106
107 static char touchpad_dimensions[40];
108 module_param_string(touchpad_dimensions, touchpad_dimensions,
109                     sizeof(touchpad_dimensions), 0444);
110 MODULE_PARM_DESC(touchpad_dimensions, "The pixel dimensions of the touchpad, as XxY+W+H .");
111
112 /**
113  * struct keyboard_protocol - keyboard message.
114  * message.type = 0x0110, message.length = 0x000a
115  *
116  * @unknown1:           unknown
117  * @modifiers:          bit-set of modifier/control keys pressed
118  * @unknown2:           unknown
119  * @keys_pressed:       the (non-modifier) keys currently pressed
120  * @fn_pressed:         whether the fn key is currently pressed
121  * @crc16:              crc over the whole message struct (message header +
122  *                      this struct) minus this @crc16 field
123  */
124 struct keyboard_protocol {
125         u8                      unknown1;
126         u8                      modifiers;
127         u8                      unknown2;
128         u8                      keys_pressed[MAX_ROLLOVER];
129         u8                      fn_pressed;
130         __le16                  crc16;
131 };
132
133 /**
134  * struct tp_finger - single trackpad finger structure, le16-aligned
135  *
136  * @origin:             zero when switching track finger
137  * @abs_x:              absolute x coodinate
138  * @abs_y:              absolute y coodinate
139  * @rel_x:              relative x coodinate
140  * @rel_y:              relative y coodinate
141  * @tool_major:         tool area, major axis
142  * @tool_minor:         tool area, minor axis
143  * @orientation:        16384 when point, else 15 bit angle
144  * @touch_major:        touch area, major axis
145  * @touch_minor:        touch area, minor axis
146  * @unused:             zeros
147  * @pressure:           pressure on forcetouch touchpad
148  * @multi:              one finger: varies, more fingers: constant
149  * @crc16:              on last finger: crc over the whole message struct
150  *                      (i.e. message header + this struct) minus the last
151  *                      @crc16 field; unknown on all other fingers.
152  */
153 struct tp_finger {
154         __le16 origin;
155         __le16 abs_x;
156         __le16 abs_y;
157         __le16 rel_x;
158         __le16 rel_y;
159         __le16 tool_major;
160         __le16 tool_minor;
161         __le16 orientation;
162         __le16 touch_major;
163         __le16 touch_minor;
164         __le16 unused[2];
165         __le16 pressure;
166         __le16 multi;
167         __le16 crc16;
168 };
169
170 /**
171  * struct touchpad_protocol - touchpad message.
172  * message.type = 0x0210
173  *
174  * @unknown1:           unknown
175  * @clicked:            1 if a button-click was detected, 0 otherwise
176  * @unknown2:           unknown
177  * @number_of_fingers:  the number of fingers being reported in @fingers
178  * @clicked2:           same as @clicked
179  * @unknown3:           unknown
180  * @fingers:            the data for each finger
181  */
182 struct touchpad_protocol {
183         u8                      unknown1[1];
184         u8                      clicked;
185         u8                      unknown2[28];
186         u8                      number_of_fingers;
187         u8                      clicked2;
188         u8                      unknown3[16];
189         struct tp_finger        fingers[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  */
199 struct command_protocol_tp_info {
200         __le16                  crc16;
201 };
202
203 /**
204  * struct touchpad_info - touchpad info response.
205  * message.type = 0x1020, message.length = 0x006e
206  *
207  * @unknown1:           unknown
208  * @model_flags:        flags (vary by model number, but significance otherwise
209  *                      unknown)
210  * @model_no:           the touchpad model number
211  * @unknown2:           unknown
212  * @crc16:              crc over the whole message struct (message header +
213  *                      this struct) minus this @crc16 field
214  */
215 struct touchpad_info_protocol {
216         u8                      unknown1[105];
217         u8                      model_flags;
218         u8                      model_no;
219         u8                      unknown2[3];
220         __le16                  crc16;
221 };
222
223 /**
224  * struct command_protocol_mt_init - initialize multitouch.
225  * message.type = 0x0252, message.length = 0x0002
226  *
227  * @cmd:                value: 0x0102
228  * @crc16:              crc over the whole message struct (message header +
229  *                      this struct) minus this @crc16 field
230  */
231 struct command_protocol_mt_init {
232         __le16                  cmd;
233         __le16                  crc16;
234 };
235
236 /**
237  * struct command_protocol_capsl - toggle caps-lock led
238  * message.type = 0x0151, message.length = 0x0002
239  *
240  * @unknown:            value: 0x01 (length?)
241  * @led:                0 off, 2 on
242  * @crc16:              crc over the whole message struct (message header +
243  *                      this struct) minus this @crc16 field
244  */
245 struct command_protocol_capsl {
246         u8                      unknown;
247         u8                      led;
248         __le16                  crc16;
249 };
250
251 /**
252  * struct command_protocol_bl - set keyboard backlight brightness
253  * message.type = 0xB051, message.length = 0x0006
254  *
255  * @const1:             value: 0x01B0
256  * @level:              the brightness level to set
257  * @const2:             value: 0x0001 (backlight off), 0x01F4 (backlight on)
258  * @crc16:              crc over the whole message struct (message header +
259  *                      this struct) minus this @crc16 field
260  */
261 struct command_protocol_bl {
262         __le16                  const1;
263         __le16                  level;
264         __le16                  const2;
265         __le16                  crc16;
266 };
267
268 /**
269  * struct message - a complete spi message.
270  *
271  * Each message begins with fixed header, followed by a message-type specific
272  * payload, and ends with a 16-bit crc. Because of the varying lengths of the
273  * payload, the crc is defined at the end of each payload struct, rather than
274  * in this struct.
275  *
276  * @type:       the message type
277  * @zero:       always 0
278  * @counter:    incremented on each message, rolls over after 255; there is a
279  *              separate counter for each message type.
280  * @rsp_buf_len:response buffer length (the exact nature of this field is quite
281  *              speculative). On a request/write this is often the same as
282  *              @length, though in some cases it has been seen to be much larger
283  *              (e.g. 0x400); on a response/read this the same as on the
284  *              request; for reads that are not responses it is 0.
285  * @length:     length of the remainder of the data in the whole message
286  *              structure (after re-assembly in case of being split over
287  *              multiple spi-packets), minus the trailing crc. The total size
288  *              of the message struct is therefore @length + 10.
289  */
290 struct 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  */
336 struct 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
346 struct 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 */
353 struct applespi_tp_info {
354         int     x_min;
355         int     y_min;
356         int     x_max;
357         int     y_max;
358 };
359
360 struct 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
426 static 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  */
449 static 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
460 struct applespi_key_translation {
461         u16 from;
462         u16 to;
463         u8 flags;
464 };
465
466 static 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
488 static const struct applespi_key_translation apple_iso_keyboard[] = {
489         { KEY_GRAVE,    KEY_102ND },
490         { KEY_102ND,    KEY_GRAVE },
491         { }
492 };
493
494 struct applespi_tp_model_info {
495         u16                     model;
496         struct applespi_tp_info tp_info;
497 };
498
499 static 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
515 typedef void (*applespi_trace_fun)(enum applespi_evt_type,
516                                    enum applespi_pkt_type, u8 *, size_t);
517
518 static 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
539 static 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
558 static 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
596 static 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
605 static 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
625 static 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
657 static 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
671 static 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
701 static int applespi_send_cmd_msg(struct applespi_data *applespi);
702
703 static 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
726 static 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
747 static 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
865 static 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
880 static 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
896 static 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         int sts;
903
904         spin_lock_irqsave(&applespi->cmd_msg_lock, flags);
905
906         if (value == 0) {
907                 applespi->want_bl_level = value;
908         } else {
909                 /*
910                  * The backlight does not turn on till level 32, so we scale
911                  * the range here so that from a user's perspective it turns
912                  * on at 1.
913                  */
914                 applespi->want_bl_level =
915                         ((value * KBD_BL_LEVEL_ADJ) / KBD_BL_LEVEL_SCALE +
916                          KBD_BL_LEVEL_MIN);
917         }
918
919         sts = applespi_send_cmd_msg(applespi);
920
921         spin_unlock_irqrestore(&applespi->cmd_msg_lock, flags);
922 }
923
924 static int applespi_event(struct input_dev *dev, unsigned int type,
925                           unsigned int code, int value)
926 {
927         struct applespi_data *applespi = input_get_drvdata(dev);
928
929         switch (type) {
930         case EV_LED:
931                 applespi_set_capsl_led(applespi, !!test_bit(LED_CAPSL, dev->led));
932                 return 0;
933         }
934
935         return -EINVAL;
936 }
937
938 /* lifted from the BCM5974 driver and renamed from raw2int */
939 /* convert 16-bit little endian to signed integer */
940 static inline int le16_to_int(__le16 x)
941 {
942         return (signed short)le16_to_cpu(x);
943 }
944
945 static void applespi_debug_update_dimensions(struct applespi_data *applespi,
946                                              const struct tp_finger *f)
947 {
948         applespi->tp_dim_min_x = min_t(int, applespi->tp_dim_min_x, f->abs_x);
949         applespi->tp_dim_max_x = max_t(int, applespi->tp_dim_max_x, f->abs_x);
950         applespi->tp_dim_min_y = min_t(int, applespi->tp_dim_min_y, f->abs_y);
951         applespi->tp_dim_max_y = max_t(int, applespi->tp_dim_max_y, f->abs_y);
952 }
953
954 static int applespi_tp_dim_open(struct inode *inode, struct file *file)
955 {
956         struct applespi_data *applespi = inode->i_private;
957
958         file->private_data = applespi;
959
960         snprintf(applespi->tp_dim_val, sizeof(applespi->tp_dim_val),
961                  "0x%.4x %dx%d+%u+%u\n",
962                  applespi->touchpad_input_dev->id.product,
963                  applespi->tp_dim_min_x, applespi->tp_dim_min_y,
964                  applespi->tp_dim_max_x - applespi->tp_dim_min_x,
965                  applespi->tp_dim_max_y - applespi->tp_dim_min_y);
966
967         return nonseekable_open(inode, file);
968 }
969
970 static ssize_t applespi_tp_dim_read(struct file *file, char __user *buf,
971                                     size_t len, loff_t *off)
972 {
973         struct applespi_data *applespi = file->private_data;
974
975         return simple_read_from_buffer(buf, len, off, applespi->tp_dim_val,
976                                        strlen(applespi->tp_dim_val));
977 }
978
979 static const struct file_operations applespi_tp_dim_fops = {
980         .owner = THIS_MODULE,
981         .open = applespi_tp_dim_open,
982         .read = applespi_tp_dim_read,
983         .llseek = no_llseek,
984 };
985
986 static void report_finger_data(struct input_dev *input, int slot,
987                                const struct input_mt_pos *pos,
988                                const struct tp_finger *f)
989 {
990         input_mt_slot(input, slot);
991         input_mt_report_slot_state(input, MT_TOOL_FINGER, true);
992
993         input_report_abs(input, ABS_MT_TOUCH_MAJOR,
994                          le16_to_int(f->touch_major) << 1);
995         input_report_abs(input, ABS_MT_TOUCH_MINOR,
996                          le16_to_int(f->touch_minor) << 1);
997         input_report_abs(input, ABS_MT_WIDTH_MAJOR,
998                          le16_to_int(f->tool_major) << 1);
999         input_report_abs(input, ABS_MT_WIDTH_MINOR,
1000                          le16_to_int(f->tool_minor) << 1);
1001         input_report_abs(input, ABS_MT_ORIENTATION,
1002                          MAX_FINGER_ORIENTATION - le16_to_int(f->orientation));
1003         input_report_abs(input, ABS_MT_POSITION_X, pos->x);
1004         input_report_abs(input, ABS_MT_POSITION_Y, pos->y);
1005 }
1006
1007 static void report_tp_state(struct applespi_data *applespi,
1008                             struct touchpad_protocol *t)
1009 {
1010         const struct tp_finger *f;
1011         struct input_dev *input;
1012         const struct applespi_tp_info *tp_info = &applespi->tp_info;
1013         int i, n;
1014
1015         /* touchpad_input_dev is set async in worker */
1016         input = smp_load_acquire(&applespi->touchpad_input_dev);
1017         if (!input)
1018                 return; /* touchpad isn't initialized yet */
1019
1020         n = 0;
1021
1022         for (i = 0; i < t->number_of_fingers; i++) {
1023                 f = &t->fingers[i];
1024                 if (le16_to_int(f->touch_major) == 0)
1025                         continue;
1026                 applespi->pos[n].x = le16_to_int(f->abs_x);
1027                 applespi->pos[n].y = tp_info->y_min + tp_info->y_max -
1028                                      le16_to_int(f->abs_y);
1029                 n++;
1030
1031                 if (applespi->debug_tp_dim)
1032                         applespi_debug_update_dimensions(applespi, f);
1033         }
1034
1035         input_mt_assign_slots(input, applespi->slots, applespi->pos, n, 0);
1036
1037         for (i = 0; i < n; i++)
1038                 report_finger_data(input, applespi->slots[i],
1039                                    &applespi->pos[i], &t->fingers[i]);
1040
1041         input_mt_sync_frame(input);
1042         input_report_key(input, BTN_LEFT, t->clicked);
1043
1044         input_sync(input);
1045 }
1046
1047 static const struct applespi_key_translation *
1048 applespi_find_translation(const struct applespi_key_translation *table, u16 key)
1049 {
1050         const struct applespi_key_translation *trans;
1051
1052         for (trans = table; trans->from; trans++)
1053                 if (trans->from == key)
1054                         return trans;
1055
1056         return NULL;
1057 }
1058
1059 static unsigned int applespi_translate_fn_key(unsigned int key, int fn_pressed)
1060 {
1061         const struct applespi_key_translation *trans;
1062         int do_translate;
1063
1064         trans = applespi_find_translation(applespi_fn_codes, key);
1065         if (trans) {
1066                 if (trans->flags & APPLE_FLAG_FKEY)
1067                         do_translate = (fnmode == 2 && fn_pressed) ||
1068                                        (fnmode == 1 && !fn_pressed);
1069                 else
1070                         do_translate = fn_pressed;
1071
1072                 if (do_translate)
1073                         key = trans->to;
1074         }
1075
1076         return key;
1077 }
1078
1079 static unsigned int applespi_translate_iso_layout(unsigned int key)
1080 {
1081         const struct applespi_key_translation *trans;
1082
1083         trans = applespi_find_translation(apple_iso_keyboard, key);
1084         if (trans)
1085                 key = trans->to;
1086
1087         return key;
1088 }
1089
1090 static unsigned int applespi_code_to_key(u8 code, int fn_pressed)
1091 {
1092         unsigned int key = applespi_scancodes[code];
1093
1094         if (fnmode)
1095                 key = applespi_translate_fn_key(key, fn_pressed);
1096         if (iso_layout)
1097                 key = applespi_translate_iso_layout(key);
1098         return key;
1099 }
1100
1101 static void
1102 applespi_remap_fn_key(struct keyboard_protocol *keyboard_protocol)
1103 {
1104         unsigned char tmp;
1105         u8 bit = BIT((fnremap - 1) & 0x07);
1106
1107         if (!fnremap || fnremap > ARRAY_SIZE(applespi_controlcodes) ||
1108             !applespi_controlcodes[fnremap - 1])
1109                 return;
1110
1111         tmp = keyboard_protocol->fn_pressed;
1112         keyboard_protocol->fn_pressed = !!(keyboard_protocol->modifiers & bit);
1113         if (tmp)
1114                 keyboard_protocol->modifiers |= bit;
1115         else
1116                 keyboard_protocol->modifiers &= ~bit;
1117 }
1118
1119 static void
1120 applespi_handle_keyboard_event(struct applespi_data *applespi,
1121                                struct keyboard_protocol *keyboard_protocol)
1122 {
1123         unsigned int key;
1124         int i;
1125
1126         compiletime_assert(ARRAY_SIZE(applespi_controlcodes) ==
1127                            sizeof_field(struct keyboard_protocol, modifiers) * 8,
1128                            "applespi_controlcodes has wrong number of entries");
1129
1130         /* check for rollover overflow, which is signalled by all keys == 1 */
1131         if (!memchr_inv(keyboard_protocol->keys_pressed, 1, MAX_ROLLOVER))
1132                 return;
1133
1134         /* remap fn key if desired */
1135         applespi_remap_fn_key(keyboard_protocol);
1136
1137         /* check released keys */
1138         for (i = 0; i < MAX_ROLLOVER; i++) {
1139                 if (memchr(keyboard_protocol->keys_pressed,
1140                            applespi->last_keys_pressed[i], MAX_ROLLOVER))
1141                         continue;       /* key is still pressed */
1142
1143                 key = applespi_code_to_key(applespi->last_keys_pressed[i],
1144                                            applespi->last_keys_fn_pressed[i]);
1145                 input_report_key(applespi->keyboard_input_dev, key, 0);
1146                 applespi->last_keys_fn_pressed[i] = 0;
1147         }
1148
1149         /* check pressed keys */
1150         for (i = 0; i < MAX_ROLLOVER; i++) {
1151                 if (keyboard_protocol->keys_pressed[i] <
1152                                 ARRAY_SIZE(applespi_scancodes) &&
1153                     keyboard_protocol->keys_pressed[i] > 0) {
1154                         key = applespi_code_to_key(
1155                                         keyboard_protocol->keys_pressed[i],
1156                                         keyboard_protocol->fn_pressed);
1157                         input_report_key(applespi->keyboard_input_dev, key, 1);
1158                         applespi->last_keys_fn_pressed[i] =
1159                                         keyboard_protocol->fn_pressed;
1160                 }
1161         }
1162
1163         /* check control keys */
1164         for (i = 0; i < ARRAY_SIZE(applespi_controlcodes); i++) {
1165                 if (keyboard_protocol->modifiers & BIT(i))
1166                         input_report_key(applespi->keyboard_input_dev,
1167                                          applespi_controlcodes[i], 1);
1168                 else
1169                         input_report_key(applespi->keyboard_input_dev,
1170                                          applespi_controlcodes[i], 0);
1171         }
1172
1173         /* check function key */
1174         if (keyboard_protocol->fn_pressed && !applespi->last_fn_pressed)
1175                 input_report_key(applespi->keyboard_input_dev, KEY_FN, 1);
1176         else if (!keyboard_protocol->fn_pressed && applespi->last_fn_pressed)
1177                 input_report_key(applespi->keyboard_input_dev, KEY_FN, 0);
1178         applespi->last_fn_pressed = keyboard_protocol->fn_pressed;
1179
1180         /* done */
1181         input_sync(applespi->keyboard_input_dev);
1182         memcpy(&applespi->last_keys_pressed, keyboard_protocol->keys_pressed,
1183                sizeof(applespi->last_keys_pressed));
1184 }
1185
1186 static const struct applespi_tp_info *applespi_find_touchpad_info(u8 model)
1187 {
1188         const struct applespi_tp_model_info *info;
1189
1190         for (info = applespi_tp_models; info->model; info++) {
1191                 if (info->model == model)
1192                         return &info->tp_info;
1193         }
1194
1195         return NULL;
1196 }
1197
1198 static int
1199 applespi_register_touchpad_device(struct applespi_data *applespi,
1200                                   struct touchpad_info_protocol *rcvd_tp_info)
1201 {
1202         const struct applespi_tp_info *tp_info;
1203         struct input_dev *touchpad_input_dev;
1204         int sts;
1205
1206         /* set up touchpad dimensions */
1207         tp_info = applespi_find_touchpad_info(rcvd_tp_info->model_no);
1208         if (!tp_info) {
1209                 dev_warn(&applespi->spi->dev,
1210                          "Unknown touchpad model %x - falling back to MB8 touchpad\n",
1211                          rcvd_tp_info->model_no);
1212                 tp_info = &applespi_tp_models[0].tp_info;
1213         }
1214
1215         applespi->tp_info = *tp_info;
1216
1217         if (touchpad_dimensions[0]) {
1218                 int x, y, w, h;
1219
1220                 sts = sscanf(touchpad_dimensions, "%dx%d+%u+%u", &x, &y, &w, &h);
1221                 if (sts == 4) {
1222                         dev_info(&applespi->spi->dev,
1223                                  "Overriding touchpad dimensions from module param\n");
1224                         applespi->tp_info.x_min = x;
1225                         applespi->tp_info.y_min = y;
1226                         applespi->tp_info.x_max = x + w;
1227                         applespi->tp_info.y_max = y + h;
1228                 } else {
1229                         dev_warn(&applespi->spi->dev,
1230                                  "Invalid touchpad dimensions '%s': must be in the form XxY+W+H\n",
1231                                  touchpad_dimensions);
1232                         touchpad_dimensions[0] = '\0';
1233                 }
1234         }
1235         if (!touchpad_dimensions[0]) {
1236                 snprintf(touchpad_dimensions, sizeof(touchpad_dimensions),
1237                          "%dx%d+%u+%u",
1238                          applespi->tp_info.x_min,
1239                          applespi->tp_info.y_min,
1240                          applespi->tp_info.x_max - applespi->tp_info.x_min,
1241                          applespi->tp_info.y_max - applespi->tp_info.y_min);
1242         }
1243
1244         /* create touchpad input device */
1245         touchpad_input_dev = devm_input_allocate_device(&applespi->spi->dev);
1246         if (!touchpad_input_dev) {
1247                 dev_err(&applespi->spi->dev,
1248                         "Failed to allocate touchpad input device\n");
1249                 return -ENOMEM;
1250         }
1251
1252         touchpad_input_dev->name = "Apple SPI Touchpad";
1253         touchpad_input_dev->phys = "applespi/input1";
1254         touchpad_input_dev->dev.parent = &applespi->spi->dev;
1255         touchpad_input_dev->id.bustype = BUS_SPI;
1256         touchpad_input_dev->id.vendor = SYNAPTICS_VENDOR_ID;
1257         touchpad_input_dev->id.product =
1258                         rcvd_tp_info->model_no << 8 | rcvd_tp_info->model_flags;
1259
1260         /* basic properties */
1261         input_set_capability(touchpad_input_dev, EV_REL, REL_X);
1262         input_set_capability(touchpad_input_dev, EV_REL, REL_Y);
1263
1264         __set_bit(INPUT_PROP_POINTER, touchpad_input_dev->propbit);
1265         __set_bit(INPUT_PROP_BUTTONPAD, touchpad_input_dev->propbit);
1266
1267         /* finger touch area */
1268         input_set_abs_params(touchpad_input_dev, ABS_MT_TOUCH_MAJOR,
1269                              0, 5000, 0, 0);
1270         input_set_abs_params(touchpad_input_dev, ABS_MT_TOUCH_MINOR,
1271                              0, 5000, 0, 0);
1272
1273         /* finger approach area */
1274         input_set_abs_params(touchpad_input_dev, ABS_MT_WIDTH_MAJOR,
1275                              0, 5000, 0, 0);
1276         input_set_abs_params(touchpad_input_dev, ABS_MT_WIDTH_MINOR,
1277                              0, 5000, 0, 0);
1278
1279         /* finger orientation */
1280         input_set_abs_params(touchpad_input_dev, ABS_MT_ORIENTATION,
1281                              -MAX_FINGER_ORIENTATION, MAX_FINGER_ORIENTATION,
1282                              0, 0);
1283
1284         /* finger position */
1285         input_set_abs_params(touchpad_input_dev, ABS_MT_POSITION_X,
1286                              applespi->tp_info.x_min, applespi->tp_info.x_max,
1287                              0, 0);
1288         input_set_abs_params(touchpad_input_dev, ABS_MT_POSITION_Y,
1289                              applespi->tp_info.y_min, applespi->tp_info.y_max,
1290                              0, 0);
1291
1292         /* touchpad button */
1293         input_set_capability(touchpad_input_dev, EV_KEY, BTN_LEFT);
1294
1295         /* multitouch */
1296         sts = input_mt_init_slots(touchpad_input_dev, MAX_FINGERS,
1297                                   INPUT_MT_POINTER | INPUT_MT_DROP_UNUSED |
1298                                         INPUT_MT_TRACK);
1299         if (sts) {
1300                 dev_err(&applespi->spi->dev,
1301                         "failed to initialize slots: %d", sts);
1302                 return sts;
1303         }
1304
1305         /* register input device */
1306         sts = input_register_device(touchpad_input_dev);
1307         if (sts) {
1308                 dev_err(&applespi->spi->dev,
1309                         "Unable to register touchpad input device (%d)\n", sts);
1310                 return sts;
1311         }
1312
1313         /* touchpad_input_dev is read async in spi callback */
1314         smp_store_release(&applespi->touchpad_input_dev, touchpad_input_dev);
1315
1316         return 0;
1317 }
1318
1319 static void applespi_worker(struct work_struct *work)
1320 {
1321         struct applespi_data *applespi =
1322                 container_of(work, struct applespi_data, work);
1323
1324         applespi_register_touchpad_device(applespi, &applespi->rcvd_tp_info);
1325 }
1326
1327 static void applespi_handle_cmd_response(struct applespi_data *applespi,
1328                                          struct spi_packet *packet,
1329                                          struct message *message)
1330 {
1331         if (packet->device == PACKET_DEV_INFO &&
1332             le16_to_cpu(message->type) == 0x1020) {
1333                 /*
1334                  * We're not allowed to sleep here, but registering an input
1335                  * device can sleep.
1336                  */
1337                 applespi->rcvd_tp_info = message->tp_info;
1338                 schedule_work(&applespi->work);
1339                 return;
1340         }
1341
1342         if (le16_to_cpu(message->length) != 0x0000) {
1343                 dev_warn_ratelimited(&applespi->spi->dev,
1344                                      "Received unexpected write response: length=%x\n",
1345                                      le16_to_cpu(message->length));
1346                 return;
1347         }
1348
1349         if (packet->device == PACKET_DEV_TPAD &&
1350             le16_to_cpu(message->type) == 0x0252 &&
1351             le16_to_cpu(message->rsp_buf_len) == 0x0002)
1352                 dev_info(&applespi->spi->dev, "modeswitch done.\n");
1353 }
1354
1355 static bool applespi_verify_crc(struct applespi_data *applespi, u8 *buffer,
1356                                 size_t buflen)
1357 {
1358         u16 crc;
1359
1360         crc = crc16(0, buffer, buflen);
1361         if (crc) {
1362                 dev_warn_ratelimited(&applespi->spi->dev,
1363                                      "Received corrupted packet (crc mismatch)\n");
1364                 trace_applespi_bad_crc(ET_RD_CRC, READ, buffer, buflen);
1365
1366                 return false;
1367         }
1368
1369         return true;
1370 }
1371
1372 static void applespi_debug_print_read_packet(struct applespi_data *applespi,
1373                                              struct spi_packet *packet)
1374 {
1375         unsigned int evt_type;
1376
1377         if (packet->flags == PACKET_TYPE_READ &&
1378             packet->device == PACKET_DEV_KEYB)
1379                 evt_type = ET_RD_KEYB;
1380         else if (packet->flags == PACKET_TYPE_READ &&
1381                  packet->device == PACKET_DEV_TPAD)
1382                 evt_type = ET_RD_TPAD;
1383         else if (packet->flags == PACKET_TYPE_WRITE)
1384                 evt_type = applespi->cmd_evt_type;
1385         else
1386                 evt_type = ET_RD_UNKN;
1387
1388         applespi_get_trace_fun(evt_type)(evt_type, PT_READ, applespi->rx_buffer,
1389                                          APPLESPI_PACKET_SIZE);
1390 }
1391
1392 static void applespi_got_data(struct applespi_data *applespi)
1393 {
1394         struct spi_packet *packet;
1395         struct message *message;
1396         unsigned int msg_len;
1397         unsigned int off;
1398         unsigned int rem;
1399         unsigned int len;
1400
1401         /* process packet header */
1402         if (!applespi_verify_crc(applespi, applespi->rx_buffer,
1403                                  APPLESPI_PACKET_SIZE)) {
1404                 unsigned long flags;
1405
1406                 spin_lock_irqsave(&applespi->cmd_msg_lock, flags);
1407
1408                 if (applespi->drain) {
1409                         applespi->read_active = false;
1410                         applespi->write_active = false;
1411
1412                         wake_up_all(&applespi->drain_complete);
1413                 }
1414
1415                 spin_unlock_irqrestore(&applespi->cmd_msg_lock, flags);
1416
1417                 return;
1418         }
1419
1420         packet = (struct spi_packet *)applespi->rx_buffer;
1421
1422         applespi_debug_print_read_packet(applespi, packet);
1423
1424         off = le16_to_cpu(packet->offset);
1425         rem = le16_to_cpu(packet->remaining);
1426         len = le16_to_cpu(packet->length);
1427
1428         if (len > sizeof(packet->data)) {
1429                 dev_warn_ratelimited(&applespi->spi->dev,
1430                                      "Received corrupted packet (invalid packet length %u)\n",
1431                                      len);
1432                 goto msg_complete;
1433         }
1434
1435         /* handle multi-packet messages */
1436         if (rem > 0 || off > 0) {
1437                 if (off != applespi->saved_msg_len) {
1438                         dev_warn_ratelimited(&applespi->spi->dev,
1439                                              "Received unexpected offset (got %u, expected %u)\n",
1440                                              off, applespi->saved_msg_len);
1441                         goto msg_complete;
1442                 }
1443
1444                 if (off + rem > MAX_PKTS_PER_MSG * APPLESPI_PACKET_SIZE) {
1445                         dev_warn_ratelimited(&applespi->spi->dev,
1446                                              "Received message too large (size %u)\n",
1447                                              off + rem);
1448                         goto msg_complete;
1449                 }
1450
1451                 if (off + len > MAX_PKTS_PER_MSG * APPLESPI_PACKET_SIZE) {
1452                         dev_warn_ratelimited(&applespi->spi->dev,
1453                                              "Received message too large (size %u)\n",
1454                                              off + len);
1455                         goto msg_complete;
1456                 }
1457
1458                 memcpy(applespi->msg_buf + off, &packet->data, len);
1459                 applespi->saved_msg_len += len;
1460
1461                 if (rem > 0)
1462                         return;
1463
1464                 message = (struct message *)applespi->msg_buf;
1465                 msg_len = applespi->saved_msg_len;
1466         } else {
1467                 message = (struct message *)&packet->data;
1468                 msg_len = len;
1469         }
1470
1471         /* got complete message - verify */
1472         if (!applespi_verify_crc(applespi, (u8 *)message, msg_len))
1473                 goto msg_complete;
1474
1475         if (le16_to_cpu(message->length) != msg_len - MSG_HEADER_SIZE - 2) {
1476                 dev_warn_ratelimited(&applespi->spi->dev,
1477                                      "Received corrupted packet (invalid message length %u - expected %u)\n",
1478                                      le16_to_cpu(message->length),
1479                                      msg_len - MSG_HEADER_SIZE - 2);
1480                 goto msg_complete;
1481         }
1482
1483         /* handle message */
1484         if (packet->flags == PACKET_TYPE_READ &&
1485             packet->device == PACKET_DEV_KEYB) {
1486                 applespi_handle_keyboard_event(applespi, &message->keyboard);
1487
1488         } else if (packet->flags == PACKET_TYPE_READ &&
1489                    packet->device == PACKET_DEV_TPAD) {
1490                 struct touchpad_protocol *tp;
1491                 size_t tp_len;
1492
1493                 tp = &message->touchpad;
1494                 tp_len = sizeof(*tp) +
1495                          tp->number_of_fingers * sizeof(tp->fingers[0]);
1496
1497                 if (le16_to_cpu(message->length) + 2 != tp_len) {
1498                         dev_warn_ratelimited(&applespi->spi->dev,
1499                                              "Received corrupted packet (invalid message length %u - num-fingers %u, tp-len %zu)\n",
1500                                              le16_to_cpu(message->length),
1501                                              tp->number_of_fingers, tp_len);
1502                         goto msg_complete;
1503                 }
1504
1505                 if (tp->number_of_fingers > MAX_FINGERS) {
1506                         dev_warn_ratelimited(&applespi->spi->dev,
1507                                              "Number of reported fingers (%u) exceeds max (%u))\n",
1508                                              tp->number_of_fingers,
1509                                              MAX_FINGERS);
1510                         tp->number_of_fingers = MAX_FINGERS;
1511                 }
1512
1513                 report_tp_state(applespi, tp);
1514
1515         } else if (packet->flags == PACKET_TYPE_WRITE) {
1516                 applespi_handle_cmd_response(applespi, packet, message);
1517         }
1518
1519 msg_complete:
1520         applespi->saved_msg_len = 0;
1521
1522         applespi_msg_complete(applespi, packet->flags == PACKET_TYPE_WRITE,
1523                               true);
1524 }
1525
1526 static void applespi_async_read_complete(void *context)
1527 {
1528         struct applespi_data *applespi = context;
1529
1530         if (applespi->rd_m.status < 0) {
1531                 dev_warn(&applespi->spi->dev, "Error reading from device: %d\n",
1532                          applespi->rd_m.status);
1533                 /*
1534                  * We don't actually know if this was a pure read, or a response
1535                  * to a write. But this is a rare error condition that should
1536                  * never occur, so clearing both flags to avoid deadlock.
1537                  */
1538                 applespi_msg_complete(applespi, true, true);
1539         } else {
1540                 applespi_got_data(applespi);
1541         }
1542
1543         acpi_finish_gpe(NULL, applespi->gpe);
1544 }
1545
1546 static u32 applespi_notify(acpi_handle gpe_device, u32 gpe, void *context)
1547 {
1548         struct applespi_data *applespi = context;
1549         int sts;
1550         unsigned long flags;
1551
1552         trace_applespi_irq_received(ET_RD_IRQ, PT_READ);
1553
1554         spin_lock_irqsave(&applespi->cmd_msg_lock, flags);
1555
1556         if (!applespi->suspended) {
1557                 sts = applespi_async(applespi, &applespi->rd_m,
1558                                      applespi_async_read_complete);
1559                 if (sts)
1560                         dev_warn(&applespi->spi->dev,
1561                                  "Error queueing async read to device: %d\n",
1562                                  sts);
1563                 else
1564                         applespi->read_active = true;
1565         }
1566
1567         spin_unlock_irqrestore(&applespi->cmd_msg_lock, flags);
1568
1569         return ACPI_INTERRUPT_HANDLED;
1570 }
1571
1572 static int applespi_get_saved_bl_level(struct applespi_data *applespi)
1573 {
1574         struct efivar_entry *efivar_entry;
1575         u16 efi_data = 0;
1576         unsigned long efi_data_len;
1577         int sts;
1578
1579         efivar_entry = kmalloc(sizeof(*efivar_entry), GFP_KERNEL);
1580         if (!efivar_entry)
1581                 return -ENOMEM;
1582
1583         memcpy(efivar_entry->var.VariableName, EFI_BL_LEVEL_NAME,
1584                sizeof(EFI_BL_LEVEL_NAME));
1585         efivar_entry->var.VendorGuid = EFI_BL_LEVEL_GUID;
1586         efi_data_len = sizeof(efi_data);
1587
1588         sts = efivar_entry_get(efivar_entry, NULL, &efi_data_len, &efi_data);
1589         if (sts && sts != -ENOENT)
1590                 dev_warn(&applespi->spi->dev,
1591                          "Error getting backlight level from EFI vars: %d\n",
1592                          sts);
1593
1594         kfree(efivar_entry);
1595
1596         return sts ? sts : efi_data;
1597 }
1598
1599 static void applespi_save_bl_level(struct applespi_data *applespi,
1600                                    unsigned int level)
1601 {
1602         efi_guid_t efi_guid;
1603         u32 efi_attr;
1604         unsigned long efi_data_len;
1605         u16 efi_data;
1606         int sts;
1607
1608         /* Save keyboard backlight level */
1609         efi_guid = EFI_BL_LEVEL_GUID;
1610         efi_data = (u16)level;
1611         efi_data_len = sizeof(efi_data);
1612         efi_attr = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS |
1613                    EFI_VARIABLE_RUNTIME_ACCESS;
1614
1615         sts = efivar_entry_set_safe(EFI_BL_LEVEL_NAME, efi_guid, efi_attr, true,
1616                                     efi_data_len, &efi_data);
1617         if (sts)
1618                 dev_warn(&applespi->spi->dev,
1619                          "Error saving backlight level to EFI vars: %d\n", sts);
1620 }
1621
1622 static int applespi_probe(struct spi_device *spi)
1623 {
1624         struct applespi_data *applespi;
1625         acpi_handle spi_handle = ACPI_HANDLE(&spi->dev);
1626         acpi_status acpi_sts;
1627         int sts, i;
1628         unsigned long long gpe, usb_status;
1629
1630         /* check if the USB interface is present and enabled already */
1631         acpi_sts = acpi_evaluate_integer(spi_handle, "UIST", NULL, &usb_status);
1632         if (ACPI_SUCCESS(acpi_sts) && usb_status) {
1633                 /* let the USB driver take over instead */
1634                 dev_info(&spi->dev, "USB interface already enabled\n");
1635                 return -ENODEV;
1636         }
1637
1638         /* allocate driver data */
1639         applespi = devm_kzalloc(&spi->dev, sizeof(*applespi), GFP_KERNEL);
1640         if (!applespi)
1641                 return -ENOMEM;
1642
1643         applespi->spi = spi;
1644
1645         INIT_WORK(&applespi->work, applespi_worker);
1646
1647         /* store the driver data */
1648         spi_set_drvdata(spi, applespi);
1649
1650         /* create our buffers */
1651         applespi->tx_buffer = devm_kmalloc(&spi->dev, APPLESPI_PACKET_SIZE,
1652                                            GFP_KERNEL);
1653         applespi->tx_status = devm_kmalloc(&spi->dev, APPLESPI_STATUS_SIZE,
1654                                            GFP_KERNEL);
1655         applespi->rx_buffer = devm_kmalloc(&spi->dev, APPLESPI_PACKET_SIZE,
1656                                            GFP_KERNEL);
1657         applespi->msg_buf = devm_kmalloc_array(&spi->dev, MAX_PKTS_PER_MSG,
1658                                                APPLESPI_PACKET_SIZE,
1659                                                GFP_KERNEL);
1660
1661         if (!applespi->tx_buffer || !applespi->tx_status ||
1662             !applespi->rx_buffer || !applespi->msg_buf)
1663                 return -ENOMEM;
1664
1665         /* set up our spi messages */
1666         applespi_setup_read_txfrs(applespi);
1667         applespi_setup_write_txfrs(applespi);
1668
1669         /* cache ACPI method handles */
1670         acpi_sts = acpi_get_handle(spi_handle, "SIEN", &applespi->sien);
1671         if (ACPI_FAILURE(acpi_sts)) {
1672                 dev_err(&applespi->spi->dev,
1673                         "Failed to get SIEN ACPI method handle: %s\n",
1674                         acpi_format_exception(acpi_sts));
1675                 return -ENODEV;
1676         }
1677
1678         acpi_sts = acpi_get_handle(spi_handle, "SIST", &applespi->sist);
1679         if (ACPI_FAILURE(acpi_sts)) {
1680                 dev_err(&applespi->spi->dev,
1681                         "Failed to get SIST ACPI method handle: %s\n",
1682                         acpi_format_exception(acpi_sts));
1683                 return -ENODEV;
1684         }
1685
1686         /* switch on the SPI interface */
1687         sts = applespi_setup_spi(applespi);
1688         if (sts)
1689                 return sts;
1690
1691         sts = applespi_enable_spi(applespi);
1692         if (sts)
1693                 return sts;
1694
1695         /* setup the keyboard input dev */
1696         applespi->keyboard_input_dev = devm_input_allocate_device(&spi->dev);
1697
1698         if (!applespi->keyboard_input_dev)
1699                 return -ENOMEM;
1700
1701         applespi->keyboard_input_dev->name = "Apple SPI Keyboard";
1702         applespi->keyboard_input_dev->phys = "applespi/input0";
1703         applespi->keyboard_input_dev->dev.parent = &spi->dev;
1704         applespi->keyboard_input_dev->id.bustype = BUS_SPI;
1705
1706         applespi->keyboard_input_dev->evbit[0] =
1707                         BIT_MASK(EV_KEY) | BIT_MASK(EV_LED) | BIT_MASK(EV_REP);
1708         applespi->keyboard_input_dev->ledbit[0] = BIT_MASK(LED_CAPSL);
1709
1710         input_set_drvdata(applespi->keyboard_input_dev, applespi);
1711         applespi->keyboard_input_dev->event = applespi_event;
1712
1713         for (i = 0; i < ARRAY_SIZE(applespi_scancodes); i++)
1714                 if (applespi_scancodes[i])
1715                         input_set_capability(applespi->keyboard_input_dev,
1716                                              EV_KEY, applespi_scancodes[i]);
1717
1718         for (i = 0; i < ARRAY_SIZE(applespi_controlcodes); i++)
1719                 if (applespi_controlcodes[i])
1720                         input_set_capability(applespi->keyboard_input_dev,
1721                                              EV_KEY, applespi_controlcodes[i]);
1722
1723         for (i = 0; i < ARRAY_SIZE(applespi_fn_codes); i++)
1724                 if (applespi_fn_codes[i].to)
1725                         input_set_capability(applespi->keyboard_input_dev,
1726                                              EV_KEY, applespi_fn_codes[i].to);
1727
1728         input_set_capability(applespi->keyboard_input_dev, EV_KEY, KEY_FN);
1729
1730         sts = input_register_device(applespi->keyboard_input_dev);
1731         if (sts) {
1732                 dev_err(&applespi->spi->dev,
1733                         "Unable to register keyboard input device (%d)\n", sts);
1734                 return -ENODEV;
1735         }
1736
1737         /*
1738          * The applespi device doesn't send interrupts normally (as is described
1739          * in its DSDT), but rather seems to use ACPI GPEs.
1740          */
1741         acpi_sts = acpi_evaluate_integer(spi_handle, "_GPE", NULL, &gpe);
1742         if (ACPI_FAILURE(acpi_sts)) {
1743                 dev_err(&applespi->spi->dev,
1744                         "Failed to obtain GPE for SPI slave device: %s\n",
1745                         acpi_format_exception(acpi_sts));
1746                 return -ENODEV;
1747         }
1748         applespi->gpe = (int)gpe;
1749
1750         acpi_sts = acpi_install_gpe_handler(NULL, applespi->gpe,
1751                                             ACPI_GPE_LEVEL_TRIGGERED,
1752                                             applespi_notify, applespi);
1753         if (ACPI_FAILURE(acpi_sts)) {
1754                 dev_err(&applespi->spi->dev,
1755                         "Failed to install GPE handler for GPE %d: %s\n",
1756                         applespi->gpe, acpi_format_exception(acpi_sts));
1757                 return -ENODEV;
1758         }
1759
1760         applespi->suspended = false;
1761
1762         acpi_sts = acpi_enable_gpe(NULL, applespi->gpe);
1763         if (ACPI_FAILURE(acpi_sts)) {
1764                 dev_err(&applespi->spi->dev,
1765                         "Failed to enable GPE handler for GPE %d: %s\n",
1766                         applespi->gpe, acpi_format_exception(acpi_sts));
1767                 acpi_remove_gpe_handler(NULL, applespi->gpe, applespi_notify);
1768                 return -ENODEV;
1769         }
1770
1771         /* trigger touchpad setup */
1772         applespi_init(applespi, false);
1773
1774         /*
1775          * By default this device is not enabled for wakeup; but USB keyboards
1776          * generally are, so the expectation is that by default the keyboard
1777          * will wake the system.
1778          */
1779         device_wakeup_enable(&spi->dev);
1780
1781         /* set up keyboard-backlight */
1782         sts = applespi_get_saved_bl_level(applespi);
1783         if (sts >= 0)
1784                 applespi_set_bl_level(&applespi->backlight_info, sts);
1785
1786         applespi->backlight_info.name            = "spi::kbd_backlight";
1787         applespi->backlight_info.default_trigger = "kbd-backlight";
1788         applespi->backlight_info.brightness_set  = applespi_set_bl_level;
1789
1790         sts = devm_led_classdev_register(&spi->dev, &applespi->backlight_info);
1791         if (sts)
1792                 dev_warn(&applespi->spi->dev,
1793                          "Unable to register keyboard backlight class dev (%d)\n",
1794                          sts);
1795
1796         /* set up debugfs entries for touchpad dimensions logging */
1797         applespi->debugfs_root = debugfs_create_dir("applespi", NULL);
1798         if (IS_ERR(applespi->debugfs_root)) {
1799                 if (PTR_ERR(applespi->debugfs_root) != -ENODEV)
1800                         dev_warn(&applespi->spi->dev,
1801                                  "Error creating debugfs root entry (%ld)\n",
1802                                  PTR_ERR(applespi->debugfs_root));
1803         } else {
1804                 struct dentry *ret;
1805
1806                 ret = debugfs_create_bool("enable_tp_dim", 0600,
1807                                           applespi->debugfs_root,
1808                                           &applespi->debug_tp_dim);
1809                 if (IS_ERR(ret))
1810                         dev_dbg(&applespi->spi->dev,
1811                                 "Error creating debugfs entry enable_tp_dim (%ld)\n",
1812                                 PTR_ERR(ret));
1813
1814                 ret = debugfs_create_file("tp_dim", 0400,
1815                                           applespi->debugfs_root, applespi,
1816                                           &applespi_tp_dim_fops);
1817                 if (IS_ERR(ret))
1818                         dev_dbg(&applespi->spi->dev,
1819                                 "Error creating debugfs entry tp_dim (%ld)\n",
1820                                 PTR_ERR(ret));
1821         }
1822
1823         return 0;
1824 }
1825
1826 static void applespi_drain_writes(struct applespi_data *applespi)
1827 {
1828         unsigned long flags;
1829
1830         spin_lock_irqsave(&applespi->cmd_msg_lock, flags);
1831
1832         applespi->drain = true;
1833         wait_event_lock_irq(applespi->drain_complete, !applespi->write_active,
1834                             applespi->cmd_msg_lock);
1835
1836         spin_unlock_irqrestore(&applespi->cmd_msg_lock, flags);
1837 }
1838
1839 static void applespi_drain_reads(struct applespi_data *applespi)
1840 {
1841         unsigned long flags;
1842
1843         spin_lock_irqsave(&applespi->cmd_msg_lock, flags);
1844
1845         wait_event_lock_irq(applespi->drain_complete, !applespi->read_active,
1846                             applespi->cmd_msg_lock);
1847
1848         applespi->suspended = true;
1849
1850         spin_unlock_irqrestore(&applespi->cmd_msg_lock, flags);
1851 }
1852
1853 static int applespi_remove(struct spi_device *spi)
1854 {
1855         struct applespi_data *applespi = spi_get_drvdata(spi);
1856
1857         applespi_drain_writes(applespi);
1858
1859         acpi_disable_gpe(NULL, applespi->gpe);
1860         acpi_remove_gpe_handler(NULL, applespi->gpe, applespi_notify);
1861         device_wakeup_disable(&spi->dev);
1862
1863         applespi_drain_reads(applespi);
1864
1865         debugfs_remove_recursive(applespi->debugfs_root);
1866
1867         return 0;
1868 }
1869
1870 static void applespi_shutdown(struct spi_device *spi)
1871 {
1872         struct applespi_data *applespi = spi_get_drvdata(spi);
1873
1874         applespi_save_bl_level(applespi, applespi->have_bl_level);
1875 }
1876
1877 static int applespi_poweroff_late(struct device *dev)
1878 {
1879         struct spi_device *spi = to_spi_device(dev);
1880         struct applespi_data *applespi = spi_get_drvdata(spi);
1881
1882         applespi_save_bl_level(applespi, applespi->have_bl_level);
1883
1884         return 0;
1885 }
1886
1887 static int __maybe_unused applespi_suspend(struct device *dev)
1888 {
1889         struct spi_device *spi = to_spi_device(dev);
1890         struct applespi_data *applespi = spi_get_drvdata(spi);
1891         acpi_status acpi_sts;
1892         int sts;
1893
1894         /* turn off caps-lock - it'll stay on otherwise */
1895         sts = applespi_set_capsl_led(applespi, false);
1896         if (sts)
1897                 dev_warn(&applespi->spi->dev,
1898                          "Failed to turn off caps-lock led (%d)\n", sts);
1899
1900         applespi_drain_writes(applespi);
1901
1902         /* disable the interrupt */
1903         acpi_sts = acpi_disable_gpe(NULL, applespi->gpe);
1904         if (ACPI_FAILURE(acpi_sts))
1905                 dev_err(&applespi->spi->dev,
1906                         "Failed to disable GPE handler for GPE %d: %s\n",
1907                         applespi->gpe, acpi_format_exception(acpi_sts));
1908
1909         applespi_drain_reads(applespi);
1910
1911         return 0;
1912 }
1913
1914 static int __maybe_unused applespi_resume(struct device *dev)
1915 {
1916         struct spi_device *spi = to_spi_device(dev);
1917         struct applespi_data *applespi = spi_get_drvdata(spi);
1918         acpi_status acpi_sts;
1919         unsigned long flags;
1920
1921         /* ensure our flags and state reflect a newly resumed device */
1922         spin_lock_irqsave(&applespi->cmd_msg_lock, flags);
1923
1924         applespi->drain = false;
1925         applespi->have_cl_led_on = false;
1926         applespi->have_bl_level = 0;
1927         applespi->cmd_msg_queued = false;
1928         applespi->read_active = false;
1929         applespi->write_active = false;
1930
1931         applespi->suspended = false;
1932
1933         spin_unlock_irqrestore(&applespi->cmd_msg_lock, flags);
1934
1935         /* switch on the SPI interface */
1936         applespi_enable_spi(applespi);
1937
1938         /* re-enable the interrupt */
1939         acpi_sts = acpi_enable_gpe(NULL, applespi->gpe);
1940         if (ACPI_FAILURE(acpi_sts))
1941                 dev_err(&applespi->spi->dev,
1942                         "Failed to re-enable GPE handler for GPE %d: %s\n",
1943                         applespi->gpe, acpi_format_exception(acpi_sts));
1944
1945         /* switch the touchpad into multitouch mode */
1946         applespi_init(applespi, true);
1947
1948         return 0;
1949 }
1950
1951 static const struct acpi_device_id applespi_acpi_match[] = {
1952         { "APP000D", 0 },
1953         { }
1954 };
1955 MODULE_DEVICE_TABLE(acpi, applespi_acpi_match);
1956
1957 const struct dev_pm_ops applespi_pm_ops = {
1958         SET_SYSTEM_SLEEP_PM_OPS(applespi_suspend, applespi_resume)
1959         .poweroff_late  = applespi_poweroff_late,
1960 };
1961
1962 static struct spi_driver applespi_driver = {
1963         .driver         = {
1964                 .name                   = "applespi",
1965                 .acpi_match_table       = applespi_acpi_match,
1966                 .pm                     = &applespi_pm_ops,
1967         },
1968         .probe          = applespi_probe,
1969         .remove         = applespi_remove,
1970         .shutdown       = applespi_shutdown,
1971 };
1972
1973 module_spi_driver(applespi_driver)
1974
1975 MODULE_LICENSE("GPL v2");
1976 MODULE_DESCRIPTION("MacBook(Pro) SPI Keyboard/Touchpad driver");
1977 MODULE_AUTHOR("Federico Lorenzi");
1978 MODULE_AUTHOR("Ronald Tschalär");