OSDN Git Service

ced2a2c641cc10f2de1c933984417c0be0bd92e5
[uclinux-h8/linux.git] / drivers / input / mouse / cyapa_gen5.c
1 /*
2  * Cypress APA trackpad with I2C interface
3  *
4  * Author: Dudley Du <dudl@cypress.com>
5  *
6  * Copyright (C) 2014 Cypress Semiconductor, Inc.
7  *
8  * This file is subject to the terms and conditions of the GNU General Public
9  * License.  See the file COPYING in the main directory of this archive for
10  * more details.
11  */
12
13 #include <linux/delay.h>
14 #include <linux/i2c.h>
15 #include <linux/input.h>
16 #include <linux/input/mt.h>
17 #include <linux/mutex.h>
18 #include <linux/completion.h>
19 #include <linux/slab.h>
20 #include <linux/unaligned/access_ok.h>
21 #include <linux/crc-itu-t.h>
22 #include "cyapa.h"
23
24
25 /* Macro of Gen5 */
26 #define RECORD_EVENT_NONE        0
27 #define RECORD_EVENT_TOUCHDOWN   1
28 #define RECORD_EVENT_DISPLACE    2
29 #define RECORD_EVENT_LIFTOFF     3
30
31 #define CYAPA_TSG_FLASH_MAP_BLOCK_SIZE      0x80
32 #define CYAPA_TSG_IMG_FW_HDR_SIZE           13
33 #define CYAPA_TSG_FW_ROW_SIZE               (CYAPA_TSG_FLASH_MAP_BLOCK_SIZE)
34 #define CYAPA_TSG_IMG_START_ROW_NUM         0x002e
35 #define CYAPA_TSG_IMG_END_ROW_NUM           0x01fe
36 #define CYAPA_TSG_IMG_APP_INTEGRITY_ROW_NUM 0x01ff
37 #define CYAPA_TSG_IMG_MAX_RECORDS           (CYAPA_TSG_IMG_END_ROW_NUM - \
38                                 CYAPA_TSG_IMG_START_ROW_NUM + 1 + 1)
39 #define CYAPA_TSG_IMG_READ_SIZE             (CYAPA_TSG_FLASH_MAP_BLOCK_SIZE / 2)
40 #define CYAPA_TSG_START_OF_APPLICATION      0x1700
41 #define CYAPA_TSG_APP_INTEGRITY_SIZE        60
42 #define CYAPA_TSG_FLASH_MAP_METADATA_SIZE   60
43 #define CYAPA_TSG_BL_KEY_SIZE               8
44
45 #define CYAPA_TSG_MAX_CMD_SIZE              256
46
47 #define GEN5_BL_CMD_VERIFY_APP_INTEGRITY    0x31
48 #define GEN5_BL_CMD_GET_BL_INFO             0x38
49 #define GEN5_BL_CMD_PROGRAM_VERIFY_ROW      0x39
50 #define GEN5_BL_CMD_LAUNCH_APP              0x3b
51 #define GEN5_BL_CMD_INITIATE_BL             0x48
52
53 #define GEN5_HID_DESCRIPTOR_ADDR        0x0001
54 #define GEN5_REPORT_DESCRIPTOR_ADDR     0x0002
55 #define GEN5_INPUT_REPORT_ADDR          0x0003
56 #define GEN5_OUTPUT_REPORT_ADDR         0x0004
57 #define GEN5_CMD_DATA_ADDR              0x0006
58
59 #define GEN5_TOUCH_REPORT_HEAD_SIZE     7
60 #define GEN5_TOUCH_REPORT_MAX_SIZE      127
61 #define GEN5_BTN_REPORT_HEAD_SIZE       6
62 #define GEN5_BTN_REPORT_MAX_SIZE        14
63 #define GEN5_WAKEUP_EVENT_SIZE          4
64 #define GEN5_RAW_DATA_HEAD_SIZE         24
65
66 #define GEN5_BL_CMD_REPORT_ID           0x40
67 #define GEN5_BL_RESP_REPORT_ID          0x30
68 #define GEN5_APP_CMD_REPORT_ID          0x2f
69 #define GEN5_APP_RESP_REPORT_ID         0x1f
70
71 #define GEN5_APP_DEEP_SLEEP_REPORT_ID   0xf0
72 #define GEN5_DEEP_SLEEP_RESP_LENGTH     5
73
74 #define GEN5_CMD_GET_PARAMETER               0x05
75 #define GEN5_CMD_SET_PARAMETER               0x06
76 #define GEN5_PARAMETER_ACT_INTERVL_ID        0x4d
77 #define GEN5_PARAMETER_ACT_INTERVL_SIZE      1
78 #define GEN5_PARAMETER_ACT_LFT_INTERVL_ID    0x4f
79 #define GEN5_PARAMETER_ACT_LFT_INTERVL_SIZE  2
80 #define GEN5_PARAMETER_LP_INTRVL_ID          0x4c
81 #define GEN5_PARAMETER_LP_INTRVL_SIZE        2
82
83 #define GEN5_PARAMETER_DISABLE_PIP_REPORT    0x08
84
85 #define GEN5_POWER_STATE_ACTIVE              0x01
86 #define GEN5_POWER_STATE_LOOK_FOR_TOUCH      0x02
87 #define GEN5_POWER_STATE_READY               0x03
88 #define GEN5_POWER_STATE_IDLE                0x04
89 #define GEN5_POWER_STATE_BTN_ONLY            0x05
90 #define GEN5_POWER_STATE_OFF                 0x06
91
92 #define GEN5_DEEP_SLEEP_STATE_MASK  0x03
93 #define GEN5_DEEP_SLEEP_STATE_ON    0x00
94 #define GEN5_DEEP_SLEEP_STATE_OFF   0x01
95
96 #define GEN5_DEEP_SLEEP_OPCODE      0x08
97 #define GEN5_DEEP_SLEEP_OPCODE_MASK 0x0f
98
99 #define GEN5_POWER_READY_MAX_INTRVL_TIME  50   /* Unit: ms */
100 #define GEN5_POWER_IDLE_MAX_INTRVL_TIME   250  /* Unit: ms */
101
102 #define GEN5_CMD_REPORT_ID_OFFSET       4
103
104 #define GEN5_RESP_REPORT_ID_OFFSET      2
105 #define GEN5_RESP_RSVD_OFFSET           3
106 #define     GEN5_RESP_RSVD_KEY          0x00
107 #define GEN5_RESP_BL_SOP_OFFSET         4
108 #define     GEN5_SOP_KEY                0x01  /* Start of Packet */
109 #define     GEN5_EOP_KEY                0x17  /* End of Packet */
110 #define GEN5_RESP_APP_CMD_OFFSET        4
111 #define     GET_GEN5_CMD_CODE(reg)      ((reg) & 0x7f)
112
113 #define VALID_CMD_RESP_HEADER(resp, cmd)                                    \
114         (((resp)[GEN5_RESP_REPORT_ID_OFFSET] == GEN5_APP_RESP_REPORT_ID) && \
115         ((resp)[GEN5_RESP_RSVD_OFFSET] == GEN5_RESP_RSVD_KEY) &&            \
116         (GET_GEN5_CMD_CODE((resp)[GEN5_RESP_APP_CMD_OFFSET]) == (cmd)))
117
118 #define GEN5_MIN_BL_CMD_LENGTH           13
119 #define GEN5_MIN_BL_RESP_LENGTH          11
120 #define GEN5_MIN_APP_CMD_LENGTH          7
121 #define GEN5_MIN_APP_RESP_LENGTH         5
122 #define GEN5_UNSUPPORTED_CMD_RESP_LENGTH 6
123
124 #define GEN5_RESP_LENGTH_OFFSET  0x00
125 #define GEN5_RESP_LENGTH_SIZE    2
126
127 #define GEN5_HID_DESCRIPTOR_SIZE      32
128 #define GEN5_BL_HID_REPORT_ID         0xff
129 #define GEN5_APP_HID_REPORT_ID        0xf7
130 #define GEN5_BL_MAX_OUTPUT_LENGTH     0x0100
131 #define GEN5_APP_MAX_OUTPUT_LENGTH    0x00fe
132
133 #define GEN5_BL_REPORT_DESCRIPTOR_SIZE            0x1d
134 #define GEN5_BL_REPORT_DESCRIPTOR_ID              0xfe
135 #define GEN5_APP_REPORT_DESCRIPTOR_SIZE           0xee
136 #define GEN5_APP_CONTRACT_REPORT_DESCRIPTOR_SIZE  0xfa
137 #define GEN5_APP_REPORT_DESCRIPTOR_ID             0xf6
138
139 #define GEN5_TOUCH_REPORT_ID         0x01
140 #define GEN5_BTN_REPORT_ID           0x03
141 #define GEN5_WAKEUP_EVENT_REPORT_ID  0x04
142 #define GEN5_OLD_PUSH_BTN_REPORT_ID  0x05
143 #define GEN5_PUSH_BTN_REPORT_ID      0x06
144
145 #define GEN5_CMD_COMPLETE_SUCCESS(status) ((status) == 0x00)
146
147 #define GEN5_BL_INITIATE_RESP_LEN            11
148 #define GEN5_BL_FAIL_EXIT_RESP_LEN           11
149 #define GEN5_BL_FAIL_EXIT_STATUS_CODE        0x0c
150 #define GEN5_BL_VERIFY_INTEGRITY_RESP_LEN    12
151 #define GEN5_BL_INTEGRITY_CHEKC_PASS         0x00
152 #define GEN5_BL_BLOCK_WRITE_RESP_LEN         11
153 #define GEN5_BL_READ_APP_INFO_RESP_LEN       31
154 #define GEN5_CMD_CALIBRATE                   0x28
155 #define CYAPA_SENSING_MODE_MUTUAL_CAP_FINE   0x00
156 #define CYAPA_SENSING_MODE_SELF_CAP          0x02
157
158 #define GEN5_CMD_RETRIEVE_DATA_STRUCTURE     0x24
159 #define GEN5_RETRIEVE_MUTUAL_PWC_DATA        0x00
160 #define GEN5_RETRIEVE_SELF_CAP_PWC_DATA      0x01
161
162 #define GEN5_RETRIEVE_DATA_ELEMENT_SIZE_MASK 0x07
163
164 #define GEN5_CMD_EXECUTE_PANEL_SCAN          0x2a
165 #define GEN5_CMD_RETRIEVE_PANEL_SCAN         0x2b
166 #define GEN5_PANEL_SCAN_MUTUAL_RAW_DATA      0x00
167 #define GEN5_PANEL_SCAN_MUTUAL_BASELINE      0x01
168 #define GEN5_PANEL_SCAN_MUTUAL_DIFFCOUNT     0x02
169 #define GEN5_PANEL_SCAN_SELF_RAW_DATA        0x03
170 #define GEN5_PANEL_SCAN_SELF_BASELINE        0x04
171 #define GEN5_PANEL_SCAN_SELF_DIFFCOUNT       0x05
172
173 /* The offset only valid for reterive PWC and panel scan commands */
174 #define GEN5_RESP_DATA_STRUCTURE_OFFSET      10
175 #define GEN5_PWC_DATA_ELEMENT_SIZE_MASK      0x07
176
177 #define GEN5_NUMBER_OF_TOUCH_OFFSET  5
178 #define GEN5_NUMBER_OF_TOUCH_MASK    0x1f
179 #define GEN5_BUTTONS_OFFSET          5
180 #define GEN5_BUTTONS_MASK            0x0f
181 #define GEN5_GET_EVENT_ID(reg)       (((reg) >> 5) & 0x03)
182 #define GEN5_GET_TOUCH_ID(reg)       ((reg) & 0x1f)
183
184 #define GEN5_PRODUCT_FAMILY_MASK        0xf000
185 #define GEN5_PRODUCT_FAMILY_TRACKPAD    0x1000
186
187 #define TSG_INVALID_CMD   0xff
188
189 struct cyapa_gen5_touch_record {
190         /*
191          * Bit 7 - 3: reserved
192          * Bit 2 - 0: touch type;
193          *            0 : standard finger;
194          *            1 - 15 : reserved.
195          */
196         u8 touch_type;
197
198         /*
199          * Bit 7: indicates touch liftoff status.
200          *              0 : touch is currently on the panel.
201          *              1 : touch record indicates a liftoff.
202          * Bit 6 - 5: indicates an event associated with this touch instance
203          *              0 : no event
204          *              1 : touchdown
205          *              2 : significant displacement (> active distance)
206          *              3 : liftoff (record reports last known coordinates)
207          * Bit 4 - 0: An arbitrary ID tag associated with a finger
208          *              to allow tracking a touch as it moves around the panel.
209          */
210         u8 touch_tip_event_id;
211
212         /* Bit 7 - 0 of X-axis coordinate of the touch in pixel. */
213         u8 x_lo;
214
215         /* Bit 15 - 8 of X-axis coordinate of the touch in pixel. */
216         u8 x_hi;
217
218         /* Bit 7 - 0 of Y-axis coordinate of the touch in pixel. */
219         u8 y_lo;
220
221         /* Bit 15 - 8 of Y-axis coordinate of the touch in pixel. */
222         u8 y_hi;
223
224         /* Touch intensity in counts, pressure value. */
225         u8 z;
226
227         /*
228          * The length of the major axis of the ellipse of contact between
229          * the finger and the panel (ABS_MT_TOUCH_MAJOR).
230          */
231         u8 major_axis_len;
232
233         /*
234          * The length of the minor axis of the ellipse of contact between
235          * the finger and the panel (ABS_MT_TOUCH_MINOR).
236          */
237         u8 minor_axis_len;
238
239         /*
240          * The length of the major axis of the approaching tool.
241          * (ABS_MT_WIDTH_MAJOR)
242          */
243         u8 major_tool_len;
244
245         /*
246          * The length of the minor axis of the approaching tool.
247          * (ABS_MT_WIDTH_MINOR)
248          */
249         u8 minor_tool_len;
250
251         /*
252          * The angle between the panel vertical axis and
253          * the major axis of the contact ellipse. This value is an 8-bit
254          * signed integer. The range is -127 to +127 (corresponding to
255          * -90 degree and +90 degree respectively).
256          * The positive direction is clockwise from the vertical axis.
257          * If the ellipse of contact degenerates into a circle,
258          * orientation is reported as 0.
259          */
260         u8 orientation;
261 } __packed;
262
263 struct cyapa_gen5_report_data {
264         u8 report_head[GEN5_TOUCH_REPORT_HEAD_SIZE];
265         struct cyapa_gen5_touch_record touch_records[10];
266 } __packed;
267
268 struct cyapa_tsg_bin_image_head {
269         u8 head_size;  /* Unit: bytes, including itself. */
270         u8 ttda_driver_major_version;  /* Reserved as 0. */
271         u8 ttda_driver_minor_version;  /* Reserved as 0. */
272         u8 fw_major_version;
273         u8 fw_minor_version;
274         u8 fw_revision_control_number[8];
275 } __packed;
276
277 struct cyapa_tsg_bin_image_data_record {
278         u8 flash_array_id;
279         __be16 row_number;
280         /* The number of bytes of flash data contained in this record. */
281         __be16 record_len;
282         /* The flash program data. */
283         u8 record_data[CYAPA_TSG_FW_ROW_SIZE];
284 } __packed;
285
286 struct cyapa_tsg_bin_image {
287         struct cyapa_tsg_bin_image_head image_head;
288         struct cyapa_tsg_bin_image_data_record records[0];
289 } __packed;
290
291 struct gen5_bl_packet_start {
292         u8 sop;  /* Start of packet, must be 01h */
293         u8 cmd_code;
294         __le16 data_length;  /* Size of data parameter start from data[0] */
295 } __packed;
296
297 struct gen5_bl_packet_end {
298         __le16 crc;
299         u8 eop;  /* End of packet, must be 17h */
300 } __packed;
301
302 struct gen5_bl_cmd_head {
303         __le16 addr;   /* Output report register address, must be 0004h */
304         /* Size of packet not including output report register address */
305         __le16 length;
306         u8 report_id;  /* Bootloader output report id, must be 40h */
307         u8 rsvd;  /* Reserved, must be 0 */
308         struct gen5_bl_packet_start packet_start;
309         u8 data[0];  /* Command data variable based on commands */
310 } __packed;
311
312 /* Initiate bootload command data structure. */
313 struct gen5_bl_initiate_cmd_data {
314         /* Key must be "A5h 01h 02h 03h FFh FEh FDh 5Ah" */
315         u8 key[CYAPA_TSG_BL_KEY_SIZE];
316         u8 metadata_raw_parameter[CYAPA_TSG_FLASH_MAP_METADATA_SIZE];
317         __le16 metadata_crc;
318 } __packed;
319
320 struct gen5_bl_metadata_row_params {
321         __le16 size;
322         __le16 maximun_size;
323         __le32 app_start;
324         __le16 app_len;
325         __le16 app_crc;
326         __le32 app_entry;
327         __le32 upgrade_start;
328         __le16 upgrade_len;
329         __le16 entry_row_crc;
330         u8 padding[36];  /* Padding data must be 0 */
331         __le16 metadata_crc;  /* CRC starts at offset of 60 */
332 } __packed;
333
334 /* Bootload program and verify row command data structure */
335 struct gen5_bl_flash_row_head {
336         u8 flash_array_id;
337         __le16 flash_row_id;
338         u8 flash_data[0];
339 } __packed;
340
341 struct gen5_app_cmd_head {
342         __le16 addr;   /* Output report register address, must be 0004h */
343         /* Size of packet not including output report register address */
344         __le16 length;
345         u8 report_id;  /* Application output report id, must be 2Fh */
346         u8 rsvd;  /* Reserved, must be 0 */
347         /*
348          * Bit 7: reserved, must be 0.
349          * Bit 6-0: command code.
350          */
351         u8 cmd_code;
352         u8 parameter_data[0];  /* Parameter data variable based on cmd_code */
353 } __packed;
354
355 /* Applicaton get/set parameter command data structure */
356 struct gen5_app_set_parameter_data {
357         u8 parameter_id;
358         u8 parameter_size;
359         __le32 value;
360 } __packed;
361
362 struct gen5_app_get_parameter_data {
363         u8 parameter_id;
364 } __packed;
365
366 struct gen5_retrieve_panel_scan_data {
367         __le16 read_offset;
368         __le16 read_elements;
369         u8 data_id;
370 } __packed;
371
372 /* Variables to record latest gen5 trackpad power states. */
373 #define GEN5_DEV_SET_PWR_STATE(cyapa, s)        ((cyapa)->dev_pwr_mode = (s))
374 #define GEN5_DEV_GET_PWR_STATE(cyapa)           ((cyapa)->dev_pwr_mode)
375 #define GEN5_DEV_SET_SLEEP_TIME(cyapa, t)       ((cyapa)->dev_sleep_time = (t))
376 #define GEN5_DEV_GET_SLEEP_TIME(cyapa)          ((cyapa)->dev_sleep_time)
377 #define GEN5_DEV_UNINIT_SLEEP_TIME(cyapa)       \
378                 (((cyapa)->dev_sleep_time) == UNINIT_SLEEP_TIME)
379
380
381 static u8 cyapa_gen5_bl_cmd_key[] = { 0xa5, 0x01, 0x02, 0x03,
382         0xff, 0xfe, 0xfd, 0x5a };
383
384 static int cyapa_gen5_initialize(struct cyapa *cyapa)
385 {
386         struct cyapa_gen5_cmd_states *gen5_pip = &cyapa->cmd_states.gen5;
387
388         init_completion(&gen5_pip->cmd_ready);
389         atomic_set(&gen5_pip->cmd_issued, 0);
390         mutex_init(&gen5_pip->cmd_lock);
391
392         gen5_pip->resp_sort_func = NULL;
393         gen5_pip->in_progress_cmd = TSG_INVALID_CMD;
394         gen5_pip->resp_data = NULL;
395         gen5_pip->resp_len = NULL;
396
397         cyapa->dev_pwr_mode = UNINIT_PWR_MODE;
398         cyapa->dev_sleep_time = UNINIT_SLEEP_TIME;
399
400         return 0;
401 }
402
403 /* Return negative errno, or else the number of bytes read. */
404 static ssize_t cyapa_i2c_pip_read(struct cyapa *cyapa, u8 *buf, size_t size)
405 {
406         int ret;
407
408         if (size == 0)
409                 return 0;
410
411         if (!buf || size > CYAPA_REG_MAP_SIZE)
412                 return -EINVAL;
413
414         ret = i2c_master_recv(cyapa->client, buf, size);
415
416         if (ret != size)
417                 return (ret < 0) ? ret : -EIO;
418
419         return size;
420 }
421
422 /**
423  * Return a negative errno code else zero on success.
424  */
425 static ssize_t cyapa_i2c_pip_write(struct cyapa *cyapa, u8 *buf, size_t size)
426 {
427         int ret;
428
429         if (!buf || !size)
430                 return -EINVAL;
431
432         ret = i2c_master_send(cyapa->client, buf, size);
433
434         if (ret != size)
435                 return (ret < 0) ? ret : -EIO;
436
437         return 0;
438 }
439
440 /**
441  * This function is aimed to dump all not read data in Gen5 trackpad
442  * before send any command, otherwise, the interrupt line will be blocked.
443  */
444 static int cyapa_empty_pip_output_data(struct cyapa *cyapa,
445                 u8 *buf, int *len, cb_sort func)
446 {
447         struct cyapa_gen5_cmd_states *gen5_pip = &cyapa->cmd_states.gen5;
448         int length;
449         int report_count;
450         int empty_count;
451         int buf_len;
452         int error;
453
454         buf_len = 0;
455         if (len) {
456                 buf_len = (*len < CYAPA_REG_MAP_SIZE) ?
457                                 *len : CYAPA_REG_MAP_SIZE;
458                 *len = 0;
459         }
460
461         report_count = 8;  /* max 7 pending data before command response data */
462         empty_count = 0;
463         do {
464                 /*
465                  * Depending on testing in cyapa driver, there are max 5 "02 00"
466                  * packets between two valid buffered data report in firmware.
467                  * So in order to dump all buffered data out and
468                  * make interrupt line release for reassert again,
469                  * we must set the empty_count check value bigger than 5 to
470                  * make it work. Otherwise, in some situation,
471                  * the interrupt line may unable to reactive again,
472                  * which will cause trackpad device unable to
473                  * report data any more.
474                  * for example, it may happen in EFT and ESD testing.
475                  */
476                 if (empty_count > 5)
477                         return 0;
478
479                 error = cyapa_i2c_pip_read(cyapa, gen5_pip->empty_buf,
480                                 GEN5_RESP_LENGTH_SIZE);
481                 if (error < 0)
482                         return error;
483
484                 length = get_unaligned_le16(gen5_pip->empty_buf);
485                 if (length == GEN5_RESP_LENGTH_SIZE) {
486                         empty_count++;
487                         continue;
488                 } else if (length > CYAPA_REG_MAP_SIZE) {
489                         /* Should not happen */
490                         return -EINVAL;
491                 } else if (length == 0) {
492                         /* Application or bootloader launch data polled out. */
493                         length = GEN5_RESP_LENGTH_SIZE;
494                         if (buf && buf_len && func &&
495                                 func(cyapa, gen5_pip->empty_buf, length)) {
496                                 length = min(buf_len, length);
497                                 memcpy(buf, gen5_pip->empty_buf, length);
498                                 *len = length;
499                                 /* Response found, success. */
500                                 return 0;
501                         }
502                         continue;
503                 }
504
505                 error = cyapa_i2c_pip_read(cyapa, gen5_pip->empty_buf, length);
506                 if (error < 0)
507                         return error;
508
509                 report_count--;
510                 empty_count = 0;
511                 length = get_unaligned_le16(gen5_pip->empty_buf);
512                 if (length <= GEN5_RESP_LENGTH_SIZE) {
513                         empty_count++;
514                 } else if (buf && buf_len && func &&
515                         func(cyapa, gen5_pip->empty_buf, length)) {
516                         length = min(buf_len, length);
517                         memcpy(buf, gen5_pip->empty_buf, length);
518                         *len = length;
519                         /* Response found, success. */
520                         return 0;
521                 }
522
523                 error = -EINVAL;
524         } while (report_count);
525
526         return error;
527 }
528
529 static int cyapa_do_i2c_pip_cmd_irq_sync(
530                 struct cyapa *cyapa,
531                 u8 *cmd, size_t cmd_len,
532                 unsigned long timeout)
533 {
534         struct cyapa_gen5_cmd_states *gen5_pip = &cyapa->cmd_states.gen5;
535         int error;
536
537         /* Wait for interrupt to set ready completion */
538         init_completion(&gen5_pip->cmd_ready);
539
540         atomic_inc(&gen5_pip->cmd_issued);
541         error = cyapa_i2c_pip_write(cyapa, cmd, cmd_len);
542         if (error) {
543                 atomic_dec(&gen5_pip->cmd_issued);
544                 return (error < 0) ? error : -EIO;
545         }
546
547         /* Wait for interrupt to indicate command is completed. */
548         timeout = wait_for_completion_timeout(&gen5_pip->cmd_ready,
549                                 msecs_to_jiffies(timeout));
550         if (timeout == 0) {
551                 atomic_dec(&gen5_pip->cmd_issued);
552                 return -ETIMEDOUT;
553         }
554
555         return 0;
556 }
557
558 static int cyapa_do_i2c_pip_cmd_polling(
559                 struct cyapa *cyapa,
560                 u8 *cmd, size_t cmd_len,
561                 u8 *resp_data, int *resp_len,
562                 unsigned long timeout,
563                 cb_sort func)
564 {
565         struct cyapa_gen5_cmd_states *gen5_pip = &cyapa->cmd_states.gen5;
566         int tries;
567         int length;
568         int error;
569
570         atomic_inc(&gen5_pip->cmd_issued);
571         error = cyapa_i2c_pip_write(cyapa, cmd, cmd_len);
572         if (error) {
573                 atomic_dec(&gen5_pip->cmd_issued);
574                 return error < 0 ? error : -EIO;
575         }
576
577         length = resp_len ? *resp_len : 0;
578         if (resp_data && resp_len && length != 0 && func) {
579                 tries = timeout / 5;
580                 do {
581                         usleep_range(3000, 5000);
582                         *resp_len = length;
583                         error = cyapa_empty_pip_output_data(cyapa,
584                                         resp_data, resp_len, func);
585                         if (error || *resp_len == 0)
586                                 continue;
587                         else
588                                 break;
589                 } while (--tries > 0);
590                 if ((error || *resp_len == 0) || tries <= 0)
591                         error = error ? error : -ETIMEDOUT;
592         }
593
594         atomic_dec(&gen5_pip->cmd_issued);
595         return error;
596 }
597
598 static int cyapa_i2c_pip_cmd_irq_sync(
599                 struct cyapa *cyapa,
600                 u8 *cmd, int cmd_len,
601                 u8 *resp_data, int *resp_len,
602                 unsigned long timeout,
603                 cb_sort func,
604                 bool irq_mode)
605 {
606         struct cyapa_gen5_cmd_states *gen5_pip = &cyapa->cmd_states.gen5;
607         int error;
608
609         if (!cmd || !cmd_len)
610                 return -EINVAL;
611
612         /* Commands must be serialized. */
613         error = mutex_lock_interruptible(&gen5_pip->cmd_lock);
614         if (error)
615                 return error;
616
617         gen5_pip->resp_sort_func = func;
618         gen5_pip->resp_data = resp_data;
619         gen5_pip->resp_len = resp_len;
620
621         if (cmd_len >= GEN5_MIN_APP_CMD_LENGTH &&
622                         cmd[4] == GEN5_APP_CMD_REPORT_ID) {
623                 /* Application command */
624                 gen5_pip->in_progress_cmd = cmd[6] & 0x7f;
625         } else if (cmd_len >= GEN5_MIN_BL_CMD_LENGTH &&
626                         cmd[4] == GEN5_BL_CMD_REPORT_ID) {
627                 /* Bootloader command */
628                 gen5_pip->in_progress_cmd = cmd[7];
629         }
630
631         /* Send command data, wait and read output response data's length. */
632         if (irq_mode) {
633                 gen5_pip->is_irq_mode = true;
634                 error = cyapa_do_i2c_pip_cmd_irq_sync(cyapa, cmd, cmd_len,
635                                                         timeout);
636                 if (error == -ETIMEDOUT && resp_data &&
637                                 resp_len && *resp_len != 0 && func) {
638                         /*
639                          * For some old version, there was no interrupt for
640                          * the command response data, so need to poll here
641                          * to try to get the response data.
642                          */
643                         error = cyapa_empty_pip_output_data(cyapa,
644                                         resp_data, resp_len, func);
645                         if (error || *resp_len == 0)
646                                 error = error ? error : -ETIMEDOUT;
647                 }
648         } else {
649                 gen5_pip->is_irq_mode = false;
650                 error = cyapa_do_i2c_pip_cmd_polling(cyapa, cmd, cmd_len,
651                                 resp_data, resp_len, timeout, func);
652         }
653
654         gen5_pip->resp_sort_func = NULL;
655         gen5_pip->resp_data = NULL;
656         gen5_pip->resp_len = NULL;
657         gen5_pip->in_progress_cmd = TSG_INVALID_CMD;
658
659         mutex_unlock(&gen5_pip->cmd_lock);
660         return error;
661 }
662
663 static bool cyapa_gen5_sort_tsg_pip_bl_resp_data(struct cyapa *cyapa,
664                 u8 *data, int len)
665 {
666         if (!data || len < GEN5_MIN_BL_RESP_LENGTH)
667                 return false;
668
669         /* Bootloader input report id 30h */
670         if (data[GEN5_RESP_REPORT_ID_OFFSET] == GEN5_BL_RESP_REPORT_ID &&
671                         data[GEN5_RESP_RSVD_OFFSET] == GEN5_RESP_RSVD_KEY &&
672                         data[GEN5_RESP_BL_SOP_OFFSET] == GEN5_SOP_KEY)
673                 return true;
674
675         return false;
676 }
677
678 static bool cyapa_gen5_sort_tsg_pip_app_resp_data(struct cyapa *cyapa,
679                 u8 *data, int len)
680 {
681         struct cyapa_gen5_cmd_states *gen5_pip = &cyapa->cmd_states.gen5;
682         int resp_len;
683
684         if (!data || len < GEN5_MIN_APP_RESP_LENGTH)
685                 return false;
686
687         if (data[GEN5_RESP_REPORT_ID_OFFSET] == GEN5_APP_RESP_REPORT_ID &&
688                         data[GEN5_RESP_RSVD_OFFSET] == GEN5_RESP_RSVD_KEY) {
689                 resp_len = get_unaligned_le16(&data[GEN5_RESP_LENGTH_OFFSET]);
690                 if (GET_GEN5_CMD_CODE(data[GEN5_RESP_APP_CMD_OFFSET]) == 0x00 &&
691                         resp_len == GEN5_UNSUPPORTED_CMD_RESP_LENGTH &&
692                         data[5] == gen5_pip->in_progress_cmd) {
693                         /* Unsupported command code */
694                         return false;
695                 } else if (GET_GEN5_CMD_CODE(data[GEN5_RESP_APP_CMD_OFFSET]) ==
696                                 gen5_pip->in_progress_cmd) {
697                         /* Correct command response received */
698                         return true;
699                 }
700         }
701
702         return false;
703 }
704
705 static bool cyapa_gen5_sort_application_launch_data(struct cyapa *cyapa,
706                 u8 *buf, int len)
707 {
708         if (buf == NULL || len < GEN5_RESP_LENGTH_SIZE)
709                 return false;
710
711         /*
712          * After reset or power on, trackpad device always sets to 0x00 0x00
713          * to indicate a reset or power on event.
714          */
715         if (buf[0] == 0 && buf[1] == 0)
716                 return true;
717
718         return false;
719 }
720
721 static bool cyapa_gen5_sort_hid_descriptor_data(struct cyapa *cyapa,
722                 u8 *buf, int len)
723 {
724         int resp_len;
725         int max_output_len;
726
727         /* Check hid descriptor. */
728         if (len != GEN5_HID_DESCRIPTOR_SIZE)
729                 return false;
730
731         resp_len = get_unaligned_le16(&buf[GEN5_RESP_LENGTH_OFFSET]);
732         max_output_len = get_unaligned_le16(&buf[16]);
733         if (resp_len == GEN5_HID_DESCRIPTOR_SIZE) {
734                 if (buf[GEN5_RESP_REPORT_ID_OFFSET] == GEN5_BL_HID_REPORT_ID &&
735                                 max_output_len == GEN5_BL_MAX_OUTPUT_LENGTH) {
736                         /* BL mode HID Descriptor */
737                         return true;
738                 } else if ((buf[GEN5_RESP_REPORT_ID_OFFSET] ==
739                                 GEN5_APP_HID_REPORT_ID) &&
740                                 max_output_len == GEN5_APP_MAX_OUTPUT_LENGTH) {
741                         /* APP mode HID Descriptor */
742                         return true;
743                 }
744         }
745
746         return false;
747 }
748
749 static bool cyapa_gen5_sort_deep_sleep_data(struct cyapa *cyapa,
750                 u8 *buf, int len)
751 {
752         if (len == GEN5_DEEP_SLEEP_RESP_LENGTH &&
753                 buf[GEN5_RESP_REPORT_ID_OFFSET] ==
754                         GEN5_APP_DEEP_SLEEP_REPORT_ID &&
755                 (buf[4] & GEN5_DEEP_SLEEP_OPCODE_MASK) ==
756                         GEN5_DEEP_SLEEP_OPCODE)
757                 return true;
758         return false;
759 }
760
761 static int gen5_idle_state_parse(struct cyapa *cyapa)
762 {
763         u8 resp_data[GEN5_HID_DESCRIPTOR_SIZE];
764         int max_output_len;
765         int length;
766         u8 cmd[2];
767         int ret;
768         int error;
769
770         /*
771          * Dump all buffered data firstly for the situation
772          * when the trackpad is just power on the cyapa go here.
773          */
774         cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
775
776         memset(resp_data, 0, sizeof(resp_data));
777         ret = cyapa_i2c_pip_read(cyapa, resp_data, 3);
778         if (ret != 3)
779                 return ret < 0 ? ret : -EIO;
780
781         length = get_unaligned_le16(&resp_data[GEN5_RESP_LENGTH_OFFSET]);
782         if (length == GEN5_RESP_LENGTH_SIZE) {
783                 /* Normal state of Gen5 with no data to respose */
784                 cyapa->gen = CYAPA_GEN5;
785
786                 cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
787
788                 /* Read description from trackpad device */
789                 cmd[0] = 0x01;
790                 cmd[1] = 0x00;
791                 length = GEN5_HID_DESCRIPTOR_SIZE;
792                 error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
793                                 cmd, GEN5_RESP_LENGTH_SIZE,
794                                 resp_data, &length,
795                                 300,
796                                 cyapa_gen5_sort_hid_descriptor_data,
797                                 false);
798                 if (error)
799                         return error;
800
801                 length = get_unaligned_le16(
802                                 &resp_data[GEN5_RESP_LENGTH_OFFSET]);
803                 max_output_len = get_unaligned_le16(&resp_data[16]);
804                 if ((length == GEN5_HID_DESCRIPTOR_SIZE ||
805                                 length == GEN5_RESP_LENGTH_SIZE) &&
806                         (resp_data[GEN5_RESP_REPORT_ID_OFFSET] ==
807                                 GEN5_BL_HID_REPORT_ID) &&
808                         max_output_len == GEN5_BL_MAX_OUTPUT_LENGTH) {
809                         /* BL mode HID Description read */
810                         cyapa->state = CYAPA_STATE_GEN5_BL;
811                 } else if ((length == GEN5_HID_DESCRIPTOR_SIZE ||
812                                 length == GEN5_RESP_LENGTH_SIZE) &&
813                         (resp_data[GEN5_RESP_REPORT_ID_OFFSET] ==
814                                 GEN5_APP_HID_REPORT_ID) &&
815                         max_output_len == GEN5_APP_MAX_OUTPUT_LENGTH) {
816                         /* APP mode HID Description read */
817                         cyapa->state = CYAPA_STATE_GEN5_APP;
818                 } else {
819                         /* Should not happen!!! */
820                         cyapa->state = CYAPA_STATE_NO_DEVICE;
821                 }
822         }
823
824         return 0;
825 }
826
827 static int gen5_hid_description_header_parse(struct cyapa *cyapa, u8 *reg_data)
828 {
829         int length;
830         u8 resp_data[32];
831         int max_output_len;
832         int ret;
833
834         /* 0x20 0x00 0xF7 is Gen5 Application HID Description Header;
835          * 0x20 0x00 0xFF is Gen5 Booloader HID Description Header.
836          *
837          * Must read HID Description content through out,
838          * otherwise Gen5 trackpad cannot response next command
839          * or report any touch or button data.
840          */
841         ret = cyapa_i2c_pip_read(cyapa, resp_data,
842                         GEN5_HID_DESCRIPTOR_SIZE);
843         if (ret != GEN5_HID_DESCRIPTOR_SIZE)
844                 return ret < 0 ? ret : -EIO;
845         length = get_unaligned_le16(&resp_data[GEN5_RESP_LENGTH_OFFSET]);
846         max_output_len = get_unaligned_le16(&resp_data[16]);
847         if (length == GEN5_RESP_LENGTH_SIZE) {
848                 if (reg_data[GEN5_RESP_REPORT_ID_OFFSET] ==
849                                 GEN5_BL_HID_REPORT_ID) {
850                         /*
851                          * BL mode HID Description has been previously
852                          * read out.
853                          */
854                         cyapa->gen = CYAPA_GEN5;
855                         cyapa->state = CYAPA_STATE_GEN5_BL;
856                 } else {
857                         /*
858                          * APP mode HID Description has been previously
859                          * read out.
860                          */
861                         cyapa->gen = CYAPA_GEN5;
862                         cyapa->state = CYAPA_STATE_GEN5_APP;
863                 }
864         } else if (length == GEN5_HID_DESCRIPTOR_SIZE &&
865                         resp_data[2] == GEN5_BL_HID_REPORT_ID &&
866                         max_output_len == GEN5_BL_MAX_OUTPUT_LENGTH) {
867                 /* BL mode HID Description read. */
868                 cyapa->gen = CYAPA_GEN5;
869                 cyapa->state = CYAPA_STATE_GEN5_BL;
870         } else if (length == GEN5_HID_DESCRIPTOR_SIZE &&
871                         (resp_data[GEN5_RESP_REPORT_ID_OFFSET] ==
872                                 GEN5_APP_HID_REPORT_ID) &&
873                         max_output_len == GEN5_APP_MAX_OUTPUT_LENGTH) {
874                 /* APP mode HID Description read. */
875                 cyapa->gen = CYAPA_GEN5;
876                 cyapa->state = CYAPA_STATE_GEN5_APP;
877         } else {
878                 /* Should not happen!!! */
879                 cyapa->state = CYAPA_STATE_NO_DEVICE;
880         }
881
882         return 0;
883 }
884
885 static int gen5_report_data_header_parse(struct cyapa *cyapa, u8 *reg_data)
886 {
887         int length;
888
889         length = get_unaligned_le16(&reg_data[GEN5_RESP_LENGTH_OFFSET]);
890         switch (reg_data[GEN5_RESP_REPORT_ID_OFFSET]) {
891         case GEN5_TOUCH_REPORT_ID:
892                 if (length < GEN5_TOUCH_REPORT_HEAD_SIZE ||
893                         length > GEN5_TOUCH_REPORT_MAX_SIZE)
894                         return -EINVAL;
895                 break;
896         case GEN5_BTN_REPORT_ID:
897         case GEN5_OLD_PUSH_BTN_REPORT_ID:
898         case GEN5_PUSH_BTN_REPORT_ID:
899                 if (length < GEN5_BTN_REPORT_HEAD_SIZE ||
900                         length > GEN5_BTN_REPORT_MAX_SIZE)
901                         return -EINVAL;
902                 break;
903         case GEN5_WAKEUP_EVENT_REPORT_ID:
904                 if (length != GEN5_WAKEUP_EVENT_SIZE)
905                         return -EINVAL;
906                 break;
907         default:
908                 return -EINVAL;
909         }
910
911         cyapa->gen = CYAPA_GEN5;
912         cyapa->state = CYAPA_STATE_GEN5_APP;
913         return 0;
914 }
915
916 static int gen5_cmd_resp_header_parse(struct cyapa *cyapa, u8 *reg_data)
917 {
918         struct cyapa_gen5_cmd_states *gen5_pip = &cyapa->cmd_states.gen5;
919         int length;
920         int ret;
921
922         /*
923          * Must read report data through out,
924          * otherwise Gen5 trackpad cannot response next command
925          * or report any touch or button data.
926          */
927         length = get_unaligned_le16(&reg_data[GEN5_RESP_LENGTH_OFFSET]);
928         ret = cyapa_i2c_pip_read(cyapa, gen5_pip->empty_buf, length);
929         if (ret != length)
930                 return ret < 0 ? ret : -EIO;
931
932         if (length == GEN5_RESP_LENGTH_SIZE) {
933                 /* Previous command has read the data through out. */
934                 if (reg_data[GEN5_RESP_REPORT_ID_OFFSET] ==
935                                 GEN5_BL_RESP_REPORT_ID) {
936                         /* Gen5 BL command response data detected */
937                         cyapa->gen = CYAPA_GEN5;
938                         cyapa->state = CYAPA_STATE_GEN5_BL;
939                 } else {
940                         /* Gen5 APP command response data detected */
941                         cyapa->gen = CYAPA_GEN5;
942                         cyapa->state = CYAPA_STATE_GEN5_APP;
943                 }
944         } else if ((gen5_pip->empty_buf[GEN5_RESP_REPORT_ID_OFFSET] ==
945                                 GEN5_BL_RESP_REPORT_ID) &&
946                         (gen5_pip->empty_buf[GEN5_RESP_RSVD_OFFSET] ==
947                                 GEN5_RESP_RSVD_KEY) &&
948                         (gen5_pip->empty_buf[GEN5_RESP_BL_SOP_OFFSET] ==
949                                 GEN5_SOP_KEY) &&
950                         (gen5_pip->empty_buf[length - 1] ==
951                                 GEN5_EOP_KEY)) {
952                 /* Gen5 BL command response data detected */
953                 cyapa->gen = CYAPA_GEN5;
954                 cyapa->state = CYAPA_STATE_GEN5_BL;
955         } else if (gen5_pip->empty_buf[GEN5_RESP_REPORT_ID_OFFSET] ==
956                                 GEN5_APP_RESP_REPORT_ID &&
957                         gen5_pip->empty_buf[GEN5_RESP_RSVD_OFFSET] ==
958                                 GEN5_RESP_RSVD_KEY) {
959                 /* Gen5 APP command response data detected */
960                 cyapa->gen = CYAPA_GEN5;
961                 cyapa->state = CYAPA_STATE_GEN5_APP;
962         } else {
963                 /* Should not happen!!! */
964                 cyapa->state = CYAPA_STATE_NO_DEVICE;
965         }
966
967         return 0;
968 }
969
970 static int cyapa_gen5_state_parse(struct cyapa *cyapa, u8 *reg_data, int len)
971 {
972         int length;
973
974         if (!reg_data || len < 3)
975                 return -EINVAL;
976
977         cyapa->state = CYAPA_STATE_NO_DEVICE;
978
979         /* Parse based on Gen5 characteristic registers and bits */
980         length = get_unaligned_le16(&reg_data[GEN5_RESP_LENGTH_OFFSET]);
981         if (length == 0 || length == GEN5_RESP_LENGTH_SIZE) {
982                 gen5_idle_state_parse(cyapa);
983         } else if (length == GEN5_HID_DESCRIPTOR_SIZE &&
984                         (reg_data[2] == GEN5_BL_HID_REPORT_ID ||
985                                 reg_data[2] == GEN5_APP_HID_REPORT_ID)) {
986                 gen5_hid_description_header_parse(cyapa, reg_data);
987         } else if ((length == GEN5_APP_REPORT_DESCRIPTOR_SIZE ||
988                         length == GEN5_APP_CONTRACT_REPORT_DESCRIPTOR_SIZE) &&
989                         reg_data[2] == GEN5_APP_REPORT_DESCRIPTOR_ID) {
990                 /* 0xEE 0x00 0xF6 is Gen5 APP report description header. */
991                 cyapa->gen = CYAPA_GEN5;
992                 cyapa->state = CYAPA_STATE_GEN5_APP;
993         } else if (length == GEN5_BL_REPORT_DESCRIPTOR_SIZE &&
994                         reg_data[2] == GEN5_BL_REPORT_DESCRIPTOR_ID) {
995                 /* 0x1D 0x00 0xFE is Gen5 BL report descriptior header. */
996                 cyapa->gen = CYAPA_GEN5;
997                 cyapa->state = CYAPA_STATE_GEN5_BL;
998         } else if (reg_data[2] == GEN5_TOUCH_REPORT_ID ||
999                         reg_data[2] == GEN5_BTN_REPORT_ID ||
1000                         reg_data[2] == GEN5_OLD_PUSH_BTN_REPORT_ID ||
1001                         reg_data[2] == GEN5_PUSH_BTN_REPORT_ID ||
1002                         reg_data[2] == GEN5_WAKEUP_EVENT_REPORT_ID) {
1003                 gen5_report_data_header_parse(cyapa, reg_data);
1004         } else if (reg_data[2] == GEN5_BL_RESP_REPORT_ID ||
1005                         reg_data[2] == GEN5_APP_RESP_REPORT_ID) {
1006                 gen5_cmd_resp_header_parse(cyapa, reg_data);
1007         }
1008
1009         if (cyapa->gen == CYAPA_GEN5) {
1010                 /*
1011                  * Must read the content (e.g.: report description and so on)
1012                  * from trackpad device throughout. Otherwise,
1013                  * Gen5 trackpad cannot response to next command or
1014                  * report any touch or button data later.
1015                  */
1016                 cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
1017
1018                 if (cyapa->state == CYAPA_STATE_GEN5_APP ||
1019                         cyapa->state == CYAPA_STATE_GEN5_BL)
1020                         return 0;
1021         }
1022
1023         return -EAGAIN;
1024 }
1025
1026 static int cyapa_gen5_bl_initiate(struct cyapa *cyapa,
1027                 const struct firmware *fw)
1028 {
1029         struct cyapa_tsg_bin_image *image;
1030         struct gen5_bl_cmd_head *bl_cmd_head;
1031         struct gen5_bl_packet_start *bl_packet_start;
1032         struct gen5_bl_initiate_cmd_data *cmd_data;
1033         struct gen5_bl_packet_end *bl_packet_end;
1034         u8 cmd[CYAPA_TSG_MAX_CMD_SIZE];
1035         int cmd_len;
1036         u16 cmd_data_len;
1037         u16 cmd_crc = 0;
1038         u16 meta_data_crc = 0;
1039         u8 resp_data[11];
1040         int resp_len;
1041         int records_num;
1042         u8 *data;
1043         int error;
1044
1045         /* Try to dump all buffered report data before any send command. */
1046         cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
1047
1048         memset(cmd, 0, CYAPA_TSG_MAX_CMD_SIZE);
1049         bl_cmd_head = (struct gen5_bl_cmd_head *)cmd;
1050         cmd_data_len = CYAPA_TSG_BL_KEY_SIZE + CYAPA_TSG_FLASH_MAP_BLOCK_SIZE;
1051         cmd_len = sizeof(struct gen5_bl_cmd_head) + cmd_data_len +
1052                   sizeof(struct gen5_bl_packet_end);
1053
1054         put_unaligned_le16(GEN5_OUTPUT_REPORT_ADDR, &bl_cmd_head->addr);
1055         put_unaligned_le16(cmd_len - 2, &bl_cmd_head->length);
1056         bl_cmd_head->report_id = GEN5_BL_CMD_REPORT_ID;
1057
1058         bl_packet_start = &bl_cmd_head->packet_start;
1059         bl_packet_start->sop = GEN5_SOP_KEY;
1060         bl_packet_start->cmd_code = GEN5_BL_CMD_INITIATE_BL;
1061         /* 8 key bytes and 128 bytes block size */
1062         put_unaligned_le16(cmd_data_len, &bl_packet_start->data_length);
1063
1064         cmd_data = (struct gen5_bl_initiate_cmd_data *)bl_cmd_head->data;
1065         memcpy(cmd_data->key, cyapa_gen5_bl_cmd_key, CYAPA_TSG_BL_KEY_SIZE);
1066
1067         /* Copy 60 bytes Meta Data Row Parameters */
1068         image = (struct cyapa_tsg_bin_image *)fw->data;
1069         records_num = (fw->size - sizeof(struct cyapa_tsg_bin_image_head)) /
1070                                 sizeof(struct cyapa_tsg_bin_image_data_record);
1071         /* APP_INTEGRITY row is always the last row block */
1072         data = image->records[records_num - 1].record_data;
1073         memcpy(cmd_data->metadata_raw_parameter, data,
1074                 CYAPA_TSG_FLASH_MAP_METADATA_SIZE);
1075
1076         meta_data_crc = crc_itu_t(0xffff, cmd_data->metadata_raw_parameter,
1077                                 CYAPA_TSG_FLASH_MAP_METADATA_SIZE);
1078         put_unaligned_le16(meta_data_crc, &cmd_data->metadata_crc);
1079
1080         bl_packet_end = (struct gen5_bl_packet_end *)(bl_cmd_head->data +
1081                                 cmd_data_len);
1082         cmd_crc = crc_itu_t(0xffff, (u8 *)bl_packet_start,
1083                 sizeof(struct gen5_bl_packet_start) + cmd_data_len);
1084         put_unaligned_le16(cmd_crc, &bl_packet_end->crc);
1085         bl_packet_end->eop = GEN5_EOP_KEY;
1086
1087         resp_len = sizeof(resp_data);
1088         error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
1089                         cmd, cmd_len,
1090                         resp_data, &resp_len, 12000,
1091                         cyapa_gen5_sort_tsg_pip_bl_resp_data, true);
1092         if (error || resp_len != GEN5_BL_INITIATE_RESP_LEN ||
1093                         resp_data[2] != GEN5_BL_RESP_REPORT_ID ||
1094                         !GEN5_CMD_COMPLETE_SUCCESS(resp_data[5]))
1095                 return error ? error : -EAGAIN;
1096
1097         return 0;
1098 }
1099
1100 static bool cyapa_gen5_sort_bl_exit_data(struct cyapa *cyapa, u8 *buf, int len)
1101 {
1102         if (buf == NULL || len < GEN5_RESP_LENGTH_SIZE)
1103                 return false;
1104
1105         if (buf[0] == 0 && buf[1] == 0)
1106                 return true;
1107
1108         /* Exit bootloader failed for some reason. */
1109         if (len == GEN5_BL_FAIL_EXIT_RESP_LEN &&
1110                         buf[GEN5_RESP_REPORT_ID_OFFSET] ==
1111                                 GEN5_BL_RESP_REPORT_ID &&
1112                         buf[GEN5_RESP_RSVD_OFFSET] == GEN5_RESP_RSVD_KEY &&
1113                         buf[GEN5_RESP_BL_SOP_OFFSET] == GEN5_SOP_KEY &&
1114                         buf[10] == GEN5_EOP_KEY)
1115                 return true;
1116
1117         return false;
1118 }
1119
1120 static int cyapa_gen5_bl_exit(struct cyapa *cyapa)
1121 {
1122
1123         u8 bl_gen5_bl_exit[] = { 0x04, 0x00,
1124                 0x0B, 0x00, 0x40, 0x00, 0x01, 0x3b, 0x00, 0x00,
1125                 0x20, 0xc7, 0x17
1126         };
1127         u8 resp_data[11];
1128         int resp_len;
1129         int error;
1130
1131         resp_len = sizeof(resp_data);
1132         error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
1133                         bl_gen5_bl_exit, sizeof(bl_gen5_bl_exit),
1134                         resp_data, &resp_len,
1135                         5000, cyapa_gen5_sort_bl_exit_data, false);
1136         if (error)
1137                 return error;
1138
1139         if (resp_len == GEN5_BL_FAIL_EXIT_RESP_LEN ||
1140                         resp_data[GEN5_RESP_REPORT_ID_OFFSET] ==
1141                                 GEN5_BL_RESP_REPORT_ID)
1142                 return -EAGAIN;
1143
1144         if (resp_data[0] == 0x00 && resp_data[1] == 0x00)
1145                 return 0;
1146
1147         return -ENODEV;
1148 }
1149
1150 static int cyapa_gen5_bl_enter(struct cyapa *cyapa)
1151 {
1152         u8 cmd[] = { 0x04, 0x00, 0x05, 0x00, 0x2F, 0x00, 0x01 };
1153         u8 resp_data[2];
1154         int resp_len;
1155         int error;
1156
1157         error = cyapa_poll_state(cyapa, 500);
1158         if (error < 0)
1159                 return error;
1160         if (cyapa->gen != CYAPA_GEN5)
1161                 return -EINVAL;
1162
1163         /* Already in Gen5 BL. Skipping exit. */
1164         if (cyapa->state == CYAPA_STATE_GEN5_BL)
1165                 return 0;
1166
1167         if (cyapa->state != CYAPA_STATE_GEN5_APP)
1168                 return -EAGAIN;
1169
1170         /* Try to dump all buffered report data before any send command. */
1171         cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
1172
1173         /*
1174          * Send bootloader enter command to trackpad device,
1175          * after enter bootloader, the response data is two bytes of 0x00 0x00.
1176          */
1177         resp_len = sizeof(resp_data);
1178         memset(resp_data, 0, resp_len);
1179         error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
1180                         cmd, sizeof(cmd),
1181                         resp_data, &resp_len,
1182                         5000, cyapa_gen5_sort_application_launch_data,
1183                         true);
1184         if (error || resp_data[0] != 0x00 || resp_data[1] != 0x00)
1185                 return error < 0 ? error : -EAGAIN;
1186
1187         cyapa->operational = false;
1188         cyapa->state = CYAPA_STATE_GEN5_BL;
1189         return 0;
1190 }
1191
1192 static int cyapa_gen5_check_fw(struct cyapa *cyapa, const struct firmware *fw)
1193 {
1194         struct device *dev = &cyapa->client->dev;
1195         struct gen5_bl_metadata_row_params metadata;
1196         struct cyapa_tsg_bin_image *image;
1197         int flash_records_count;
1198         u16 app_crc = 0;
1199         u16 app_integrity_crc = 0;
1200         u16 row_num;
1201         u8 *data;
1202         int record_index;
1203         int i;
1204
1205         image = (struct cyapa_tsg_bin_image *)fw->data;
1206         flash_records_count = (fw->size -
1207                         sizeof(struct cyapa_tsg_bin_image_head)) /
1208                         sizeof(struct cyapa_tsg_bin_image_data_record);
1209
1210         /* APP_INTEGRITY row is always the last row block,
1211          * and the row id must be 0x01ff */
1212         row_num = get_unaligned_be16(
1213                         &image->records[flash_records_count - 1].row_number);
1214         if (image->records[flash_records_count - 1].flash_array_id != 0x00 &&
1215                         row_num != 0x01ff) {
1216                 dev_err(dev, "%s: invalid app_integrity data.\n", __func__);
1217                 return -EINVAL;
1218         }
1219         data = image->records[flash_records_count - 1].record_data;
1220
1221         metadata.app_start = get_unaligned_le32(&data[4]);
1222         metadata.app_len = get_unaligned_le16(&data[8]);
1223         metadata.app_crc = get_unaligned_le16(&data[10]);
1224         metadata.upgrade_start = get_unaligned_le32(&data[16]);
1225         metadata.upgrade_len  = get_unaligned_le16(&data[20]);
1226         metadata.metadata_crc = get_unaligned_le16(&data[60]);
1227
1228         if ((metadata.app_start + metadata.app_len +
1229                 metadata.upgrade_start + metadata.upgrade_len) %
1230                         CYAPA_TSG_FW_ROW_SIZE) {
1231                 dev_err(dev, "%s: invalid image alignment.\n", __func__);
1232                 return -EINVAL;
1233         }
1234
1235         /* Verify app_integrity crc */
1236         app_integrity_crc = crc_itu_t(0xffff, data,
1237                         CYAPA_TSG_APP_INTEGRITY_SIZE);
1238         if (app_integrity_crc != metadata.metadata_crc) {
1239                 dev_err(dev, "%s: invalid app_integrity crc.\n", __func__);
1240                 return -EINVAL;
1241         }
1242
1243         /*
1244          * Verify application image CRC
1245          */
1246         record_index = metadata.app_start / CYAPA_TSG_FW_ROW_SIZE -
1247                                 CYAPA_TSG_IMG_START_ROW_NUM;
1248         data = (u8 *)&image->records[record_index].record_data;
1249         app_crc = crc_itu_t(0xffff, data, CYAPA_TSG_FW_ROW_SIZE);
1250         for (i = 1; i < (metadata.app_len / CYAPA_TSG_FW_ROW_SIZE); i++) {
1251                 data = (u8 *)&image->records[++record_index].record_data;
1252                 app_crc = crc_itu_t(app_crc, data, CYAPA_TSG_FW_ROW_SIZE);
1253         }
1254
1255         if (app_crc != metadata.app_crc) {
1256                 dev_err(dev, "%s: invalid firmware app crc check.\n", __func__);
1257                 return -EINVAL;
1258         }
1259
1260         return 0;
1261 }
1262
1263 static int cyapa_gen5_write_fw_block(struct cyapa *cyapa,
1264                 struct cyapa_tsg_bin_image_data_record *flash_record)
1265 {
1266         struct gen5_bl_cmd_head *bl_cmd_head;
1267         struct gen5_bl_packet_start *bl_packet_start;
1268         struct gen5_bl_flash_row_head *flash_row_head;
1269         struct gen5_bl_packet_end *bl_packet_end;
1270         u8 cmd[CYAPA_TSG_MAX_CMD_SIZE];
1271         u16 cmd_len;
1272         u8 flash_array_id;
1273         u16 flash_row_id;
1274         u16 record_len;
1275         u8 *record_data;
1276         u16 data_len;
1277         u16 crc;
1278         u8 resp_data[11];
1279         int resp_len;
1280         int error;
1281
1282         flash_array_id = flash_record->flash_array_id;
1283         flash_row_id = get_unaligned_be16(&flash_record->row_number);
1284         record_len = get_unaligned_be16(&flash_record->record_len);
1285         record_data = flash_record->record_data;
1286
1287         memset(cmd, 0, CYAPA_TSG_MAX_CMD_SIZE);
1288         bl_cmd_head = (struct gen5_bl_cmd_head *)cmd;
1289         bl_packet_start = &bl_cmd_head->packet_start;
1290         cmd_len = sizeof(struct gen5_bl_cmd_head) +
1291                   sizeof(struct gen5_bl_flash_row_head) +
1292                   CYAPA_TSG_FLASH_MAP_BLOCK_SIZE +
1293                   sizeof(struct gen5_bl_packet_end);
1294
1295         put_unaligned_le16(GEN5_OUTPUT_REPORT_ADDR, &bl_cmd_head->addr);
1296         /* Don't include 2 bytes register address */
1297         put_unaligned_le16(cmd_len - 2, &bl_cmd_head->length);
1298         bl_cmd_head->report_id = GEN5_BL_CMD_REPORT_ID;
1299         bl_packet_start->sop = GEN5_SOP_KEY;
1300         bl_packet_start->cmd_code = GEN5_BL_CMD_PROGRAM_VERIFY_ROW;
1301
1302         /* 1 (Flash Array ID) + 2 (Flash Row ID) + 128 (flash data) */
1303         data_len = sizeof(struct gen5_bl_flash_row_head) + record_len;
1304         put_unaligned_le16(data_len, &bl_packet_start->data_length);
1305
1306         flash_row_head = (struct gen5_bl_flash_row_head *)bl_cmd_head->data;
1307         flash_row_head->flash_array_id = flash_array_id;
1308         put_unaligned_le16(flash_row_id, &flash_row_head->flash_row_id);
1309         memcpy(flash_row_head->flash_data, record_data, record_len);
1310
1311         bl_packet_end = (struct gen5_bl_packet_end *)(bl_cmd_head->data +
1312                                                       data_len);
1313         crc = crc_itu_t(0xffff, (u8 *)bl_packet_start,
1314                 sizeof(struct gen5_bl_packet_start) + data_len);
1315         put_unaligned_le16(crc, &bl_packet_end->crc);
1316         bl_packet_end->eop = GEN5_EOP_KEY;
1317
1318         resp_len = sizeof(resp_data);
1319         error = cyapa_i2c_pip_cmd_irq_sync(cyapa, cmd, cmd_len,
1320                         resp_data, &resp_len,
1321                         500, cyapa_gen5_sort_tsg_pip_bl_resp_data, true);
1322         if (error || resp_len != GEN5_BL_BLOCK_WRITE_RESP_LEN ||
1323                         resp_data[2] != GEN5_BL_RESP_REPORT_ID ||
1324                         !GEN5_CMD_COMPLETE_SUCCESS(resp_data[5]))
1325                 return error < 0 ? error : -EAGAIN;
1326
1327         return 0;
1328 }
1329
1330 static int cyapa_gen5_do_fw_update(struct cyapa *cyapa,
1331                 const struct firmware *fw)
1332 {
1333         struct device *dev = &cyapa->client->dev;
1334         struct cyapa_tsg_bin_image_data_record *flash_record;
1335         struct cyapa_tsg_bin_image *image =
1336                 (struct cyapa_tsg_bin_image *)fw->data;
1337         int flash_records_count;
1338         int i;
1339         int error;
1340
1341         cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
1342
1343         flash_records_count =
1344                 (fw->size - sizeof(struct cyapa_tsg_bin_image_head)) /
1345                         sizeof(struct cyapa_tsg_bin_image_data_record);
1346         /*
1347          * The last flash row 0x01ff has been written through bl_initiate
1348          * command, so DO NOT write flash 0x01ff to trackpad device.
1349          */
1350         for (i = 0; i < (flash_records_count - 1); i++) {
1351                 flash_record = &image->records[i];
1352                 error = cyapa_gen5_write_fw_block(cyapa, flash_record);
1353                 if (error) {
1354                         dev_err(dev, "%s: Gen5 FW update aborted: %d\n",
1355                                 __func__, error);
1356                         return error;
1357                 }
1358         }
1359
1360         return 0;
1361 }
1362
1363 static int cyapa_gen5_change_power_state(struct cyapa *cyapa, u8 power_state)
1364 {
1365         u8 cmd[8] = { 0x04, 0x00, 0x06, 0x00, 0x2f, 0x00, 0x08, 0x01 };
1366         u8 resp_data[6];
1367         int resp_len;
1368         int error;
1369
1370         cmd[7] = power_state;
1371         resp_len = sizeof(resp_data);
1372         error = cyapa_i2c_pip_cmd_irq_sync(cyapa, cmd, sizeof(cmd),
1373                         resp_data, &resp_len,
1374                         500, cyapa_gen5_sort_tsg_pip_app_resp_data, false);
1375         if (error || !VALID_CMD_RESP_HEADER(resp_data, 0x08) ||
1376                         !GEN5_CMD_COMPLETE_SUCCESS(resp_data[5]))
1377                 return error < 0 ? error : -EINVAL;
1378
1379         return 0;
1380 }
1381
1382 static int cyapa_gen5_set_interval_time(struct cyapa *cyapa,
1383                 u8 parameter_id, u16 interval_time)
1384 {
1385         struct gen5_app_cmd_head *app_cmd_head;
1386         struct gen5_app_set_parameter_data *parameter_data;
1387         u8 cmd[CYAPA_TSG_MAX_CMD_SIZE];
1388         int cmd_len;
1389         u8 resp_data[7];
1390         int resp_len;
1391         u8 parameter_size;
1392         int error;
1393
1394         memset(cmd, 0, CYAPA_TSG_MAX_CMD_SIZE);
1395         app_cmd_head = (struct gen5_app_cmd_head *)cmd;
1396         parameter_data = (struct gen5_app_set_parameter_data *)
1397                          app_cmd_head->parameter_data;
1398         cmd_len = sizeof(struct gen5_app_cmd_head) +
1399                   sizeof(struct gen5_app_set_parameter_data);
1400
1401         switch (parameter_id) {
1402         case GEN5_PARAMETER_ACT_INTERVL_ID:
1403                 parameter_size = GEN5_PARAMETER_ACT_INTERVL_SIZE;
1404                 break;
1405         case GEN5_PARAMETER_ACT_LFT_INTERVL_ID:
1406                 parameter_size = GEN5_PARAMETER_ACT_LFT_INTERVL_SIZE;
1407                 break;
1408         case GEN5_PARAMETER_LP_INTRVL_ID:
1409                 parameter_size = GEN5_PARAMETER_LP_INTRVL_SIZE;
1410                 break;
1411         default:
1412                 return -EINVAL;
1413         }
1414
1415         put_unaligned_le16(GEN5_OUTPUT_REPORT_ADDR, &app_cmd_head->addr);
1416         /*
1417          * Don't include unused parameter value bytes and
1418          * 2 bytes register address.
1419          */
1420         put_unaligned_le16(cmd_len - (4 - parameter_size) - 2,
1421                            &app_cmd_head->length);
1422         app_cmd_head->report_id = GEN5_APP_CMD_REPORT_ID;
1423         app_cmd_head->cmd_code = GEN5_CMD_SET_PARAMETER;
1424         parameter_data->parameter_id = parameter_id;
1425         parameter_data->parameter_size = parameter_size;
1426         put_unaligned_le32((u32)interval_time, &parameter_data->value);
1427         resp_len = sizeof(resp_data);
1428         error = cyapa_i2c_pip_cmd_irq_sync(cyapa, cmd, cmd_len,
1429                         resp_data, &resp_len,
1430                         500, cyapa_gen5_sort_tsg_pip_app_resp_data, false);
1431         if (error || resp_data[5] != parameter_id ||
1432                 resp_data[6] != parameter_size ||
1433                 !VALID_CMD_RESP_HEADER(resp_data, GEN5_CMD_SET_PARAMETER))
1434                 return error < 0 ? error : -EINVAL;
1435
1436         return 0;
1437 }
1438
1439 static int cyapa_gen5_get_interval_time(struct cyapa *cyapa,
1440                 u8 parameter_id, u16 *interval_time)
1441 {
1442         struct gen5_app_cmd_head *app_cmd_head;
1443         struct gen5_app_get_parameter_data *parameter_data;
1444         u8 cmd[CYAPA_TSG_MAX_CMD_SIZE];
1445         int cmd_len;
1446         u8 resp_data[11];
1447         int resp_len;
1448         u8 parameter_size;
1449         u16 mask, i;
1450         int error;
1451
1452         memset(cmd, 0, CYAPA_TSG_MAX_CMD_SIZE);
1453         app_cmd_head = (struct gen5_app_cmd_head *)cmd;
1454         parameter_data = (struct gen5_app_get_parameter_data *)
1455                          app_cmd_head->parameter_data;
1456         cmd_len = sizeof(struct gen5_app_cmd_head) +
1457                   sizeof(struct gen5_app_get_parameter_data);
1458
1459         *interval_time = 0;
1460         switch (parameter_id) {
1461         case GEN5_PARAMETER_ACT_INTERVL_ID:
1462                 parameter_size = GEN5_PARAMETER_ACT_INTERVL_SIZE;
1463                 break;
1464         case GEN5_PARAMETER_ACT_LFT_INTERVL_ID:
1465                 parameter_size = GEN5_PARAMETER_ACT_LFT_INTERVL_SIZE;
1466                 break;
1467         case GEN5_PARAMETER_LP_INTRVL_ID:
1468                 parameter_size = GEN5_PARAMETER_LP_INTRVL_SIZE;
1469                 break;
1470         default:
1471                 return -EINVAL;
1472         }
1473
1474         put_unaligned_le16(GEN5_HID_DESCRIPTOR_ADDR, &app_cmd_head->addr);
1475         /* Don't include 2 bytes register address */
1476         put_unaligned_le16(cmd_len - 2, &app_cmd_head->length);
1477         app_cmd_head->report_id = GEN5_APP_CMD_REPORT_ID;
1478         app_cmd_head->cmd_code = GEN5_CMD_GET_PARAMETER;
1479         parameter_data->parameter_id = parameter_id;
1480
1481         resp_len = sizeof(resp_data);
1482         error = cyapa_i2c_pip_cmd_irq_sync(cyapa, cmd, cmd_len,
1483                         resp_data, &resp_len,
1484                         500, cyapa_gen5_sort_tsg_pip_app_resp_data, false);
1485         if (error || resp_data[5] != parameter_id || resp_data[6] == 0 ||
1486                 !VALID_CMD_RESP_HEADER(resp_data, GEN5_CMD_GET_PARAMETER))
1487                 return error < 0 ? error : -EINVAL;
1488
1489         mask = 0;
1490         for (i = 0; i < parameter_size; i++)
1491                 mask |= (0xff << (i * 8));
1492         *interval_time = get_unaligned_le16(&resp_data[7]) & mask;
1493
1494         return 0;
1495 }
1496
1497 static int cyapa_gen5_disable_pip_report(struct cyapa *cyapa)
1498 {
1499         struct gen5_app_cmd_head *app_cmd_head;
1500         u8 cmd[10];
1501         u8 resp_data[7];
1502         int resp_len;
1503         int error;
1504
1505         memset(cmd, 0, sizeof(cmd));
1506         app_cmd_head = (struct gen5_app_cmd_head *)cmd;
1507
1508         put_unaligned_le16(GEN5_HID_DESCRIPTOR_ADDR, &app_cmd_head->addr);
1509         put_unaligned_le16(sizeof(cmd) - 2, &app_cmd_head->length);
1510         app_cmd_head->report_id = GEN5_APP_CMD_REPORT_ID;
1511         app_cmd_head->cmd_code = GEN5_CMD_SET_PARAMETER;
1512         app_cmd_head->parameter_data[0] = GEN5_PARAMETER_DISABLE_PIP_REPORT;
1513         app_cmd_head->parameter_data[1] = 0x01;
1514         app_cmd_head->parameter_data[2] = 0x01;
1515         resp_len = sizeof(resp_data);
1516         error = cyapa_i2c_pip_cmd_irq_sync(cyapa, cmd, sizeof(cmd),
1517                         resp_data, &resp_len,
1518                         500, cyapa_gen5_sort_tsg_pip_app_resp_data, false);
1519         if (error || resp_data[5] != GEN5_PARAMETER_DISABLE_PIP_REPORT ||
1520                 !VALID_CMD_RESP_HEADER(resp_data, GEN5_CMD_SET_PARAMETER) ||
1521                 resp_data[6] != 0x01)
1522                 return error < 0 ? error : -EINVAL;
1523
1524         return 0;
1525 }
1526
1527 static int cyapa_gen5_deep_sleep(struct cyapa *cyapa, u8 state)
1528 {
1529         u8 cmd[] = { 0x05, 0x00, 0x00, 0x08};
1530         u8 resp_data[5];
1531         int resp_len;
1532         int error;
1533
1534         cmd[2] = state & GEN5_DEEP_SLEEP_STATE_MASK;
1535         resp_len = sizeof(resp_data);
1536         error = cyapa_i2c_pip_cmd_irq_sync(cyapa, cmd, sizeof(cmd),
1537                         resp_data, &resp_len,
1538                         500, cyapa_gen5_sort_deep_sleep_data, false);
1539         if (error || ((resp_data[3] & GEN5_DEEP_SLEEP_STATE_MASK) != state))
1540                 return -EINVAL;
1541
1542         return 0;
1543 }
1544
1545 static int cyapa_gen5_set_power_mode(struct cyapa *cyapa,
1546                 u8 power_mode, u16 sleep_time)
1547 {
1548         struct device *dev = &cyapa->client->dev;
1549         u8 power_state;
1550         int error;
1551
1552         if (cyapa->state != CYAPA_STATE_GEN5_APP)
1553                 return 0;
1554
1555         /* Dump all the report data before do power mode commmands. */
1556         cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
1557
1558         if (GEN5_DEV_GET_PWR_STATE(cyapa) == UNINIT_PWR_MODE) {
1559                 /*
1560                  * Assume TP in deep sleep mode when driver is loaded,
1561                  * avoid driver unload and reload command IO issue caused by TP
1562                  * has been set into deep sleep mode when unloading.
1563                  */
1564                 GEN5_DEV_SET_PWR_STATE(cyapa, PWR_MODE_OFF);
1565         }
1566
1567         if (GEN5_DEV_UNINIT_SLEEP_TIME(cyapa) &&
1568                         GEN5_DEV_GET_PWR_STATE(cyapa) != PWR_MODE_OFF)
1569                 if (cyapa_gen5_get_interval_time(cyapa,
1570                                 GEN5_PARAMETER_LP_INTRVL_ID,
1571                                 &cyapa->dev_sleep_time) != 0)
1572                         GEN5_DEV_SET_SLEEP_TIME(cyapa, UNINIT_SLEEP_TIME);
1573
1574         if (GEN5_DEV_GET_PWR_STATE(cyapa) == power_mode) {
1575                 if (power_mode == PWR_MODE_OFF ||
1576                         power_mode == PWR_MODE_FULL_ACTIVE ||
1577                         power_mode == PWR_MODE_BTN_ONLY ||
1578                         GEN5_DEV_GET_SLEEP_TIME(cyapa) == sleep_time) {
1579                         /* Has in correct power mode state, early return. */
1580                         return 0;
1581                 }
1582         }
1583
1584         if (power_mode == PWR_MODE_OFF) {
1585                 error = cyapa_gen5_deep_sleep(cyapa, GEN5_DEEP_SLEEP_STATE_OFF);
1586                 if (error) {
1587                         dev_err(dev, "enter deep sleep fail: %d\n", error);
1588                         return error;
1589                 }
1590
1591                 GEN5_DEV_SET_PWR_STATE(cyapa, PWR_MODE_OFF);
1592                 return 0;
1593         }
1594
1595         /*
1596          * When trackpad in power off mode, it cannot change to other power
1597          * state directly, must be wake up from sleep firstly, then
1598          * continue to do next power sate change.
1599          */
1600         if (GEN5_DEV_GET_PWR_STATE(cyapa) == PWR_MODE_OFF) {
1601                 error = cyapa_gen5_deep_sleep(cyapa, GEN5_DEEP_SLEEP_STATE_ON);
1602                 if (error) {
1603                         dev_err(dev, "deep sleep wake fail: %d\n", error);
1604                         return error;
1605                 }
1606         }
1607
1608         if (power_mode == PWR_MODE_FULL_ACTIVE) {
1609                 error = cyapa_gen5_change_power_state(cyapa,
1610                                 GEN5_POWER_STATE_ACTIVE);
1611                 if (error) {
1612                         dev_err(dev, "change to active fail: %d\n", error);
1613                         return error;
1614                 }
1615
1616                 GEN5_DEV_SET_PWR_STATE(cyapa, PWR_MODE_FULL_ACTIVE);
1617         } else if (power_mode == PWR_MODE_BTN_ONLY) {
1618                 error = cyapa_gen5_change_power_state(cyapa,
1619                                 GEN5_POWER_STATE_BTN_ONLY);
1620                 if (error) {
1621                         dev_err(dev, "fail to button only mode: %d\n", error);
1622                         return error;
1623                 }
1624
1625                 GEN5_DEV_SET_PWR_STATE(cyapa, PWR_MODE_BTN_ONLY);
1626         } else {
1627                 /*
1628                  * Continue to change power mode even failed to set
1629                  * interval time, it won't affect the power mode change.
1630                  * except the sleep interval time is not correct.
1631                  */
1632                 if (GEN5_DEV_UNINIT_SLEEP_TIME(cyapa) ||
1633                                 sleep_time != GEN5_DEV_GET_SLEEP_TIME(cyapa))
1634                         if (cyapa_gen5_set_interval_time(cyapa,
1635                                         GEN5_PARAMETER_LP_INTRVL_ID,
1636                                         sleep_time) == 0)
1637                                 GEN5_DEV_SET_SLEEP_TIME(cyapa, sleep_time);
1638
1639                 if (sleep_time <= GEN5_POWER_READY_MAX_INTRVL_TIME)
1640                         power_state = GEN5_POWER_STATE_READY;
1641                 else
1642                         power_state = GEN5_POWER_STATE_IDLE;
1643                 error = cyapa_gen5_change_power_state(cyapa, power_state);
1644                 if (error) {
1645                         dev_err(dev, "set power state to 0x%02x failed: %d\n",
1646                                 power_state, error);
1647                         return error;
1648                 }
1649
1650                 /*
1651                  * Disable pip report for a little time, firmware will
1652                  * re-enable it automatically. It's used to fix the issue
1653                  * that trackpad unable to report signal to wake system up
1654                  * in the special situation that system is in suspending, and
1655                  * at the same time, user touch trackpad to wake system up.
1656                  * This function can avoid the data to be buffured when system
1657                  * is suspending which may cause interrput line unable to be
1658                  * asserted again.
1659                  */
1660                 cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
1661                 cyapa_gen5_disable_pip_report(cyapa);
1662
1663                 GEN5_DEV_SET_PWR_STATE(cyapa,
1664                         cyapa_sleep_time_to_pwr_cmd(sleep_time));
1665         }
1666
1667         return 0;
1668 }
1669
1670 static int cyapa_gen5_resume_scanning(struct cyapa *cyapa)
1671 {
1672         u8 cmd[] = { 0x04, 0x00, 0x05, 0x00, 0x2f, 0x00, 0x04 };
1673         u8 resp_data[6];
1674         int resp_len;
1675         int error;
1676
1677         /* Try to dump all buffered data before doing command. */
1678         cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
1679
1680         resp_len = sizeof(resp_data);
1681         error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
1682                         cmd, sizeof(cmd),
1683                         resp_data, &resp_len,
1684                         500, cyapa_gen5_sort_tsg_pip_app_resp_data, true);
1685         if (error || !VALID_CMD_RESP_HEADER(resp_data, 0x04))
1686                 return -EINVAL;
1687
1688         /* Try to dump all buffered data when resuming scanning. */
1689         cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
1690
1691         return 0;
1692 }
1693
1694 static int cyapa_gen5_suspend_scanning(struct cyapa *cyapa)
1695 {
1696         u8 cmd[] = { 0x04, 0x00, 0x05, 0x00, 0x2f, 0x00, 0x03 };
1697         u8 resp_data[6];
1698         int resp_len;
1699         int error;
1700
1701         /* Try to dump all buffered data before doing command. */
1702         cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
1703
1704         resp_len = sizeof(resp_data);
1705         error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
1706                         cmd, sizeof(cmd),
1707                         resp_data, &resp_len,
1708                         500, cyapa_gen5_sort_tsg_pip_app_resp_data, true);
1709         if (error || !VALID_CMD_RESP_HEADER(resp_data, 0x03))
1710                 return -EINVAL;
1711
1712         /* Try to dump all buffered data when suspending scanning. */
1713         cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
1714
1715         return 0;
1716 }
1717
1718 static int cyapa_gen5_calibrate_pwcs(struct cyapa *cyapa,
1719                 u8 calibrate_sensing_mode_type)
1720 {
1721         struct gen5_app_cmd_head *app_cmd_head;
1722         u8 cmd[8];
1723         u8 resp_data[6];
1724         int resp_len;
1725         int error;
1726
1727         /* Try to dump all buffered data before doing command. */
1728         cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
1729
1730         memset(cmd, 0, sizeof(cmd));
1731         app_cmd_head = (struct gen5_app_cmd_head *)cmd;
1732         put_unaligned_le16(GEN5_OUTPUT_REPORT_ADDR, &app_cmd_head->addr);
1733         put_unaligned_le16(sizeof(cmd) - 2, &app_cmd_head->length);
1734         app_cmd_head->report_id = GEN5_APP_CMD_REPORT_ID;
1735         app_cmd_head->cmd_code = GEN5_CMD_CALIBRATE;
1736         app_cmd_head->parameter_data[0] = calibrate_sensing_mode_type;
1737         resp_len = sizeof(resp_data);
1738         error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
1739                         cmd, sizeof(cmd),
1740                         resp_data, &resp_len,
1741                         5000, cyapa_gen5_sort_tsg_pip_app_resp_data, true);
1742         if (error || !VALID_CMD_RESP_HEADER(resp_data, GEN5_CMD_CALIBRATE) ||
1743                         !GEN5_CMD_COMPLETE_SUCCESS(resp_data[5]))
1744                 return error < 0 ? error : -EAGAIN;
1745
1746         return 0;
1747 }
1748
1749 static ssize_t cyapa_gen5_do_calibrate(struct device *dev,
1750                                      struct device_attribute *attr,
1751                                      const char *buf, size_t count)
1752 {
1753         struct cyapa *cyapa = dev_get_drvdata(dev);
1754         int error, calibrate_error;
1755
1756         /* 1. Suspend Scanning*/
1757         error = cyapa_gen5_suspend_scanning(cyapa);
1758         if (error)
1759                 return error;
1760
1761         /* 2. Do mutual capacitance fine calibrate. */
1762         calibrate_error = cyapa_gen5_calibrate_pwcs(cyapa,
1763                                 CYAPA_SENSING_MODE_MUTUAL_CAP_FINE);
1764         if (calibrate_error)
1765                 goto resume_scanning;
1766
1767         /* 3. Do self capacitance calibrate. */
1768         calibrate_error = cyapa_gen5_calibrate_pwcs(cyapa,
1769                                 CYAPA_SENSING_MODE_SELF_CAP);
1770         if (calibrate_error)
1771                 goto resume_scanning;
1772
1773 resume_scanning:
1774         /* 4. Resume Scanning*/
1775         error = cyapa_gen5_resume_scanning(cyapa);
1776         if (error || calibrate_error)
1777                 return error ? error : calibrate_error;
1778
1779         return count;
1780 }
1781
1782 static s32 twos_complement_to_s32(s32 value, int num_bits)
1783 {
1784         if (value >> (num_bits - 1))
1785                 value |=  -1 << num_bits;
1786         return value;
1787 }
1788
1789 static s32 cyapa_parse_structure_data(u8 data_format, u8 *buf, int buf_len)
1790 {
1791         int data_size;
1792         bool big_endian;
1793         bool unsigned_type;
1794         s32 value;
1795
1796         data_size = (data_format & 0x07);
1797         big_endian = ((data_format & 0x10) == 0x00);
1798         unsigned_type = ((data_format & 0x20) == 0x00);
1799
1800         if (buf_len < data_size)
1801                 return 0;
1802
1803         switch (data_size) {
1804         case 1:
1805                 value  = buf[0];
1806                 break;
1807         case 2:
1808                 if (big_endian)
1809                         value = get_unaligned_be16(buf);
1810                 else
1811                         value = get_unaligned_le16(buf);
1812                 break;
1813         case 4:
1814                 if (big_endian)
1815                         value = get_unaligned_be32(buf);
1816                 else
1817                         value = get_unaligned_le32(buf);
1818                 break;
1819         default:
1820                 /* Should not happen, just as default case here. */
1821                 value = 0;
1822                 break;
1823         }
1824
1825         if (!unsigned_type)
1826                 value = twos_complement_to_s32(value, data_size * 8);
1827
1828         return value;
1829 }
1830
1831 static void cyapa_gen5_guess_electrodes(struct cyapa *cyapa,
1832                 int *electrodes_rx, int *electrodes_tx)
1833 {
1834         if (cyapa->electrodes_rx != 0) {
1835                 *electrodes_rx = cyapa->electrodes_rx;
1836                 *electrodes_tx = (cyapa->electrodes_x == *electrodes_rx) ?
1837                                 cyapa->electrodes_y : cyapa->electrodes_x;
1838         } else {
1839                 *electrodes_tx = min(cyapa->electrodes_x, cyapa->electrodes_y);
1840                 *electrodes_rx = max(cyapa->electrodes_x, cyapa->electrodes_y);
1841         }
1842 }
1843
1844 /*
1845  * Read all the global mutual or self idac data or mutual or self local PWC
1846  * data based on the @idac_data_type.
1847  * If the input value of @data_size is 0, then means read global mutual or
1848  * self idac data. For read global mutual idac data, @idac_max, @idac_min and
1849  * @idac_ave are in order used to return the max value of global mutual idac
1850  * data, the min value of global mutual idac and the average value of the
1851  * global mutual idac data. For read global self idac data, @idac_max is used
1852  * to return the global self cap idac data in Rx direction, @idac_min is used
1853  * to return the global self cap idac data in Tx direction. @idac_ave is not
1854  * used.
1855  * If the input value of @data_size is not 0, than means read the mutual or
1856  * self local PWC data. The @idac_max, @idac_min and @idac_ave are used to
1857  * return the max, min and average value of the mutual or self local PWC data.
1858  * Note, in order to raed mutual local PWC data, must read invoke this function
1859  * to read the mutual global idac data firstly to set the correct Rx number
1860  * value, otherwise, the read mutual idac and PWC data may not correct.
1861  */
1862 static int cyapa_gen5_read_idac_data(struct cyapa *cyapa,
1863                 u8 cmd_code, u8 idac_data_type, int *data_size,
1864                 int *idac_max, int *idac_min, int *idac_ave)
1865 {
1866         struct gen5_app_cmd_head *cmd_head;
1867         u8 cmd[12];
1868         u8 resp_data[256];
1869         int resp_len;
1870         int read_len;
1871         int value;
1872         u16 offset;
1873         int read_elements;
1874         bool read_global_idac;
1875         int sum, count, max_element_cnt;
1876         int tmp_max, tmp_min, tmp_ave, tmp_sum, tmp_count;
1877         int electrodes_rx, electrodes_tx;
1878         int i;
1879         int error;
1880
1881         if (cmd_code != GEN5_CMD_RETRIEVE_DATA_STRUCTURE ||
1882                 (idac_data_type != GEN5_RETRIEVE_MUTUAL_PWC_DATA &&
1883                 idac_data_type != GEN5_RETRIEVE_SELF_CAP_PWC_DATA) ||
1884                 !data_size || !idac_max || !idac_min || !idac_ave)
1885                 return -EINVAL;
1886
1887         *idac_max = INT_MIN;
1888         *idac_min = INT_MAX;
1889         sum = count = tmp_count = 0;
1890         electrodes_rx = electrodes_tx = 0;
1891         if (*data_size == 0) {
1892                 /*
1893                  * Read global idac values firstly.
1894                  * Currently, no idac data exceed 4 bytes.
1895                  */
1896                 read_global_idac = true;
1897                 offset = 0;
1898                 *data_size = 4;
1899                 tmp_max = INT_MIN;
1900                 tmp_min = INT_MAX;
1901                 tmp_ave = tmp_sum = tmp_count = 0;
1902
1903                 if (idac_data_type == GEN5_RETRIEVE_MUTUAL_PWC_DATA) {
1904                         if (cyapa->aligned_electrodes_rx == 0) {
1905                                 cyapa_gen5_guess_electrodes(cyapa,
1906                                         &electrodes_rx, &electrodes_tx);
1907                                 cyapa->aligned_electrodes_rx =
1908                                         (electrodes_rx + 3) & ~3u;
1909                         }
1910                         max_element_cnt =
1911                                 (cyapa->aligned_electrodes_rx + 7) & ~7u;
1912                 } else {
1913                         max_element_cnt = 2;
1914                 }
1915         } else {
1916                 read_global_idac = false;
1917                 if (*data_size > 4)
1918                         *data_size = 4;
1919                 /* Calculate the start offset in bytes of local PWC data. */
1920                 if (idac_data_type == GEN5_RETRIEVE_MUTUAL_PWC_DATA) {
1921                         offset = cyapa->aligned_electrodes_rx * (*data_size);
1922                         if (cyapa->electrodes_rx == cyapa->electrodes_x)
1923                                 electrodes_tx = cyapa->electrodes_y;
1924                         else
1925                                 electrodes_tx = cyapa->electrodes_x;
1926                         max_element_cnt = ((cyapa->aligned_electrodes_rx + 7) &
1927                                                 ~7u) * electrodes_tx;
1928                 } else if (idac_data_type == GEN5_RETRIEVE_SELF_CAP_PWC_DATA) {
1929                         offset = 2;
1930                         max_element_cnt = cyapa->electrodes_x +
1931                                                 cyapa->electrodes_y;
1932                         max_element_cnt = (max_element_cnt + 3) & ~3u;
1933                 }
1934         }
1935
1936         memset(cmd, 0, sizeof(cmd));
1937         cmd_head = (struct gen5_app_cmd_head *)cmd;
1938         put_unaligned_le16(GEN5_OUTPUT_REPORT_ADDR, &cmd_head->addr);
1939         put_unaligned_le16(sizeof(cmd) - 2, &cmd_head->length);
1940         cmd_head->report_id = GEN5_APP_CMD_REPORT_ID;
1941         cmd_head->cmd_code = cmd_code;
1942         do {
1943                 read_elements = (256 - GEN5_RESP_DATA_STRUCTURE_OFFSET) /
1944                                 (*data_size);
1945                 read_elements = min(read_elements, max_element_cnt - count);
1946                 read_len = read_elements * (*data_size);
1947
1948                 put_unaligned_le16(offset, &cmd_head->parameter_data[0]);
1949                 put_unaligned_le16(read_len, &cmd_head->parameter_data[2]);
1950                 cmd_head->parameter_data[4] = idac_data_type;
1951                 resp_len = GEN5_RESP_DATA_STRUCTURE_OFFSET + read_len;
1952                 error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
1953                                 cmd, sizeof(cmd),
1954                                 resp_data, &resp_len,
1955                                 500, cyapa_gen5_sort_tsg_pip_app_resp_data,
1956                                 true);
1957                 if (error || resp_len < GEN5_RESP_DATA_STRUCTURE_OFFSET ||
1958                                 !VALID_CMD_RESP_HEADER(resp_data, cmd_code) ||
1959                                 !GEN5_CMD_COMPLETE_SUCCESS(resp_data[5]) ||
1960                                 resp_data[6] != idac_data_type)
1961                         return (error < 0) ? error : -EAGAIN;
1962                 read_len = get_unaligned_le16(&resp_data[7]);
1963                 if (read_len == 0)
1964                         break;
1965
1966                 *data_size = (resp_data[9] & GEN5_PWC_DATA_ELEMENT_SIZE_MASK);
1967                 if (read_len < *data_size)
1968                         return -EINVAL;
1969
1970                 if (read_global_idac &&
1971                         idac_data_type == GEN5_RETRIEVE_SELF_CAP_PWC_DATA) {
1972                         /* Rx's self global idac data. */
1973                         *idac_max = cyapa_parse_structure_data(
1974                                 resp_data[9],
1975                                 &resp_data[GEN5_RESP_DATA_STRUCTURE_OFFSET],
1976                                 *data_size);
1977                         /* Tx's self global idac data. */
1978                         *idac_min = cyapa_parse_structure_data(
1979                                 resp_data[9],
1980                                 &resp_data[GEN5_RESP_DATA_STRUCTURE_OFFSET +
1981                                            *data_size],
1982                                 *data_size);
1983                         break;
1984                 }
1985
1986                 /* Read mutual global idac or local mutual/self PWC data. */
1987                 offset += read_len;
1988                 for (i = 10; i < (read_len + GEN5_RESP_DATA_STRUCTURE_OFFSET);
1989                                 i += *data_size) {
1990                         value = cyapa_parse_structure_data(resp_data[9],
1991                                         &resp_data[i], *data_size);
1992                         *idac_min = min(value, *idac_min);
1993                         *idac_max = max(value, *idac_max);
1994
1995                         if (idac_data_type == GEN5_RETRIEVE_MUTUAL_PWC_DATA &&
1996                                 tmp_count < cyapa->aligned_electrodes_rx &&
1997                                 read_global_idac) {
1998                                 /*
1999                                  * The value gap betwen global and local mutual
2000                                  * idac data must bigger than 50%.
2001                                  * Normally, global value bigger than 50,
2002                                  * local values less than 10.
2003                                  */
2004                                 if (!tmp_ave || value > tmp_ave / 2) {
2005                                         tmp_min = min(value, tmp_min);
2006                                         tmp_max = max(value, tmp_max);
2007                                         tmp_sum += value;
2008                                         tmp_count++;
2009
2010                                         tmp_ave = tmp_sum / tmp_count;
2011                                 }
2012                         }
2013
2014                         sum += value;
2015                         count++;
2016
2017                         if (count >= max_element_cnt)
2018                                 goto out;
2019                 }
2020         } while (true);
2021
2022 out:
2023         *idac_ave = count ? (sum / count) : 0;
2024
2025         if (read_global_idac &&
2026                 idac_data_type == GEN5_RETRIEVE_MUTUAL_PWC_DATA) {
2027                 if (tmp_count == 0)
2028                         return 0;
2029
2030                 if (tmp_count == cyapa->aligned_electrodes_rx) {
2031                         cyapa->electrodes_rx = cyapa->electrodes_rx ?
2032                                 cyapa->electrodes_rx : electrodes_rx;
2033                 } else if (tmp_count == electrodes_rx) {
2034                         cyapa->electrodes_rx = cyapa->electrodes_rx ?
2035                                 cyapa->electrodes_rx : electrodes_rx;
2036                         cyapa->aligned_electrodes_rx = electrodes_rx;
2037                 } else {
2038                         cyapa->electrodes_rx = cyapa->electrodes_rx ?
2039                                 cyapa->electrodes_rx : electrodes_tx;
2040                         cyapa->aligned_electrodes_rx = tmp_count;
2041                 }
2042
2043                 *idac_min = tmp_min;
2044                 *idac_max = tmp_max;
2045                 *idac_ave = tmp_ave;
2046         }
2047
2048         return 0;
2049 }
2050
2051 static int cyapa_gen5_read_mutual_idac_data(struct cyapa *cyapa,
2052         int *gidac_mutual_max, int *gidac_mutual_min, int *gidac_mutual_ave,
2053         int *lidac_mutual_max, int *lidac_mutual_min, int *lidac_mutual_ave)
2054 {
2055         int data_size;
2056         int error;
2057
2058         *gidac_mutual_max = *gidac_mutual_min = *gidac_mutual_ave = 0;
2059         *lidac_mutual_max = *lidac_mutual_min = *lidac_mutual_ave = 0;
2060
2061         data_size = 0;
2062         error = cyapa_gen5_read_idac_data(cyapa,
2063                 GEN5_CMD_RETRIEVE_DATA_STRUCTURE,
2064                 GEN5_RETRIEVE_MUTUAL_PWC_DATA,
2065                 &data_size,
2066                 gidac_mutual_max, gidac_mutual_min, gidac_mutual_ave);
2067         if (error)
2068                 return error;
2069
2070         error = cyapa_gen5_read_idac_data(cyapa,
2071                 GEN5_CMD_RETRIEVE_DATA_STRUCTURE,
2072                 GEN5_RETRIEVE_MUTUAL_PWC_DATA,
2073                 &data_size,
2074                 lidac_mutual_max, lidac_mutual_min, lidac_mutual_ave);
2075         return error;
2076 }
2077
2078 static int cyapa_gen5_read_self_idac_data(struct cyapa *cyapa,
2079                 int *gidac_self_rx, int *gidac_self_tx,
2080                 int *lidac_self_max, int *lidac_self_min, int *lidac_self_ave)
2081 {
2082         int data_size;
2083         int error;
2084
2085         *gidac_self_rx = *gidac_self_tx = 0;
2086         *lidac_self_max = *lidac_self_min = *lidac_self_ave = 0;
2087
2088         data_size = 0;
2089         error = cyapa_gen5_read_idac_data(cyapa,
2090                 GEN5_CMD_RETRIEVE_DATA_STRUCTURE,
2091                 GEN5_RETRIEVE_SELF_CAP_PWC_DATA,
2092                 &data_size,
2093                 lidac_self_max, lidac_self_min, lidac_self_ave);
2094         if (error)
2095                 return error;
2096         *gidac_self_rx = *lidac_self_max;
2097         *gidac_self_tx = *lidac_self_min;
2098
2099         error = cyapa_gen5_read_idac_data(cyapa,
2100                 GEN5_CMD_RETRIEVE_DATA_STRUCTURE,
2101                 GEN5_RETRIEVE_SELF_CAP_PWC_DATA,
2102                 &data_size,
2103                 lidac_self_max, lidac_self_min, lidac_self_ave);
2104         return error;
2105 }
2106
2107 static ssize_t cyapa_gen5_execute_panel_scan(struct cyapa *cyapa)
2108 {
2109         struct gen5_app_cmd_head *app_cmd_head;
2110         u8 cmd[7];
2111         u8 resp_data[6];
2112         int resp_len;
2113         int error;
2114
2115         memset(cmd, 0, sizeof(cmd));
2116         app_cmd_head = (struct gen5_app_cmd_head *)cmd;
2117         put_unaligned_le16(GEN5_OUTPUT_REPORT_ADDR, &app_cmd_head->addr);
2118         put_unaligned_le16(sizeof(cmd) - 2, &app_cmd_head->length);
2119         app_cmd_head->report_id = GEN5_APP_CMD_REPORT_ID;
2120         app_cmd_head->cmd_code = GEN5_CMD_EXECUTE_PANEL_SCAN;
2121         resp_len = sizeof(resp_data);
2122         error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
2123                         cmd, sizeof(cmd),
2124                         resp_data, &resp_len,
2125                         500, cyapa_gen5_sort_tsg_pip_app_resp_data, true);
2126         if (error || resp_len != sizeof(resp_data) ||
2127                         !VALID_CMD_RESP_HEADER(resp_data,
2128                                 GEN5_CMD_EXECUTE_PANEL_SCAN) ||
2129                         !GEN5_CMD_COMPLETE_SUCCESS(resp_data[5]))
2130                 return error ? error : -EAGAIN;
2131
2132         return 0;
2133 }
2134
2135 static int cyapa_gen5_read_panel_scan_raw_data(struct cyapa *cyapa,
2136                 u8 cmd_code, u8 raw_data_type, int raw_data_max_num,
2137                 int *raw_data_max, int *raw_data_min, int *raw_data_ave,
2138                 u8 *buffer)
2139 {
2140         struct gen5_app_cmd_head *app_cmd_head;
2141         struct gen5_retrieve_panel_scan_data *panel_sacn_data;
2142         u8 cmd[12];
2143         u8 resp_data[256];  /* Max bytes can transfer one time. */
2144         int resp_len;
2145         int read_elements;
2146         int read_len;
2147         u16 offset;
2148         s32 value;
2149         int sum, count;
2150         int data_size;
2151         s32 *intp;
2152         int i;
2153         int error;
2154
2155         if (cmd_code != GEN5_CMD_RETRIEVE_PANEL_SCAN ||
2156                 (raw_data_type > GEN5_PANEL_SCAN_SELF_DIFFCOUNT) ||
2157                 !raw_data_max || !raw_data_min || !raw_data_ave)
2158                 return -EINVAL;
2159
2160         intp = (s32 *)buffer;
2161         *raw_data_max = INT_MIN;
2162         *raw_data_min = INT_MAX;
2163         sum = count = 0;
2164         offset = 0;
2165         /* Assume max element size is 4 currently. */
2166         read_elements = (256 - GEN5_RESP_DATA_STRUCTURE_OFFSET) / 4;
2167         read_len = read_elements * 4;
2168         app_cmd_head = (struct gen5_app_cmd_head *)cmd;
2169         put_unaligned_le16(GEN5_OUTPUT_REPORT_ADDR, &app_cmd_head->addr);
2170         put_unaligned_le16(sizeof(cmd) - 2, &app_cmd_head->length);
2171         app_cmd_head->report_id = GEN5_APP_CMD_REPORT_ID;
2172         app_cmd_head->cmd_code = cmd_code;
2173         panel_sacn_data = (struct gen5_retrieve_panel_scan_data *)
2174                         app_cmd_head->parameter_data;
2175         do {
2176                 put_unaligned_le16(offset, &panel_sacn_data->read_offset);
2177                 put_unaligned_le16(read_elements,
2178                         &panel_sacn_data->read_elements);
2179                 panel_sacn_data->data_id = raw_data_type;
2180
2181                 resp_len = GEN5_RESP_DATA_STRUCTURE_OFFSET + read_len;
2182                 error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
2183                         cmd, sizeof(cmd),
2184                         resp_data, &resp_len,
2185                         500, cyapa_gen5_sort_tsg_pip_app_resp_data, true);
2186                 if (error || resp_len < GEN5_RESP_DATA_STRUCTURE_OFFSET ||
2187                                 !VALID_CMD_RESP_HEADER(resp_data, cmd_code) ||
2188                                 !GEN5_CMD_COMPLETE_SUCCESS(resp_data[5]) ||
2189                                 resp_data[6] != raw_data_type)
2190                         return error ? error : -EAGAIN;
2191
2192                 read_elements = get_unaligned_le16(&resp_data[7]);
2193                 if (read_elements == 0)
2194                         break;
2195
2196                 data_size = (resp_data[9] & GEN5_PWC_DATA_ELEMENT_SIZE_MASK);
2197                 offset += read_elements;
2198                 if (read_elements) {
2199                         for (i = GEN5_RESP_DATA_STRUCTURE_OFFSET;
2200                              i < (read_elements * data_size +
2201                                         GEN5_RESP_DATA_STRUCTURE_OFFSET);
2202                              i += data_size) {
2203                                 value = cyapa_parse_structure_data(resp_data[9],
2204                                                 &resp_data[i], data_size);
2205                                 *raw_data_min = min(value, *raw_data_min);
2206                                 *raw_data_max = max(value, *raw_data_max);
2207
2208                                 if (intp)
2209                                         put_unaligned_le32(value, &intp[count]);
2210
2211                                 sum += value;
2212                                 count++;
2213
2214                         }
2215                 }
2216
2217                 if (count >= raw_data_max_num)
2218                         break;
2219
2220                 read_elements = (sizeof(resp_data) -
2221                                 GEN5_RESP_DATA_STRUCTURE_OFFSET) / data_size;
2222                 read_len = read_elements * data_size;
2223         } while (true);
2224
2225         *raw_data_ave = count ? (sum / count) : 0;
2226
2227         return 0;
2228 }
2229
2230 static ssize_t cyapa_gen5_show_baseline(struct device *dev,
2231                                    struct device_attribute *attr, char *buf)
2232 {
2233         struct cyapa *cyapa = dev_get_drvdata(dev);
2234         int gidac_mutual_max, gidac_mutual_min, gidac_mutual_ave;
2235         int lidac_mutual_max, lidac_mutual_min, lidac_mutual_ave;
2236         int gidac_self_rx, gidac_self_tx;
2237         int lidac_self_max, lidac_self_min, lidac_self_ave;
2238         int raw_cap_mutual_max, raw_cap_mutual_min, raw_cap_mutual_ave;
2239         int raw_cap_self_max, raw_cap_self_min, raw_cap_self_ave;
2240         int mutual_diffdata_max, mutual_diffdata_min, mutual_diffdata_ave;
2241         int self_diffdata_max, self_diffdata_min, self_diffdata_ave;
2242         int mutual_baseline_max, mutual_baseline_min, mutual_baseline_ave;
2243         int self_baseline_max, self_baseline_min, self_baseline_ave;
2244         int error, resume_error;
2245         int size;
2246
2247         if (cyapa->state != CYAPA_STATE_GEN5_APP)
2248                 return -EBUSY;
2249
2250         /* 1. Suspend Scanning*/
2251         error = cyapa_gen5_suspend_scanning(cyapa);
2252         if (error)
2253                 return error;
2254
2255         /* 2.  Read global and local mutual IDAC data. */
2256         gidac_self_rx = gidac_self_tx = 0;
2257         error = cyapa_gen5_read_mutual_idac_data(cyapa,
2258                                 &gidac_mutual_max, &gidac_mutual_min,
2259                                 &gidac_mutual_ave, &lidac_mutual_max,
2260                                 &lidac_mutual_min, &lidac_mutual_ave);
2261         if (error)
2262                 goto resume_scanning;
2263
2264         /* 3.  Read global and local self IDAC data. */
2265         error = cyapa_gen5_read_self_idac_data(cyapa,
2266                                 &gidac_self_rx, &gidac_self_tx,
2267                                 &lidac_self_max, &lidac_self_min,
2268                                 &lidac_self_ave);
2269         if (error)
2270                 goto resume_scanning;
2271
2272         /* 4. Execuate panel scan. It must be executed before read data. */
2273         error = cyapa_gen5_execute_panel_scan(cyapa);
2274         if (error)
2275                 goto resume_scanning;
2276
2277         /* 5. Retrieve panel scan, mutual cap raw data. */
2278         error = cyapa_gen5_read_panel_scan_raw_data(cyapa,
2279                                 GEN5_CMD_RETRIEVE_PANEL_SCAN,
2280                                 GEN5_PANEL_SCAN_MUTUAL_RAW_DATA,
2281                                 cyapa->electrodes_x * cyapa->electrodes_y,
2282                                 &raw_cap_mutual_max, &raw_cap_mutual_min,
2283                                 &raw_cap_mutual_ave,
2284                                 NULL);
2285         if (error)
2286                 goto resume_scanning;
2287
2288         /* 6. Retrieve panel scan, self cap raw data. */
2289         error = cyapa_gen5_read_panel_scan_raw_data(cyapa,
2290                                 GEN5_CMD_RETRIEVE_PANEL_SCAN,
2291                                 GEN5_PANEL_SCAN_SELF_RAW_DATA,
2292                                 cyapa->electrodes_x + cyapa->electrodes_y,
2293                                 &raw_cap_self_max, &raw_cap_self_min,
2294                                 &raw_cap_self_ave,
2295                                 NULL);
2296         if (error)
2297                 goto resume_scanning;
2298
2299         /* 7. Retrieve panel scan, mutual cap diffcount raw data. */
2300         error = cyapa_gen5_read_panel_scan_raw_data(cyapa,
2301                                 GEN5_CMD_RETRIEVE_PANEL_SCAN,
2302                                 GEN5_PANEL_SCAN_MUTUAL_DIFFCOUNT,
2303                                 cyapa->electrodes_x * cyapa->electrodes_y,
2304                                 &mutual_diffdata_max, &mutual_diffdata_min,
2305                                 &mutual_diffdata_ave,
2306                                 NULL);
2307         if (error)
2308                 goto resume_scanning;
2309
2310         /* 8. Retrieve panel scan, self cap diffcount raw data. */
2311         error = cyapa_gen5_read_panel_scan_raw_data(cyapa,
2312                                 GEN5_CMD_RETRIEVE_PANEL_SCAN,
2313                                 GEN5_PANEL_SCAN_SELF_DIFFCOUNT,
2314                                 cyapa->electrodes_x + cyapa->electrodes_y,
2315                                 &self_diffdata_max, &self_diffdata_min,
2316                                 &self_diffdata_ave,
2317                                 NULL);
2318         if (error)
2319                 goto resume_scanning;
2320
2321         /* 9. Retrieve panel scan, mutual cap baseline raw data. */
2322         error = cyapa_gen5_read_panel_scan_raw_data(cyapa,
2323                                 GEN5_CMD_RETRIEVE_PANEL_SCAN,
2324                                 GEN5_PANEL_SCAN_MUTUAL_BASELINE,
2325                                 cyapa->electrodes_x * cyapa->electrodes_y,
2326                                 &mutual_baseline_max, &mutual_baseline_min,
2327                                 &mutual_baseline_ave,
2328                                 NULL);
2329         if (error)
2330                 goto resume_scanning;
2331
2332         /* 10. Retrieve panel scan, self cap baseline raw data. */
2333         error = cyapa_gen5_read_panel_scan_raw_data(cyapa,
2334                                 GEN5_CMD_RETRIEVE_PANEL_SCAN,
2335                                 GEN5_PANEL_SCAN_SELF_BASELINE,
2336                                 cyapa->electrodes_x + cyapa->electrodes_y,
2337                                 &self_baseline_max, &self_baseline_min,
2338                                 &self_baseline_ave,
2339                                 NULL);
2340         if (error)
2341                 goto resume_scanning;
2342
2343 resume_scanning:
2344         /* 11. Resume Scanning*/
2345         resume_error = cyapa_gen5_resume_scanning(cyapa);
2346         if (resume_error || error)
2347                 return resume_error ? resume_error : error;
2348
2349         /* 12. Output data strings */
2350         size = scnprintf(buf, PAGE_SIZE, "%d %d %d %d %d %d %d %d %d %d %d ",
2351                 gidac_mutual_min, gidac_mutual_max, gidac_mutual_ave,
2352                 lidac_mutual_min, lidac_mutual_max, lidac_mutual_ave,
2353                 gidac_self_rx, gidac_self_tx,
2354                 lidac_self_min, lidac_self_max, lidac_self_ave);
2355         size += scnprintf(buf + size, PAGE_SIZE - size,
2356                 "%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n",
2357                 raw_cap_mutual_min, raw_cap_mutual_max, raw_cap_mutual_ave,
2358                 raw_cap_self_min, raw_cap_self_max, raw_cap_self_ave,
2359                 mutual_diffdata_min, mutual_diffdata_max, mutual_diffdata_ave,
2360                 self_diffdata_min, self_diffdata_max, self_diffdata_ave,
2361                 mutual_baseline_min, mutual_baseline_max, mutual_baseline_ave,
2362                 self_baseline_min, self_baseline_max, self_baseline_ave);
2363         return size;
2364 }
2365
2366 static bool cyapa_gen5_sort_system_info_data(struct cyapa *cyapa,
2367                 u8 *buf, int len)
2368 {
2369         /* Check the report id and command code */
2370         if (VALID_CMD_RESP_HEADER(buf, 0x02))
2371                 return true;
2372
2373         return false;
2374 }
2375
2376 static int cyapa_gen5_bl_query_data(struct cyapa *cyapa)
2377 {
2378         u8 bl_query_data_cmd[] = { 0x04, 0x00, 0x0b, 0x00, 0x40, 0x00,
2379                 0x01, 0x3c, 0x00, 0x00, 0xb0, 0x42, 0x17
2380         };
2381         u8 resp_data[GEN5_BL_READ_APP_INFO_RESP_LEN];
2382         int resp_len;
2383         int error;
2384
2385         resp_len = GEN5_BL_READ_APP_INFO_RESP_LEN;
2386         error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
2387                         bl_query_data_cmd, sizeof(bl_query_data_cmd),
2388                         resp_data, &resp_len,
2389                         500, cyapa_gen5_sort_tsg_pip_bl_resp_data, false);
2390         if (error || resp_len != GEN5_BL_READ_APP_INFO_RESP_LEN ||
2391                 !GEN5_CMD_COMPLETE_SUCCESS(resp_data[5]))
2392                 return error ? error : -EIO;
2393
2394         memcpy(&cyapa->product_id[0], &resp_data[8], 5);
2395         cyapa->product_id[5] = '-';
2396         memcpy(&cyapa->product_id[6], &resp_data[13], 6);
2397         cyapa->product_id[12] = '-';
2398         memcpy(&cyapa->product_id[13], &resp_data[19], 2);
2399         cyapa->product_id[15] = '\0';
2400
2401         cyapa->fw_maj_ver = resp_data[22];
2402         cyapa->fw_min_ver = resp_data[23];
2403
2404         return 0;
2405 }
2406
2407 static int cyapa_gen5_get_query_data(struct cyapa *cyapa)
2408 {
2409         u8 get_system_information[] = {
2410                 0x04, 0x00, 0x05, 0x00, 0x2f, 0x00, 0x02
2411         };
2412         u8 resp_data[71];
2413         int resp_len;
2414         u16 product_family;
2415         int error;
2416
2417         resp_len = sizeof(resp_data);
2418         error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
2419                         get_system_information, sizeof(get_system_information),
2420                         resp_data, &resp_len,
2421                         2000, cyapa_gen5_sort_system_info_data, false);
2422         if (error || resp_len < sizeof(resp_data))
2423                 return error ? error : -EIO;
2424
2425         product_family = get_unaligned_le16(&resp_data[7]);
2426         if ((product_family & GEN5_PRODUCT_FAMILY_MASK) !=
2427                 GEN5_PRODUCT_FAMILY_TRACKPAD)
2428                 return -EINVAL;
2429
2430         cyapa->fw_maj_ver = resp_data[15];
2431         cyapa->fw_min_ver = resp_data[16];
2432
2433         cyapa->electrodes_x = resp_data[52];
2434         cyapa->electrodes_y = resp_data[53];
2435
2436         cyapa->physical_size_x =  get_unaligned_le16(&resp_data[54]) / 100;
2437         cyapa->physical_size_y = get_unaligned_le16(&resp_data[56]) / 100;
2438
2439         cyapa->max_abs_x = get_unaligned_le16(&resp_data[58]);
2440         cyapa->max_abs_y = get_unaligned_le16(&resp_data[60]);
2441
2442         cyapa->max_z = get_unaligned_le16(&resp_data[62]);
2443
2444         cyapa->x_origin = resp_data[64] & 0x01;
2445         cyapa->y_origin = resp_data[65] & 0x01;
2446
2447         cyapa->btn_capability = (resp_data[70] << 3) & CAPABILITY_BTN_MASK;
2448
2449         memcpy(&cyapa->product_id[0], &resp_data[33], 5);
2450         cyapa->product_id[5] = '-';
2451         memcpy(&cyapa->product_id[6], &resp_data[38], 6);
2452         cyapa->product_id[12] = '-';
2453         memcpy(&cyapa->product_id[13], &resp_data[44], 2);
2454         cyapa->product_id[15] = '\0';
2455
2456         if (!cyapa->electrodes_x || !cyapa->electrodes_y ||
2457                 !cyapa->physical_size_x || !cyapa->physical_size_y ||
2458                 !cyapa->max_abs_x || !cyapa->max_abs_y || !cyapa->max_z)
2459                 return -EINVAL;
2460
2461         return 0;
2462 }
2463
2464 static int cyapa_gen5_do_operational_check(struct cyapa *cyapa)
2465 {
2466         struct device *dev = &cyapa->client->dev;
2467         int error;
2468
2469         if (cyapa->gen != CYAPA_GEN5)
2470                 return -ENODEV;
2471
2472         switch (cyapa->state) {
2473         case CYAPA_STATE_GEN5_BL:
2474                 error = cyapa_gen5_bl_exit(cyapa);
2475                 if (error) {
2476                         /* Rry to update trackpad product information. */
2477                         cyapa_gen5_bl_query_data(cyapa);
2478                         goto out;
2479                 }
2480
2481                 cyapa->state = CYAPA_STATE_GEN5_APP;
2482
2483         case CYAPA_STATE_GEN5_APP:
2484                 /*
2485                  * If trackpad device in deep sleep mode,
2486                  * the app command will fail.
2487                  * So always try to reset trackpad device to full active when
2488                  * the device state is requeried.
2489                  */
2490                 error = cyapa_gen5_set_power_mode(cyapa,
2491                                 PWR_MODE_FULL_ACTIVE, 0);
2492                 if (error)
2493                         dev_warn(dev, "%s: failed to set power active mode.\n",
2494                                 __func__);
2495
2496                 /* Get trackpad product information. */
2497                 error = cyapa_gen5_get_query_data(cyapa);
2498                 if (error)
2499                         goto out;
2500                 /* Only support product ID starting with CYTRA */
2501                 if (memcmp(cyapa->product_id, product_id,
2502                                 strlen(product_id)) != 0) {
2503                         dev_err(dev, "%s: unknown product ID (%s)\n",
2504                                 __func__, cyapa->product_id);
2505                         error = -EINVAL;
2506                 }
2507                 break;
2508         default:
2509                 error = -EINVAL;
2510         }
2511
2512 out:
2513         return error;
2514 }
2515
2516 /*
2517  * Return false, do not continue process
2518  * Return true, continue process.
2519  */
2520 static bool cyapa_gen5_irq_cmd_handler(struct cyapa *cyapa)
2521 {
2522         struct cyapa_gen5_cmd_states *gen5_pip = &cyapa->cmd_states.gen5;
2523         int length;
2524
2525         if (atomic_read(&gen5_pip->cmd_issued)) {
2526                 /* Polling command response data. */
2527                 if (gen5_pip->is_irq_mode == false)
2528                         return false;
2529
2530                 /*
2531                  * Read out all none command response data.
2532                  * these output data may caused by user put finger on
2533                  * trackpad when host waiting the command response.
2534                  */
2535                 cyapa_i2c_pip_read(cyapa, gen5_pip->irq_cmd_buf,
2536                         GEN5_RESP_LENGTH_SIZE);
2537                 length = get_unaligned_le16(gen5_pip->irq_cmd_buf);
2538                 length = (length <= GEN5_RESP_LENGTH_SIZE) ?
2539                                 GEN5_RESP_LENGTH_SIZE : length;
2540                 if (length > GEN5_RESP_LENGTH_SIZE)
2541                         cyapa_i2c_pip_read(cyapa,
2542                                 gen5_pip->irq_cmd_buf, length);
2543
2544                 if (!(gen5_pip->resp_sort_func &&
2545                         gen5_pip->resp_sort_func(cyapa,
2546                                 gen5_pip->irq_cmd_buf, length))) {
2547                         /*
2548                          * Cover the Gen5 V1 firmware issue.
2549                          * The issue is there is no interrut will be
2550                          * asserted to notityf host to read a command
2551                          * data out when always has finger touch on
2552                          * trackpad during the command is issued to
2553                          * trackad device.
2554                          * This issue has the scenario is that,
2555                          * user always has his fingers touched on
2556                          * trackpad device when booting/rebooting
2557                          * their chrome book.
2558                          */
2559                         length = *gen5_pip->resp_len;
2560                         cyapa_empty_pip_output_data(cyapa,
2561                                         gen5_pip->resp_data,
2562                                         &length,
2563                                         gen5_pip->resp_sort_func);
2564                         if (gen5_pip->resp_len && length != 0) {
2565                                 *gen5_pip->resp_len = length;
2566                                 atomic_dec(&gen5_pip->cmd_issued);
2567                                 complete(&gen5_pip->cmd_ready);
2568                         }
2569                         return false;
2570                 }
2571
2572                 if (gen5_pip->resp_data && gen5_pip->resp_len) {
2573                         *gen5_pip->resp_len = (*gen5_pip->resp_len < length) ?
2574                                 *gen5_pip->resp_len : length;
2575                         memcpy(gen5_pip->resp_data, gen5_pip->irq_cmd_buf,
2576                                 *gen5_pip->resp_len);
2577                 }
2578                 atomic_dec(&gen5_pip->cmd_issued);
2579                 complete(&gen5_pip->cmd_ready);
2580                 return false;
2581         }
2582
2583         return true;
2584 }
2585
2586 static void cyapa_gen5_report_buttons(struct cyapa *cyapa,
2587                 const struct cyapa_gen5_report_data *report_data)
2588 {
2589         struct input_dev *input = cyapa->input;
2590         u8 buttons = report_data->report_head[GEN5_BUTTONS_OFFSET];
2591
2592         buttons = (buttons << CAPABILITY_BTN_SHIFT) & CAPABILITY_BTN_MASK;
2593
2594         if (cyapa->btn_capability & CAPABILITY_LEFT_BTN_MASK) {
2595                 input_report_key(input, BTN_LEFT,
2596                         !!(buttons & CAPABILITY_LEFT_BTN_MASK));
2597         }
2598         if (cyapa->btn_capability & CAPABILITY_MIDDLE_BTN_MASK) {
2599                 input_report_key(input, BTN_MIDDLE,
2600                         !!(buttons & CAPABILITY_MIDDLE_BTN_MASK));
2601         }
2602         if (cyapa->btn_capability & CAPABILITY_RIGHT_BTN_MASK) {
2603                 input_report_key(input, BTN_RIGHT,
2604                         !!(buttons & CAPABILITY_RIGHT_BTN_MASK));
2605         }
2606
2607         input_sync(input);
2608 }
2609
2610 static void cyapa_gen5_report_slot_data(struct cyapa *cyapa,
2611                 const struct cyapa_gen5_touch_record *touch)
2612 {
2613         struct input_dev *input = cyapa->input;
2614         u8 event_id = GEN5_GET_EVENT_ID(touch->touch_tip_event_id);
2615         int slot = GEN5_GET_TOUCH_ID(touch->touch_tip_event_id);
2616         int x, y;
2617
2618         if (event_id == RECORD_EVENT_LIFTOFF)
2619                 return;
2620
2621         input_mt_slot(input, slot);
2622         input_mt_report_slot_state(input, MT_TOOL_FINGER, true);
2623         x = (touch->x_hi << 8) | touch->x_lo;
2624         if (cyapa->x_origin)
2625                 x = cyapa->max_abs_x - x;
2626         input_report_abs(input, ABS_MT_POSITION_X, x);
2627         y = (touch->y_hi << 8) | touch->y_lo;
2628         if (cyapa->y_origin)
2629                 y = cyapa->max_abs_y - y;
2630         input_report_abs(input, ABS_MT_POSITION_Y, y);
2631         input_report_abs(input, ABS_MT_PRESSURE,
2632                 touch->z);
2633         input_report_abs(input, ABS_MT_TOUCH_MAJOR,
2634                 touch->major_axis_len);
2635         input_report_abs(input, ABS_MT_TOUCH_MINOR,
2636                 touch->minor_axis_len);
2637
2638         input_report_abs(input, ABS_MT_WIDTH_MAJOR,
2639                 touch->major_tool_len);
2640         input_report_abs(input, ABS_MT_WIDTH_MINOR,
2641                 touch->minor_tool_len);
2642
2643         input_report_abs(input, ABS_MT_ORIENTATION,
2644                 touch->orientation);
2645 }
2646
2647 static void cyapa_gen5_report_touches(struct cyapa *cyapa,
2648                 const struct cyapa_gen5_report_data *report_data)
2649 {
2650         struct input_dev *input = cyapa->input;
2651         unsigned int touch_num;
2652         int i;
2653
2654         touch_num = report_data->report_head[GEN5_NUMBER_OF_TOUCH_OFFSET] &
2655                         GEN5_NUMBER_OF_TOUCH_MASK;
2656
2657         for (i = 0; i < touch_num; i++)
2658                 cyapa_gen5_report_slot_data(cyapa,
2659                         &report_data->touch_records[i]);
2660
2661         input_mt_sync_frame(input);
2662         input_sync(input);
2663 }
2664
2665 static int cyapa_gen5_irq_handler(struct cyapa *cyapa)
2666 {
2667         struct device *dev = &cyapa->client->dev;
2668         struct cyapa_gen5_report_data report_data;
2669         int ret;
2670         u8 report_id;
2671         unsigned int report_len;
2672
2673         if (cyapa->gen != CYAPA_GEN5 ||
2674                 cyapa->state != CYAPA_STATE_GEN5_APP) {
2675                 dev_err(dev, "invalid device state, gen=%d, state=0x%02x\n",
2676                         cyapa->gen, cyapa->state);
2677                 return -EINVAL;
2678         }
2679
2680         ret = cyapa_i2c_pip_read(cyapa, (u8 *)&report_data,
2681                         GEN5_RESP_LENGTH_SIZE);
2682         if (ret != GEN5_RESP_LENGTH_SIZE) {
2683                 dev_err(dev, "failed to read length bytes, (%d)\n", ret);
2684                 return -EINVAL;
2685         }
2686
2687         report_len = get_unaligned_le16(
2688                         &report_data.report_head[GEN5_RESP_LENGTH_OFFSET]);
2689         if (report_len < GEN5_RESP_LENGTH_SIZE) {
2690                 /* Invliad length or internal reset happened. */
2691                 dev_err(dev, "invalid report_len=%d. bytes: %02x %02x\n",
2692                         report_len, report_data.report_head[0],
2693                         report_data.report_head[1]);
2694                 return -EINVAL;
2695         }
2696
2697         /* Idle, no data for report. */
2698         if (report_len == GEN5_RESP_LENGTH_SIZE)
2699                 return 0;
2700
2701         ret = cyapa_i2c_pip_read(cyapa, (u8 *)&report_data, report_len);
2702         if (ret != report_len) {
2703                 dev_err(dev, "failed to read %d bytes report data, (%d)\n",
2704                         report_len, ret);
2705                 return -EINVAL;
2706         }
2707
2708         report_id = report_data.report_head[GEN5_RESP_REPORT_ID_OFFSET];
2709         if (report_id == GEN5_WAKEUP_EVENT_REPORT_ID &&
2710                         report_len == GEN5_WAKEUP_EVENT_SIZE) {
2711                 /*
2712                  * Device wake event from deep sleep mode for touch.
2713                  * This interrupt event is used to wake system up.
2714                  */
2715                 return 0;
2716         } else if (report_id != GEN5_TOUCH_REPORT_ID &&
2717                         report_id != GEN5_BTN_REPORT_ID &&
2718                         report_id != GEN5_OLD_PUSH_BTN_REPORT_ID &&
2719                         report_id != GEN5_PUSH_BTN_REPORT_ID) {
2720                 /* Running in BL mode or unknown response data read. */
2721                 dev_err(dev, "invalid report_id=0x%02x\n", report_id);
2722                 return -EINVAL;
2723         }
2724
2725         if (report_id == GEN5_TOUCH_REPORT_ID &&
2726                 (report_len < GEN5_TOUCH_REPORT_HEAD_SIZE ||
2727                         report_len > GEN5_TOUCH_REPORT_MAX_SIZE)) {
2728                 /* Invalid report data length for finger packet. */
2729                 dev_err(dev, "invalid touch packet length=%d\n", report_len);
2730                 return 0;
2731         }
2732
2733         if ((report_id == GEN5_BTN_REPORT_ID ||
2734                         report_id == GEN5_OLD_PUSH_BTN_REPORT_ID ||
2735                         report_id == GEN5_PUSH_BTN_REPORT_ID) &&
2736                 (report_len < GEN5_BTN_REPORT_HEAD_SIZE ||
2737                         report_len > GEN5_BTN_REPORT_MAX_SIZE)) {
2738                 /* Invalid report data length of button packet. */
2739                 dev_err(dev, "invalid button packet length=%d\n", report_len);
2740                 return 0;
2741         }
2742
2743         if (report_id == GEN5_TOUCH_REPORT_ID)
2744                 cyapa_gen5_report_touches(cyapa, &report_data);
2745         else
2746                 cyapa_gen5_report_buttons(cyapa, &report_data);
2747
2748         return 0;
2749 }
2750
2751 static int cyapa_gen5_bl_activate(struct cyapa *cyapa) { return 0; }
2752 static int cyapa_gen5_bl_deactivate(struct cyapa *cyapa) { return 0; }
2753
2754 const struct cyapa_dev_ops cyapa_gen5_ops = {
2755         .check_fw = cyapa_gen5_check_fw,
2756         .bl_enter = cyapa_gen5_bl_enter,
2757         .bl_initiate = cyapa_gen5_bl_initiate,
2758         .update_fw = cyapa_gen5_do_fw_update,
2759         .bl_activate = cyapa_gen5_bl_activate,
2760         .bl_deactivate = cyapa_gen5_bl_deactivate,
2761
2762         .show_baseline = cyapa_gen5_show_baseline,
2763         .calibrate_store = cyapa_gen5_do_calibrate,
2764
2765         .initialize = cyapa_gen5_initialize,
2766
2767         .state_parse = cyapa_gen5_state_parse,
2768         .operational_check = cyapa_gen5_do_operational_check,
2769
2770         .irq_handler = cyapa_gen5_irq_handler,
2771         .irq_cmd_handler = cyapa_gen5_irq_cmd_handler,
2772         .sort_empty_output_data = cyapa_empty_pip_output_data,
2773         .set_power_mode = cyapa_gen5_set_power_mode,
2774 };