GNU Linux-libre 4.9.309-gnu1
[releases.git] / drivers / hid / hid-logitech-hidpp.c
1 /*
2  *  HIDPP protocol for Logitech Unifying receivers
3  *
4  *  Copyright (c) 2011 Logitech (c)
5  *  Copyright (c) 2012-2013 Google (c)
6  *  Copyright (c) 2013-2014 Red Hat Inc.
7  */
8
9 /*
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU General Public License as published by the Free
12  * Software Foundation; version 2 of the License.
13  */
14
15 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16
17 #include <linux/device.h>
18 #include <linux/input.h>
19 #include <linux/usb.h>
20 #include <linux/hid.h>
21 #include <linux/module.h>
22 #include <linux/slab.h>
23 #include <linux/sched.h>
24 #include <linux/kfifo.h>
25 #include <linux/input/mt.h>
26 #include <linux/workqueue.h>
27 #include <linux/atomic.h>
28 #include <linux/fixp-arith.h>
29 #include <asm/unaligned.h>
30 #include "usbhid/usbhid.h"
31 #include "hid-ids.h"
32
33 MODULE_LICENSE("GPL");
34 MODULE_AUTHOR("Benjamin Tissoires <benjamin.tissoires@gmail.com>");
35 MODULE_AUTHOR("Nestor Lopez Casado <nlopezcasad@logitech.com>");
36
37 static bool disable_raw_mode;
38 module_param(disable_raw_mode, bool, 0644);
39 MODULE_PARM_DESC(disable_raw_mode,
40         "Disable Raw mode reporting for touchpads and keep firmware gestures.");
41
42 static bool disable_tap_to_click;
43 module_param(disable_tap_to_click, bool, 0644);
44 MODULE_PARM_DESC(disable_tap_to_click,
45         "Disable Tap-To-Click mode reporting for touchpads (only on the K400 currently).");
46
47 #define REPORT_ID_HIDPP_SHORT                   0x10
48 #define REPORT_ID_HIDPP_LONG                    0x11
49 #define REPORT_ID_HIDPP_VERY_LONG               0x12
50
51 #define HIDPP_REPORT_SHORT_LENGTH               7
52 #define HIDPP_REPORT_LONG_LENGTH                20
53 #define HIDPP_REPORT_VERY_LONG_LENGTH           64
54
55 #define HIDPP_QUIRK_CLASS_WTP                   BIT(0)
56 #define HIDPP_QUIRK_CLASS_M560                  BIT(1)
57 #define HIDPP_QUIRK_CLASS_K400                  BIT(2)
58 #define HIDPP_QUIRK_CLASS_G920                  BIT(3)
59
60 /* bits 2..20 are reserved for classes */
61 #define HIDPP_QUIRK_CONNECT_EVENTS              BIT(21)
62 #define HIDPP_QUIRK_WTP_PHYSICAL_BUTTONS        BIT(22)
63 #define HIDPP_QUIRK_NO_HIDINPUT                 BIT(23)
64 #define HIDPP_QUIRK_FORCE_OUTPUT_REPORTS        BIT(24)
65
66 #define HIDPP_QUIRK_DELAYED_INIT                (HIDPP_QUIRK_NO_HIDINPUT | \
67                                                  HIDPP_QUIRK_CONNECT_EVENTS)
68
69 /*
70  * There are two hidpp protocols in use, the first version hidpp10 is known
71  * as register access protocol or RAP, the second version hidpp20 is known as
72  * feature access protocol or FAP
73  *
74  * Most older devices (including the Unifying usb receiver) use the RAP protocol
75  * where as most newer devices use the FAP protocol. Both protocols are
76  * compatible with the underlying transport, which could be usb, Unifiying, or
77  * bluetooth. The message lengths are defined by the hid vendor specific report
78  * descriptor for the HIDPP_SHORT report type (total message lenth 7 bytes) and
79  * the HIDPP_LONG report type (total message length 20 bytes)
80  *
81  * The RAP protocol uses both report types, whereas the FAP only uses HIDPP_LONG
82  * messages. The Unifying receiver itself responds to RAP messages (device index
83  * is 0xFF for the receiver), and all messages (short or long) with a device
84  * index between 1 and 6 are passed untouched to the corresponding paired
85  * Unifying device.
86  *
87  * The paired device can be RAP or FAP, it will receive the message untouched
88  * from the Unifiying receiver.
89  */
90
91 struct fap {
92         u8 feature_index;
93         u8 funcindex_clientid;
94         u8 params[HIDPP_REPORT_VERY_LONG_LENGTH - 4U];
95 };
96
97 struct rap {
98         u8 sub_id;
99         u8 reg_address;
100         u8 params[HIDPP_REPORT_VERY_LONG_LENGTH - 4U];
101 };
102
103 struct hidpp_report {
104         u8 report_id;
105         u8 device_index;
106         union {
107                 struct fap fap;
108                 struct rap rap;
109                 u8 rawbytes[sizeof(struct fap)];
110         };
111 } __packed;
112
113 struct hidpp_device {
114         struct hid_device *hid_dev;
115         struct mutex send_mutex;
116         void *send_receive_buf;
117         char *name;             /* will never be NULL and should not be freed */
118         wait_queue_head_t wait;
119         bool answer_available;
120         u8 protocol_major;
121         u8 protocol_minor;
122
123         void *private_data;
124
125         struct work_struct work;
126         struct kfifo delayed_work_fifo;
127         atomic_t connected;
128         struct input_dev *delayed_input;
129
130         unsigned long quirks;
131 };
132
133
134 /* HID++ 1.0 error codes */
135 #define HIDPP_ERROR                             0x8f
136 #define HIDPP_ERROR_SUCCESS                     0x00
137 #define HIDPP_ERROR_INVALID_SUBID               0x01
138 #define HIDPP_ERROR_INVALID_ADRESS              0x02
139 #define HIDPP_ERROR_INVALID_VALUE               0x03
140 #define HIDPP_ERROR_CONNECT_FAIL                0x04
141 #define HIDPP_ERROR_TOO_MANY_DEVICES            0x05
142 #define HIDPP_ERROR_ALREADY_EXISTS              0x06
143 #define HIDPP_ERROR_BUSY                        0x07
144 #define HIDPP_ERROR_UNKNOWN_DEVICE              0x08
145 #define HIDPP_ERROR_RESOURCE_ERROR              0x09
146 #define HIDPP_ERROR_REQUEST_UNAVAILABLE         0x0a
147 #define HIDPP_ERROR_INVALID_PARAM_VALUE         0x0b
148 #define HIDPP_ERROR_WRONG_PIN_CODE              0x0c
149 /* HID++ 2.0 error codes */
150 #define HIDPP20_ERROR                           0xff
151
152 static void hidpp_connect_event(struct hidpp_device *hidpp_dev);
153
154 static int __hidpp_send_report(struct hid_device *hdev,
155                                 struct hidpp_report *hidpp_report)
156 {
157         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
158         int fields_count, ret;
159
160         hidpp = hid_get_drvdata(hdev);
161
162         switch (hidpp_report->report_id) {
163         case REPORT_ID_HIDPP_SHORT:
164                 fields_count = HIDPP_REPORT_SHORT_LENGTH;
165                 break;
166         case REPORT_ID_HIDPP_LONG:
167                 fields_count = HIDPP_REPORT_LONG_LENGTH;
168                 break;
169         case REPORT_ID_HIDPP_VERY_LONG:
170                 fields_count = HIDPP_REPORT_VERY_LONG_LENGTH;
171                 break;
172         default:
173                 return -ENODEV;
174         }
175
176         /*
177          * set the device_index as the receiver, it will be overwritten by
178          * hid_hw_request if needed
179          */
180         hidpp_report->device_index = 0xff;
181
182         if (hidpp->quirks & HIDPP_QUIRK_FORCE_OUTPUT_REPORTS) {
183                 ret = hid_hw_output_report(hdev, (u8 *)hidpp_report, fields_count);
184         } else {
185                 ret = hid_hw_raw_request(hdev, hidpp_report->report_id,
186                         (u8 *)hidpp_report, fields_count, HID_OUTPUT_REPORT,
187                         HID_REQ_SET_REPORT);
188         }
189
190         return ret == fields_count ? 0 : -1;
191 }
192
193 /**
194  * hidpp_send_message_sync() returns 0 in case of success, and something else
195  * in case of a failure.
196  * - If ' something else' is positive, that means that an error has been raised
197  *   by the protocol itself.
198  * - If ' something else' is negative, that means that we had a classic error
199  *   (-ENOMEM, -EPIPE, etc...)
200  */
201 static int hidpp_send_message_sync(struct hidpp_device *hidpp,
202         struct hidpp_report *message,
203         struct hidpp_report *response)
204 {
205         int ret;
206
207         mutex_lock(&hidpp->send_mutex);
208
209         hidpp->send_receive_buf = response;
210         hidpp->answer_available = false;
211
212         /*
213          * So that we can later validate the answer when it arrives
214          * in hidpp_raw_event
215          */
216         *response = *message;
217
218         ret = __hidpp_send_report(hidpp->hid_dev, message);
219
220         if (ret) {
221                 dbg_hid("__hidpp_send_report returned err: %d\n", ret);
222                 memset(response, 0, sizeof(struct hidpp_report));
223                 goto exit;
224         }
225
226         if (!wait_event_timeout(hidpp->wait, hidpp->answer_available,
227                                 5*HZ)) {
228                 dbg_hid("%s:timeout waiting for response\n", __func__);
229                 memset(response, 0, sizeof(struct hidpp_report));
230                 ret = -ETIMEDOUT;
231         }
232
233         if (response->report_id == REPORT_ID_HIDPP_SHORT &&
234             response->rap.sub_id == HIDPP_ERROR) {
235                 ret = response->rap.params[1];
236                 dbg_hid("%s:got hidpp error %02X\n", __func__, ret);
237                 goto exit;
238         }
239
240         if ((response->report_id == REPORT_ID_HIDPP_LONG ||
241                         response->report_id == REPORT_ID_HIDPP_VERY_LONG) &&
242                         response->fap.feature_index == HIDPP20_ERROR) {
243                 ret = response->fap.params[1];
244                 dbg_hid("%s:got hidpp 2.0 error %02X\n", __func__, ret);
245                 goto exit;
246         }
247
248 exit:
249         mutex_unlock(&hidpp->send_mutex);
250         return ret;
251
252 }
253
254 static int hidpp_send_fap_command_sync(struct hidpp_device *hidpp,
255         u8 feat_index, u8 funcindex_clientid, u8 *params, int param_count,
256         struct hidpp_report *response)
257 {
258         struct hidpp_report *message;
259         int ret;
260
261         if (param_count > sizeof(message->fap.params))
262                 return -EINVAL;
263
264         message = kzalloc(sizeof(struct hidpp_report), GFP_KERNEL);
265         if (!message)
266                 return -ENOMEM;
267
268         if (param_count > (HIDPP_REPORT_LONG_LENGTH - 4))
269                 message->report_id = REPORT_ID_HIDPP_VERY_LONG;
270         else
271                 message->report_id = REPORT_ID_HIDPP_LONG;
272         message->fap.feature_index = feat_index;
273         message->fap.funcindex_clientid = funcindex_clientid;
274         memcpy(&message->fap.params, params, param_count);
275
276         ret = hidpp_send_message_sync(hidpp, message, response);
277         kfree(message);
278         return ret;
279 }
280
281 static int hidpp_send_rap_command_sync(struct hidpp_device *hidpp_dev,
282         u8 report_id, u8 sub_id, u8 reg_address, u8 *params, int param_count,
283         struct hidpp_report *response)
284 {
285         struct hidpp_report *message;
286         int ret, max_count;
287
288         switch (report_id) {
289         case REPORT_ID_HIDPP_SHORT:
290                 max_count = HIDPP_REPORT_SHORT_LENGTH - 4;
291                 break;
292         case REPORT_ID_HIDPP_LONG:
293                 max_count = HIDPP_REPORT_LONG_LENGTH - 4;
294                 break;
295         case REPORT_ID_HIDPP_VERY_LONG:
296                 max_count = HIDPP_REPORT_VERY_LONG_LENGTH - 4;
297                 break;
298         default:
299                 return -EINVAL;
300         }
301
302         if (param_count > max_count)
303                 return -EINVAL;
304
305         message = kzalloc(sizeof(struct hidpp_report), GFP_KERNEL);
306         if (!message)
307                 return -ENOMEM;
308         message->report_id = report_id;
309         message->rap.sub_id = sub_id;
310         message->rap.reg_address = reg_address;
311         memcpy(&message->rap.params, params, param_count);
312
313         ret = hidpp_send_message_sync(hidpp_dev, message, response);
314         kfree(message);
315         return ret;
316 }
317
318 static void delayed_work_cb(struct work_struct *work)
319 {
320         struct hidpp_device *hidpp = container_of(work, struct hidpp_device,
321                                                         work);
322         hidpp_connect_event(hidpp);
323 }
324
325 static inline bool hidpp_match_answer(struct hidpp_report *question,
326                 struct hidpp_report *answer)
327 {
328         return (answer->fap.feature_index == question->fap.feature_index) &&
329            (answer->fap.funcindex_clientid == question->fap.funcindex_clientid);
330 }
331
332 static inline bool hidpp_match_error(struct hidpp_report *question,
333                 struct hidpp_report *answer)
334 {
335         return ((answer->rap.sub_id == HIDPP_ERROR) ||
336             (answer->fap.feature_index == HIDPP20_ERROR)) &&
337             (answer->fap.funcindex_clientid == question->fap.feature_index) &&
338             (answer->fap.params[0] == question->fap.funcindex_clientid);
339 }
340
341 static inline bool hidpp_report_is_connect_event(struct hidpp_report *report)
342 {
343         return (report->report_id == REPORT_ID_HIDPP_SHORT) &&
344                 (report->rap.sub_id == 0x41);
345 }
346
347 /**
348  * hidpp_prefix_name() prefixes the current given name with "Logitech ".
349  */
350 static void hidpp_prefix_name(char **name, int name_length)
351 {
352 #define PREFIX_LENGTH 9 /* "Logitech " */
353
354         int new_length;
355         char *new_name;
356
357         if (name_length > PREFIX_LENGTH &&
358             strncmp(*name, "Logitech ", PREFIX_LENGTH) == 0)
359                 /* The prefix has is already in the name */
360                 return;
361
362         new_length = PREFIX_LENGTH + name_length;
363         new_name = kzalloc(new_length, GFP_KERNEL);
364         if (!new_name)
365                 return;
366
367         snprintf(new_name, new_length, "Logitech %s", *name);
368
369         kfree(*name);
370
371         *name = new_name;
372 }
373
374 /* -------------------------------------------------------------------------- */
375 /* HIDP++ 1.0 commands                                                        */
376 /* -------------------------------------------------------------------------- */
377
378 #define HIDPP_SET_REGISTER                              0x80
379 #define HIDPP_GET_REGISTER                              0x81
380 #define HIDPP_SET_LONG_REGISTER                         0x82
381 #define HIDPP_GET_LONG_REGISTER                         0x83
382
383 #define HIDPP_REG_PAIRING_INFORMATION                   0xB5
384 #define DEVICE_NAME                                     0x40
385
386 static char *hidpp_get_unifying_name(struct hidpp_device *hidpp_dev)
387 {
388         struct hidpp_report response;
389         int ret;
390         /* hid-logitech-dj is in charge of setting the right device index */
391         u8 params[1] = { DEVICE_NAME };
392         char *name;
393         int len;
394
395         ret = hidpp_send_rap_command_sync(hidpp_dev,
396                                         REPORT_ID_HIDPP_SHORT,
397                                         HIDPP_GET_LONG_REGISTER,
398                                         HIDPP_REG_PAIRING_INFORMATION,
399                                         params, 1, &response);
400         if (ret)
401                 return NULL;
402
403         len = response.rap.params[1];
404
405         if (2 + len > sizeof(response.rap.params))
406                 return NULL;
407
408         name = kzalloc(len + 1, GFP_KERNEL);
409         if (!name)
410                 return NULL;
411
412         memcpy(name, &response.rap.params[2], len);
413
414         /* include the terminating '\0' */
415         hidpp_prefix_name(&name, len + 1);
416
417         return name;
418 }
419
420 /* -------------------------------------------------------------------------- */
421 /* 0x0000: Root                                                               */
422 /* -------------------------------------------------------------------------- */
423
424 #define HIDPP_PAGE_ROOT                                 0x0000
425 #define HIDPP_PAGE_ROOT_IDX                             0x00
426
427 #define CMD_ROOT_GET_FEATURE                            0x01
428 #define CMD_ROOT_GET_PROTOCOL_VERSION                   0x11
429
430 static int hidpp_root_get_feature(struct hidpp_device *hidpp, u16 feature,
431         u8 *feature_index, u8 *feature_type)
432 {
433         struct hidpp_report response;
434         int ret;
435         u8 params[2] = { feature >> 8, feature & 0x00FF };
436
437         ret = hidpp_send_fap_command_sync(hidpp,
438                         HIDPP_PAGE_ROOT_IDX,
439                         CMD_ROOT_GET_FEATURE,
440                         params, 2, &response);
441         if (ret)
442                 return ret;
443
444         *feature_index = response.fap.params[0];
445         *feature_type = response.fap.params[1];
446
447         return ret;
448 }
449
450 static int hidpp_root_get_protocol_version(struct hidpp_device *hidpp)
451 {
452         const u8 ping_byte = 0x5a;
453         u8 ping_data[3] = { 0, 0, ping_byte };
454         struct hidpp_report response;
455         int ret;
456
457         ret = hidpp_send_rap_command_sync(hidpp,
458                         REPORT_ID_HIDPP_SHORT,
459                         HIDPP_PAGE_ROOT_IDX,
460                         CMD_ROOT_GET_PROTOCOL_VERSION,
461                         ping_data, sizeof(ping_data), &response);
462
463         if (ret == HIDPP_ERROR_INVALID_SUBID) {
464                 hidpp->protocol_major = 1;
465                 hidpp->protocol_minor = 0;
466                 return 0;
467         }
468
469         /* the device might not be connected */
470         if (ret == HIDPP_ERROR_RESOURCE_ERROR)
471                 return -EIO;
472
473         if (ret > 0) {
474                 hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
475                         __func__, ret);
476                 return -EPROTO;
477         }
478         if (ret)
479                 return ret;
480
481         if (response.rap.params[2] != ping_byte) {
482                 hid_err(hidpp->hid_dev, "%s: ping mismatch 0x%02x != 0x%02x\n",
483                         __func__, response.rap.params[2], ping_byte);
484                 return -EPROTO;
485         }
486
487         hidpp->protocol_major = response.rap.params[0];
488         hidpp->protocol_minor = response.rap.params[1];
489
490         return ret;
491 }
492
493 static bool hidpp_is_connected(struct hidpp_device *hidpp)
494 {
495         int ret;
496
497         ret = hidpp_root_get_protocol_version(hidpp);
498         if (!ret)
499                 hid_dbg(hidpp->hid_dev, "HID++ %u.%u device connected.\n",
500                         hidpp->protocol_major, hidpp->protocol_minor);
501         return ret == 0;
502 }
503
504 /* -------------------------------------------------------------------------- */
505 /* 0x0005: GetDeviceNameType                                                  */
506 /* -------------------------------------------------------------------------- */
507
508 #define HIDPP_PAGE_GET_DEVICE_NAME_TYPE                 0x0005
509
510 #define CMD_GET_DEVICE_NAME_TYPE_GET_COUNT              0x01
511 #define CMD_GET_DEVICE_NAME_TYPE_GET_DEVICE_NAME        0x11
512 #define CMD_GET_DEVICE_NAME_TYPE_GET_TYPE               0x21
513
514 static int hidpp_devicenametype_get_count(struct hidpp_device *hidpp,
515         u8 feature_index, u8 *nameLength)
516 {
517         struct hidpp_report response;
518         int ret;
519
520         ret = hidpp_send_fap_command_sync(hidpp, feature_index,
521                 CMD_GET_DEVICE_NAME_TYPE_GET_COUNT, NULL, 0, &response);
522
523         if (ret > 0) {
524                 hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
525                         __func__, ret);
526                 return -EPROTO;
527         }
528         if (ret)
529                 return ret;
530
531         *nameLength = response.fap.params[0];
532
533         return ret;
534 }
535
536 static int hidpp_devicenametype_get_device_name(struct hidpp_device *hidpp,
537         u8 feature_index, u8 char_index, char *device_name, int len_buf)
538 {
539         struct hidpp_report response;
540         int ret, i;
541         int count;
542
543         ret = hidpp_send_fap_command_sync(hidpp, feature_index,
544                 CMD_GET_DEVICE_NAME_TYPE_GET_DEVICE_NAME, &char_index, 1,
545                 &response);
546
547         if (ret > 0) {
548                 hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
549                         __func__, ret);
550                 return -EPROTO;
551         }
552         if (ret)
553                 return ret;
554
555         switch (response.report_id) {
556         case REPORT_ID_HIDPP_VERY_LONG:
557                 count = HIDPP_REPORT_VERY_LONG_LENGTH - 4;
558                 break;
559         case REPORT_ID_HIDPP_LONG:
560                 count = HIDPP_REPORT_LONG_LENGTH - 4;
561                 break;
562         case REPORT_ID_HIDPP_SHORT:
563                 count = HIDPP_REPORT_SHORT_LENGTH - 4;
564                 break;
565         default:
566                 return -EPROTO;
567         }
568
569         if (len_buf < count)
570                 count = len_buf;
571
572         for (i = 0; i < count; i++)
573                 device_name[i] = response.fap.params[i];
574
575         return count;
576 }
577
578 static char *hidpp_get_device_name(struct hidpp_device *hidpp)
579 {
580         u8 feature_type;
581         u8 feature_index;
582         u8 __name_length;
583         char *name;
584         unsigned index = 0;
585         int ret;
586
587         ret = hidpp_root_get_feature(hidpp, HIDPP_PAGE_GET_DEVICE_NAME_TYPE,
588                 &feature_index, &feature_type);
589         if (ret)
590                 return NULL;
591
592         ret = hidpp_devicenametype_get_count(hidpp, feature_index,
593                 &__name_length);
594         if (ret)
595                 return NULL;
596
597         name = kzalloc(__name_length + 1, GFP_KERNEL);
598         if (!name)
599                 return NULL;
600
601         while (index < __name_length) {
602                 ret = hidpp_devicenametype_get_device_name(hidpp,
603                         feature_index, index, name + index,
604                         __name_length - index);
605                 if (ret <= 0) {
606                         kfree(name);
607                         return NULL;
608                 }
609                 index += ret;
610         }
611
612         /* include the terminating '\0' */
613         hidpp_prefix_name(&name, __name_length + 1);
614
615         return name;
616 }
617
618 /* -------------------------------------------------------------------------- */
619 /* 0x6010: Touchpad FW items                                                  */
620 /* -------------------------------------------------------------------------- */
621
622 #define HIDPP_PAGE_TOUCHPAD_FW_ITEMS                    0x6010
623
624 #define CMD_TOUCHPAD_FW_ITEMS_SET                       0x10
625
626 struct hidpp_touchpad_fw_items {
627         uint8_t presence;
628         uint8_t desired_state;
629         uint8_t state;
630         uint8_t persistent;
631 };
632
633 /**
634  * send a set state command to the device by reading the current items->state
635  * field. items is then filled with the current state.
636  */
637 static int hidpp_touchpad_fw_items_set(struct hidpp_device *hidpp,
638                                        u8 feature_index,
639                                        struct hidpp_touchpad_fw_items *items)
640 {
641         struct hidpp_report response;
642         int ret;
643         u8 *params = (u8 *)response.fap.params;
644
645         ret = hidpp_send_fap_command_sync(hidpp, feature_index,
646                 CMD_TOUCHPAD_FW_ITEMS_SET, &items->state, 1, &response);
647
648         if (ret > 0) {
649                 hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
650                         __func__, ret);
651                 return -EPROTO;
652         }
653         if (ret)
654                 return ret;
655
656         items->presence = params[0];
657         items->desired_state = params[1];
658         items->state = params[2];
659         items->persistent = params[3];
660
661         return 0;
662 }
663
664 /* -------------------------------------------------------------------------- */
665 /* 0x6100: TouchPadRawXY                                                      */
666 /* -------------------------------------------------------------------------- */
667
668 #define HIDPP_PAGE_TOUCHPAD_RAW_XY                      0x6100
669
670 #define CMD_TOUCHPAD_GET_RAW_INFO                       0x01
671 #define CMD_TOUCHPAD_SET_RAW_REPORT_STATE               0x21
672
673 #define EVENT_TOUCHPAD_RAW_XY                           0x00
674
675 #define TOUCHPAD_RAW_XY_ORIGIN_LOWER_LEFT               0x01
676 #define TOUCHPAD_RAW_XY_ORIGIN_UPPER_LEFT               0x03
677
678 struct hidpp_touchpad_raw_info {
679         u16 x_size;
680         u16 y_size;
681         u8 z_range;
682         u8 area_range;
683         u8 timestamp_unit;
684         u8 maxcontacts;
685         u8 origin;
686         u16 res;
687 };
688
689 struct hidpp_touchpad_raw_xy_finger {
690         u8 contact_type;
691         u8 contact_status;
692         u16 x;
693         u16 y;
694         u8 z;
695         u8 area;
696         u8 finger_id;
697 };
698
699 struct hidpp_touchpad_raw_xy {
700         u16 timestamp;
701         struct hidpp_touchpad_raw_xy_finger fingers[2];
702         u8 spurious_flag;
703         u8 end_of_frame;
704         u8 finger_count;
705         u8 button;
706 };
707
708 static int hidpp_touchpad_get_raw_info(struct hidpp_device *hidpp,
709         u8 feature_index, struct hidpp_touchpad_raw_info *raw_info)
710 {
711         struct hidpp_report response;
712         int ret;
713         u8 *params = (u8 *)response.fap.params;
714
715         ret = hidpp_send_fap_command_sync(hidpp, feature_index,
716                 CMD_TOUCHPAD_GET_RAW_INFO, NULL, 0, &response);
717
718         if (ret > 0) {
719                 hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
720                         __func__, ret);
721                 return -EPROTO;
722         }
723         if (ret)
724                 return ret;
725
726         raw_info->x_size = get_unaligned_be16(&params[0]);
727         raw_info->y_size = get_unaligned_be16(&params[2]);
728         raw_info->z_range = params[4];
729         raw_info->area_range = params[5];
730         raw_info->maxcontacts = params[7];
731         raw_info->origin = params[8];
732         /* res is given in unit per inch */
733         raw_info->res = get_unaligned_be16(&params[13]) * 2 / 51;
734
735         return ret;
736 }
737
738 static int hidpp_touchpad_set_raw_report_state(struct hidpp_device *hidpp_dev,
739                 u8 feature_index, bool send_raw_reports,
740                 bool sensor_enhanced_settings)
741 {
742         struct hidpp_report response;
743
744         /*
745          * Params:
746          *   bit 0 - enable raw
747          *   bit 1 - 16bit Z, no area
748          *   bit 2 - enhanced sensitivity
749          *   bit 3 - width, height (4 bits each) instead of area
750          *   bit 4 - send raw + gestures (degrades smoothness)
751          *   remaining bits - reserved
752          */
753         u8 params = send_raw_reports | (sensor_enhanced_settings << 2);
754
755         return hidpp_send_fap_command_sync(hidpp_dev, feature_index,
756                 CMD_TOUCHPAD_SET_RAW_REPORT_STATE, &params, 1, &response);
757 }
758
759 static void hidpp_touchpad_touch_event(u8 *data,
760         struct hidpp_touchpad_raw_xy_finger *finger)
761 {
762         u8 x_m = data[0] << 2;
763         u8 y_m = data[2] << 2;
764
765         finger->x = x_m << 6 | data[1];
766         finger->y = y_m << 6 | data[3];
767
768         finger->contact_type = data[0] >> 6;
769         finger->contact_status = data[2] >> 6;
770
771         finger->z = data[4];
772         finger->area = data[5];
773         finger->finger_id = data[6] >> 4;
774 }
775
776 static void hidpp_touchpad_raw_xy_event(struct hidpp_device *hidpp_dev,
777                 u8 *data, struct hidpp_touchpad_raw_xy *raw_xy)
778 {
779         memset(raw_xy, 0, sizeof(struct hidpp_touchpad_raw_xy));
780         raw_xy->end_of_frame = data[8] & 0x01;
781         raw_xy->spurious_flag = (data[8] >> 1) & 0x01;
782         raw_xy->finger_count = data[15] & 0x0f;
783         raw_xy->button = (data[8] >> 2) & 0x01;
784
785         if (raw_xy->finger_count) {
786                 hidpp_touchpad_touch_event(&data[2], &raw_xy->fingers[0]);
787                 hidpp_touchpad_touch_event(&data[9], &raw_xy->fingers[1]);
788         }
789 }
790
791 /* -------------------------------------------------------------------------- */
792 /* 0x8123: Force feedback support                                             */
793 /* -------------------------------------------------------------------------- */
794
795 #define HIDPP_FF_GET_INFO               0x01
796 #define HIDPP_FF_RESET_ALL              0x11
797 #define HIDPP_FF_DOWNLOAD_EFFECT        0x21
798 #define HIDPP_FF_SET_EFFECT_STATE       0x31
799 #define HIDPP_FF_DESTROY_EFFECT         0x41
800 #define HIDPP_FF_GET_APERTURE           0x51
801 #define HIDPP_FF_SET_APERTURE           0x61
802 #define HIDPP_FF_GET_GLOBAL_GAINS       0x71
803 #define HIDPP_FF_SET_GLOBAL_GAINS       0x81
804
805 #define HIDPP_FF_EFFECT_STATE_GET       0x00
806 #define HIDPP_FF_EFFECT_STATE_STOP      0x01
807 #define HIDPP_FF_EFFECT_STATE_PLAY      0x02
808 #define HIDPP_FF_EFFECT_STATE_PAUSE     0x03
809
810 #define HIDPP_FF_EFFECT_CONSTANT        0x00
811 #define HIDPP_FF_EFFECT_PERIODIC_SINE           0x01
812 #define HIDPP_FF_EFFECT_PERIODIC_SQUARE         0x02
813 #define HIDPP_FF_EFFECT_PERIODIC_TRIANGLE       0x03
814 #define HIDPP_FF_EFFECT_PERIODIC_SAWTOOTHUP     0x04
815 #define HIDPP_FF_EFFECT_PERIODIC_SAWTOOTHDOWN   0x05
816 #define HIDPP_FF_EFFECT_SPRING          0x06
817 #define HIDPP_FF_EFFECT_DAMPER          0x07
818 #define HIDPP_FF_EFFECT_FRICTION        0x08
819 #define HIDPP_FF_EFFECT_INERTIA         0x09
820 #define HIDPP_FF_EFFECT_RAMP            0x0A
821
822 #define HIDPP_FF_EFFECT_AUTOSTART       0x80
823
824 #define HIDPP_FF_EFFECTID_NONE          -1
825 #define HIDPP_FF_EFFECTID_AUTOCENTER    -2
826
827 #define HIDPP_FF_MAX_PARAMS     20
828 #define HIDPP_FF_RESERVED_SLOTS 1
829
830 struct hidpp_ff_private_data {
831         struct hidpp_device *hidpp;
832         u8 feature_index;
833         u8 version;
834         u16 gain;
835         s16 range;
836         u8 slot_autocenter;
837         u8 num_effects;
838         int *effect_ids;
839         struct workqueue_struct *wq;
840         atomic_t workqueue_size;
841 };
842
843 struct hidpp_ff_work_data {
844         struct work_struct work;
845         struct hidpp_ff_private_data *data;
846         int effect_id;
847         u8 command;
848         u8 params[HIDPP_FF_MAX_PARAMS];
849         u8 size;
850 };
851
852 static const signed short hiddpp_ff_effects[] = {
853         FF_CONSTANT,
854         FF_PERIODIC,
855         FF_SINE,
856         FF_SQUARE,
857         FF_SAW_UP,
858         FF_SAW_DOWN,
859         FF_TRIANGLE,
860         FF_SPRING,
861         FF_DAMPER,
862         FF_AUTOCENTER,
863         FF_GAIN,
864         -1
865 };
866
867 static const signed short hiddpp_ff_effects_v2[] = {
868         FF_RAMP,
869         FF_FRICTION,
870         FF_INERTIA,
871         -1
872 };
873
874 static const u8 HIDPP_FF_CONDITION_CMDS[] = {
875         HIDPP_FF_EFFECT_SPRING,
876         HIDPP_FF_EFFECT_FRICTION,
877         HIDPP_FF_EFFECT_DAMPER,
878         HIDPP_FF_EFFECT_INERTIA
879 };
880
881 static const char *HIDPP_FF_CONDITION_NAMES[] = {
882         "spring",
883         "friction",
884         "damper",
885         "inertia"
886 };
887
888
889 static u8 hidpp_ff_find_effect(struct hidpp_ff_private_data *data, int effect_id)
890 {
891         int i;
892
893         for (i = 0; i < data->num_effects; i++)
894                 if (data->effect_ids[i] == effect_id)
895                         return i+1;
896
897         return 0;
898 }
899
900 static void hidpp_ff_work_handler(struct work_struct *w)
901 {
902         struct hidpp_ff_work_data *wd = container_of(w, struct hidpp_ff_work_data, work);
903         struct hidpp_ff_private_data *data = wd->data;
904         struct hidpp_report response;
905         u8 slot;
906         int ret;
907
908         /* add slot number if needed */
909         switch (wd->effect_id) {
910         case HIDPP_FF_EFFECTID_AUTOCENTER:
911                 wd->params[0] = data->slot_autocenter;
912                 break;
913         case HIDPP_FF_EFFECTID_NONE:
914                 /* leave slot as zero */
915                 break;
916         default:
917                 /* find current slot for effect */
918                 wd->params[0] = hidpp_ff_find_effect(data, wd->effect_id);
919                 break;
920         }
921
922         /* send command and wait for reply */
923         ret = hidpp_send_fap_command_sync(data->hidpp, data->feature_index,
924                 wd->command, wd->params, wd->size, &response);
925
926         if (ret) {
927                 hid_err(data->hidpp->hid_dev, "Failed to send command to device!\n");
928                 goto out;
929         }
930
931         /* parse return data */
932         switch (wd->command) {
933         case HIDPP_FF_DOWNLOAD_EFFECT:
934                 slot = response.fap.params[0];
935                 if (slot > 0 && slot <= data->num_effects) {
936                         if (wd->effect_id >= 0)
937                                 /* regular effect uploaded */
938                                 data->effect_ids[slot-1] = wd->effect_id;
939                         else if (wd->effect_id >= HIDPP_FF_EFFECTID_AUTOCENTER)
940                                 /* autocenter spring uploaded */
941                                 data->slot_autocenter = slot;
942                 }
943                 break;
944         case HIDPP_FF_DESTROY_EFFECT:
945                 if (wd->effect_id >= 0)
946                         /* regular effect destroyed */
947                         data->effect_ids[wd->params[0]-1] = -1;
948                 else if (wd->effect_id >= HIDPP_FF_EFFECTID_AUTOCENTER)
949                         /* autocenter spring destoyed */
950                         data->slot_autocenter = 0;
951                 break;
952         case HIDPP_FF_SET_GLOBAL_GAINS:
953                 data->gain = (wd->params[0] << 8) + wd->params[1];
954                 break;
955         case HIDPP_FF_SET_APERTURE:
956                 data->range = (wd->params[0] << 8) + wd->params[1];
957                 break;
958         default:
959                 /* no action needed */
960                 break;
961         }
962
963 out:
964         atomic_dec(&data->workqueue_size);
965         kfree(wd);
966 }
967
968 static int hidpp_ff_queue_work(struct hidpp_ff_private_data *data, int effect_id, u8 command, u8 *params, u8 size)
969 {
970         struct hidpp_ff_work_data *wd = kzalloc(sizeof(*wd), GFP_KERNEL);
971         int s;
972
973         if (!wd)
974                 return -ENOMEM;
975
976         INIT_WORK(&wd->work, hidpp_ff_work_handler);
977
978         wd->data = data;
979         wd->effect_id = effect_id;
980         wd->command = command;
981         wd->size = size;
982         memcpy(wd->params, params, size);
983
984         atomic_inc(&data->workqueue_size);
985         queue_work(data->wq, &wd->work);
986
987         /* warn about excessive queue size */
988         s = atomic_read(&data->workqueue_size);
989         if (s >= 20 && s % 20 == 0)
990                 hid_warn(data->hidpp->hid_dev, "Force feedback command queue contains %d commands, causing substantial delays!", s);
991
992         return 0;
993 }
994
995 static int hidpp_ff_upload_effect(struct input_dev *dev, struct ff_effect *effect, struct ff_effect *old)
996 {
997         struct hidpp_ff_private_data *data = dev->ff->private;
998         u8 params[20];
999         u8 size;
1000         int force;
1001
1002         /* set common parameters */
1003         params[2] = effect->replay.length >> 8;
1004         params[3] = effect->replay.length & 255;
1005         params[4] = effect->replay.delay >> 8;
1006         params[5] = effect->replay.delay & 255;
1007
1008         switch (effect->type) {
1009         case FF_CONSTANT:
1010                 force = (effect->u.constant.level * fixp_sin16((effect->direction * 360) >> 16)) >> 15;
1011                 params[1] = HIDPP_FF_EFFECT_CONSTANT;
1012                 params[6] = force >> 8;
1013                 params[7] = force & 255;
1014                 params[8] = effect->u.constant.envelope.attack_level >> 7;
1015                 params[9] = effect->u.constant.envelope.attack_length >> 8;
1016                 params[10] = effect->u.constant.envelope.attack_length & 255;
1017                 params[11] = effect->u.constant.envelope.fade_level >> 7;
1018                 params[12] = effect->u.constant.envelope.fade_length >> 8;
1019                 params[13] = effect->u.constant.envelope.fade_length & 255;
1020                 size = 14;
1021                 dbg_hid("Uploading constant force level=%d in dir %d = %d\n",
1022                                 effect->u.constant.level,
1023                                 effect->direction, force);
1024                 dbg_hid("          envelope attack=(%d, %d ms) fade=(%d, %d ms)\n",
1025                                 effect->u.constant.envelope.attack_level,
1026                                 effect->u.constant.envelope.attack_length,
1027                                 effect->u.constant.envelope.fade_level,
1028                                 effect->u.constant.envelope.fade_length);
1029                 break;
1030         case FF_PERIODIC:
1031         {
1032                 switch (effect->u.periodic.waveform) {
1033                 case FF_SINE:
1034                         params[1] = HIDPP_FF_EFFECT_PERIODIC_SINE;
1035                         break;
1036                 case FF_SQUARE:
1037                         params[1] = HIDPP_FF_EFFECT_PERIODIC_SQUARE;
1038                         break;
1039                 case FF_SAW_UP:
1040                         params[1] = HIDPP_FF_EFFECT_PERIODIC_SAWTOOTHUP;
1041                         break;
1042                 case FF_SAW_DOWN:
1043                         params[1] = HIDPP_FF_EFFECT_PERIODIC_SAWTOOTHDOWN;
1044                         break;
1045                 case FF_TRIANGLE:
1046                         params[1] = HIDPP_FF_EFFECT_PERIODIC_TRIANGLE;
1047                         break;
1048                 default:
1049                         hid_err(data->hidpp->hid_dev, "Unexpected periodic waveform type %i!\n", effect->u.periodic.waveform);
1050                         return -EINVAL;
1051                 }
1052                 force = (effect->u.periodic.magnitude * fixp_sin16((effect->direction * 360) >> 16)) >> 15;
1053                 params[6] = effect->u.periodic.magnitude >> 8;
1054                 params[7] = effect->u.periodic.magnitude & 255;
1055                 params[8] = effect->u.periodic.offset >> 8;
1056                 params[9] = effect->u.periodic.offset & 255;
1057                 params[10] = effect->u.periodic.period >> 8;
1058                 params[11] = effect->u.periodic.period & 255;
1059                 params[12] = effect->u.periodic.phase >> 8;
1060                 params[13] = effect->u.periodic.phase & 255;
1061                 params[14] = effect->u.periodic.envelope.attack_level >> 7;
1062                 params[15] = effect->u.periodic.envelope.attack_length >> 8;
1063                 params[16] = effect->u.periodic.envelope.attack_length & 255;
1064                 params[17] = effect->u.periodic.envelope.fade_level >> 7;
1065                 params[18] = effect->u.periodic.envelope.fade_length >> 8;
1066                 params[19] = effect->u.periodic.envelope.fade_length & 255;
1067                 size = 20;
1068                 dbg_hid("Uploading periodic force mag=%d/dir=%d, offset=%d, period=%d ms, phase=%d\n",
1069                                 effect->u.periodic.magnitude, effect->direction,
1070                                 effect->u.periodic.offset,
1071                                 effect->u.periodic.period,
1072                                 effect->u.periodic.phase);
1073                 dbg_hid("          envelope attack=(%d, %d ms) fade=(%d, %d ms)\n",
1074                                 effect->u.periodic.envelope.attack_level,
1075                                 effect->u.periodic.envelope.attack_length,
1076                                 effect->u.periodic.envelope.fade_level,
1077                                 effect->u.periodic.envelope.fade_length);
1078                 break;
1079         }
1080         case FF_RAMP:
1081                 params[1] = HIDPP_FF_EFFECT_RAMP;
1082                 force = (effect->u.ramp.start_level * fixp_sin16((effect->direction * 360) >> 16)) >> 15;
1083                 params[6] = force >> 8;
1084                 params[7] = force & 255;
1085                 force = (effect->u.ramp.end_level * fixp_sin16((effect->direction * 360) >> 16)) >> 15;
1086                 params[8] = force >> 8;
1087                 params[9] = force & 255;
1088                 params[10] = effect->u.ramp.envelope.attack_level >> 7;
1089                 params[11] = effect->u.ramp.envelope.attack_length >> 8;
1090                 params[12] = effect->u.ramp.envelope.attack_length & 255;
1091                 params[13] = effect->u.ramp.envelope.fade_level >> 7;
1092                 params[14] = effect->u.ramp.envelope.fade_length >> 8;
1093                 params[15] = effect->u.ramp.envelope.fade_length & 255;
1094                 size = 16;
1095                 dbg_hid("Uploading ramp force level=%d -> %d in dir %d = %d\n",
1096                                 effect->u.ramp.start_level,
1097                                 effect->u.ramp.end_level,
1098                                 effect->direction, force);
1099                 dbg_hid("          envelope attack=(%d, %d ms) fade=(%d, %d ms)\n",
1100                                 effect->u.ramp.envelope.attack_level,
1101                                 effect->u.ramp.envelope.attack_length,
1102                                 effect->u.ramp.envelope.fade_level,
1103                                 effect->u.ramp.envelope.fade_length);
1104                 break;
1105         case FF_FRICTION:
1106         case FF_INERTIA:
1107         case FF_SPRING:
1108         case FF_DAMPER:
1109                 params[1] = HIDPP_FF_CONDITION_CMDS[effect->type - FF_SPRING];
1110                 params[6] = effect->u.condition[0].left_saturation >> 9;
1111                 params[7] = (effect->u.condition[0].left_saturation >> 1) & 255;
1112                 params[8] = effect->u.condition[0].left_coeff >> 8;
1113                 params[9] = effect->u.condition[0].left_coeff & 255;
1114                 params[10] = effect->u.condition[0].deadband >> 9;
1115                 params[11] = (effect->u.condition[0].deadband >> 1) & 255;
1116                 params[12] = effect->u.condition[0].center >> 8;
1117                 params[13] = effect->u.condition[0].center & 255;
1118                 params[14] = effect->u.condition[0].right_coeff >> 8;
1119                 params[15] = effect->u.condition[0].right_coeff & 255;
1120                 params[16] = effect->u.condition[0].right_saturation >> 9;
1121                 params[17] = (effect->u.condition[0].right_saturation >> 1) & 255;
1122                 size = 18;
1123                 dbg_hid("Uploading %s force left coeff=%d, left sat=%d, right coeff=%d, right sat=%d\n",
1124                                 HIDPP_FF_CONDITION_NAMES[effect->type - FF_SPRING],
1125                                 effect->u.condition[0].left_coeff,
1126                                 effect->u.condition[0].left_saturation,
1127                                 effect->u.condition[0].right_coeff,
1128                                 effect->u.condition[0].right_saturation);
1129                 dbg_hid("          deadband=%d, center=%d\n",
1130                                 effect->u.condition[0].deadband,
1131                                 effect->u.condition[0].center);
1132                 break;
1133         default:
1134                 hid_err(data->hidpp->hid_dev, "Unexpected force type %i!\n", effect->type);
1135                 return -EINVAL;
1136         }
1137
1138         return hidpp_ff_queue_work(data, effect->id, HIDPP_FF_DOWNLOAD_EFFECT, params, size);
1139 }
1140
1141 static int hidpp_ff_playback(struct input_dev *dev, int effect_id, int value)
1142 {
1143         struct hidpp_ff_private_data *data = dev->ff->private;
1144         u8 params[2];
1145
1146         params[1] = value ? HIDPP_FF_EFFECT_STATE_PLAY : HIDPP_FF_EFFECT_STATE_STOP;
1147
1148         dbg_hid("St%sing playback of effect %d.\n", value?"art":"opp", effect_id);
1149
1150         return hidpp_ff_queue_work(data, effect_id, HIDPP_FF_SET_EFFECT_STATE, params, ARRAY_SIZE(params));
1151 }
1152
1153 static int hidpp_ff_erase_effect(struct input_dev *dev, int effect_id)
1154 {
1155         struct hidpp_ff_private_data *data = dev->ff->private;
1156         u8 slot = 0;
1157
1158         dbg_hid("Erasing effect %d.\n", effect_id);
1159
1160         return hidpp_ff_queue_work(data, effect_id, HIDPP_FF_DESTROY_EFFECT, &slot, 1);
1161 }
1162
1163 static void hidpp_ff_set_autocenter(struct input_dev *dev, u16 magnitude)
1164 {
1165         struct hidpp_ff_private_data *data = dev->ff->private;
1166         u8 params[18];
1167
1168         dbg_hid("Setting autocenter to %d.\n", magnitude);
1169
1170         /* start a standard spring effect */
1171         params[1] = HIDPP_FF_EFFECT_SPRING | HIDPP_FF_EFFECT_AUTOSTART;
1172         /* zero delay and duration */
1173         params[2] = params[3] = params[4] = params[5] = 0;
1174         /* set coeff to 25% of saturation */
1175         params[8] = params[14] = magnitude >> 11;
1176         params[9] = params[15] = (magnitude >> 3) & 255;
1177         params[6] = params[16] = magnitude >> 9;
1178         params[7] = params[17] = (magnitude >> 1) & 255;
1179         /* zero deadband and center */
1180         params[10] = params[11] = params[12] = params[13] = 0;
1181
1182         hidpp_ff_queue_work(data, HIDPP_FF_EFFECTID_AUTOCENTER, HIDPP_FF_DOWNLOAD_EFFECT, params, ARRAY_SIZE(params));
1183 }
1184
1185 static void hidpp_ff_set_gain(struct input_dev *dev, u16 gain)
1186 {
1187         struct hidpp_ff_private_data *data = dev->ff->private;
1188         u8 params[4];
1189
1190         dbg_hid("Setting gain to %d.\n", gain);
1191
1192         params[0] = gain >> 8;
1193         params[1] = gain & 255;
1194         params[2] = 0; /* no boost */
1195         params[3] = 0;
1196
1197         hidpp_ff_queue_work(data, HIDPP_FF_EFFECTID_NONE, HIDPP_FF_SET_GLOBAL_GAINS, params, ARRAY_SIZE(params));
1198 }
1199
1200 static ssize_t hidpp_ff_range_show(struct device *dev, struct device_attribute *attr, char *buf)
1201 {
1202         struct hid_device *hid = to_hid_device(dev);
1203         struct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list);
1204         struct input_dev *idev = hidinput->input;
1205         struct hidpp_ff_private_data *data = idev->ff->private;
1206
1207         return scnprintf(buf, PAGE_SIZE, "%u\n", data->range);
1208 }
1209
1210 static ssize_t hidpp_ff_range_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
1211 {
1212         struct hid_device *hid = to_hid_device(dev);
1213         struct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list);
1214         struct input_dev *idev = hidinput->input;
1215         struct hidpp_ff_private_data *data = idev->ff->private;
1216         u8 params[2];
1217         int range = simple_strtoul(buf, NULL, 10);
1218
1219         range = clamp(range, 180, 900);
1220
1221         params[0] = range >> 8;
1222         params[1] = range & 0x00FF;
1223
1224         hidpp_ff_queue_work(data, -1, HIDPP_FF_SET_APERTURE, params, ARRAY_SIZE(params));
1225
1226         return count;
1227 }
1228
1229 static DEVICE_ATTR(range, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH, hidpp_ff_range_show, hidpp_ff_range_store);
1230
1231 static void hidpp_ff_destroy(struct ff_device *ff)
1232 {
1233         struct hidpp_ff_private_data *data = ff->private;
1234
1235         kfree(data->effect_ids);
1236 }
1237
1238 static int hidpp_ff_init(struct hidpp_device *hidpp, u8 feature_index)
1239 {
1240         struct hid_device *hid = hidpp->hid_dev;
1241         struct hid_input *hidinput;
1242         struct input_dev *dev;
1243         const struct usb_device_descriptor *udesc = &(hid_to_usb_dev(hid)->descriptor);
1244         const u16 bcdDevice = le16_to_cpu(udesc->bcdDevice);
1245         struct ff_device *ff;
1246         struct hidpp_report response;
1247         struct hidpp_ff_private_data *data;
1248         int error, j, num_slots;
1249         u8 version;
1250
1251         if (list_empty(&hid->inputs)) {
1252                 hid_err(hid, "no inputs found\n");
1253                 return -ENODEV;
1254         }
1255         hidinput = list_entry(hid->inputs.next, struct hid_input, list);
1256         dev = hidinput->input;
1257
1258         if (!dev) {
1259                 hid_err(hid, "Struct input_dev not set!\n");
1260                 return -EINVAL;
1261         }
1262
1263         /* Get firmware release */
1264         version = bcdDevice & 255;
1265
1266         /* Set supported force feedback capabilities */
1267         for (j = 0; hiddpp_ff_effects[j] >= 0; j++)
1268                 set_bit(hiddpp_ff_effects[j], dev->ffbit);
1269         if (version > 1)
1270                 for (j = 0; hiddpp_ff_effects_v2[j] >= 0; j++)
1271                         set_bit(hiddpp_ff_effects_v2[j], dev->ffbit);
1272
1273         /* Read number of slots available in device */
1274         error = hidpp_send_fap_command_sync(hidpp, feature_index,
1275                 HIDPP_FF_GET_INFO, NULL, 0, &response);
1276         if (error) {
1277                 if (error < 0)
1278                         return error;
1279                 hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
1280                         __func__, error);
1281                 return -EPROTO;
1282         }
1283
1284         num_slots = response.fap.params[0] - HIDPP_FF_RESERVED_SLOTS;
1285
1286         error = input_ff_create(dev, num_slots);
1287
1288         if (error) {
1289                 hid_err(dev, "Failed to create FF device!\n");
1290                 return error;
1291         }
1292
1293         data = kzalloc(sizeof(*data), GFP_KERNEL);
1294         if (!data)
1295                 return -ENOMEM;
1296         data->effect_ids = kcalloc(num_slots, sizeof(int), GFP_KERNEL);
1297         if (!data->effect_ids) {
1298                 kfree(data);
1299                 return -ENOMEM;
1300         }
1301         data->wq = create_singlethread_workqueue("hidpp-ff-sendqueue");
1302         if (!data->wq) {
1303                 kfree(data->effect_ids);
1304                 kfree(data);
1305                 return -ENOMEM;
1306         }
1307
1308         data->hidpp = hidpp;
1309         data->feature_index = feature_index;
1310         data->version = version;
1311         data->slot_autocenter = 0;
1312         data->num_effects = num_slots;
1313         for (j = 0; j < num_slots; j++)
1314                 data->effect_ids[j] = -1;
1315
1316         ff = dev->ff;
1317         ff->private = data;
1318
1319         ff->upload = hidpp_ff_upload_effect;
1320         ff->erase = hidpp_ff_erase_effect;
1321         ff->playback = hidpp_ff_playback;
1322         ff->set_gain = hidpp_ff_set_gain;
1323         ff->set_autocenter = hidpp_ff_set_autocenter;
1324         ff->destroy = hidpp_ff_destroy;
1325
1326
1327         /* reset all forces */
1328         error = hidpp_send_fap_command_sync(hidpp, feature_index,
1329                 HIDPP_FF_RESET_ALL, NULL, 0, &response);
1330
1331         /* Read current Range */
1332         error = hidpp_send_fap_command_sync(hidpp, feature_index,
1333                 HIDPP_FF_GET_APERTURE, NULL, 0, &response);
1334         if (error)
1335                 hid_warn(hidpp->hid_dev, "Failed to read range from device!\n");
1336         data->range = error ? 900 : get_unaligned_be16(&response.fap.params[0]);
1337
1338         /* Create sysfs interface */
1339         error = device_create_file(&(hidpp->hid_dev->dev), &dev_attr_range);
1340         if (error)
1341                 hid_warn(hidpp->hid_dev, "Unable to create sysfs interface for \"range\", errno %d!\n", error);
1342
1343         /* Read the current gain values */
1344         error = hidpp_send_fap_command_sync(hidpp, feature_index,
1345                 HIDPP_FF_GET_GLOBAL_GAINS, NULL, 0, &response);
1346         if (error)
1347                 hid_warn(hidpp->hid_dev, "Failed to read gain values from device!\n");
1348         data->gain = error ? 0xffff : get_unaligned_be16(&response.fap.params[0]);
1349         /* ignore boost value at response.fap.params[2] */
1350
1351         /* init the hardware command queue */
1352         atomic_set(&data->workqueue_size, 0);
1353
1354         /* initialize with zero autocenter to get wheel in usable state */
1355         hidpp_ff_set_autocenter(dev, 0);
1356
1357         hid_info(hid, "Force feeback support loaded (firmware release %d).\n", version);
1358
1359         return 0;
1360 }
1361
1362 static int hidpp_ff_deinit(struct hid_device *hid)
1363 {
1364         struct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list);
1365         struct input_dev *dev = hidinput->input;
1366         struct hidpp_ff_private_data *data;
1367
1368         if (!dev) {
1369                 hid_err(hid, "Struct input_dev not found!\n");
1370                 return -EINVAL;
1371         }
1372
1373         hid_info(hid, "Unloading HID++ force feedback.\n");
1374         data = dev->ff->private;
1375         if (!data) {
1376                 hid_err(hid, "Private data not found!\n");
1377                 return -EINVAL;
1378         }
1379
1380         destroy_workqueue(data->wq);
1381         device_remove_file(&hid->dev, &dev_attr_range);
1382
1383         return 0;
1384 }
1385
1386
1387 /* ************************************************************************** */
1388 /*                                                                            */
1389 /* Device Support                                                             */
1390 /*                                                                            */
1391 /* ************************************************************************** */
1392
1393 /* -------------------------------------------------------------------------- */
1394 /* Touchpad HID++ devices                                                     */
1395 /* -------------------------------------------------------------------------- */
1396
1397 #define WTP_MANUAL_RESOLUTION                           39
1398
1399 struct wtp_data {
1400         struct input_dev *input;
1401         u16 x_size, y_size;
1402         u8 finger_count;
1403         u8 mt_feature_index;
1404         u8 button_feature_index;
1405         u8 maxcontacts;
1406         bool flip_y;
1407         unsigned int resolution;
1408 };
1409
1410 static int wtp_input_mapping(struct hid_device *hdev, struct hid_input *hi,
1411                 struct hid_field *field, struct hid_usage *usage,
1412                 unsigned long **bit, int *max)
1413 {
1414         return -1;
1415 }
1416
1417 static void wtp_populate_input(struct hidpp_device *hidpp,
1418                 struct input_dev *input_dev, bool origin_is_hid_core)
1419 {
1420         struct wtp_data *wd = hidpp->private_data;
1421
1422         __set_bit(EV_ABS, input_dev->evbit);
1423         __set_bit(EV_KEY, input_dev->evbit);
1424         __clear_bit(EV_REL, input_dev->evbit);
1425         __clear_bit(EV_LED, input_dev->evbit);
1426
1427         input_set_abs_params(input_dev, ABS_MT_POSITION_X, 0, wd->x_size, 0, 0);
1428         input_abs_set_res(input_dev, ABS_MT_POSITION_X, wd->resolution);
1429         input_set_abs_params(input_dev, ABS_MT_POSITION_Y, 0, wd->y_size, 0, 0);
1430         input_abs_set_res(input_dev, ABS_MT_POSITION_Y, wd->resolution);
1431
1432         /* Max pressure is not given by the devices, pick one */
1433         input_set_abs_params(input_dev, ABS_MT_PRESSURE, 0, 50, 0, 0);
1434
1435         input_set_capability(input_dev, EV_KEY, BTN_LEFT);
1436
1437         if (hidpp->quirks & HIDPP_QUIRK_WTP_PHYSICAL_BUTTONS)
1438                 input_set_capability(input_dev, EV_KEY, BTN_RIGHT);
1439         else
1440                 __set_bit(INPUT_PROP_BUTTONPAD, input_dev->propbit);
1441
1442         input_mt_init_slots(input_dev, wd->maxcontacts, INPUT_MT_POINTER |
1443                 INPUT_MT_DROP_UNUSED);
1444
1445         wd->input = input_dev;
1446 }
1447
1448 static void wtp_touch_event(struct wtp_data *wd,
1449         struct hidpp_touchpad_raw_xy_finger *touch_report)
1450 {
1451         int slot;
1452
1453         if (!touch_report->finger_id || touch_report->contact_type)
1454                 /* no actual data */
1455                 return;
1456
1457         slot = input_mt_get_slot_by_key(wd->input, touch_report->finger_id);
1458
1459         input_mt_slot(wd->input, slot);
1460         input_mt_report_slot_state(wd->input, MT_TOOL_FINGER,
1461                                         touch_report->contact_status);
1462         if (touch_report->contact_status) {
1463                 input_event(wd->input, EV_ABS, ABS_MT_POSITION_X,
1464                                 touch_report->x);
1465                 input_event(wd->input, EV_ABS, ABS_MT_POSITION_Y,
1466                                 wd->flip_y ? wd->y_size - touch_report->y :
1467                                              touch_report->y);
1468                 input_event(wd->input, EV_ABS, ABS_MT_PRESSURE,
1469                                 touch_report->area);
1470         }
1471 }
1472
1473 static void wtp_send_raw_xy_event(struct hidpp_device *hidpp,
1474                 struct hidpp_touchpad_raw_xy *raw)
1475 {
1476         struct wtp_data *wd = hidpp->private_data;
1477         int i;
1478
1479         for (i = 0; i < 2; i++)
1480                 wtp_touch_event(wd, &(raw->fingers[i]));
1481
1482         if (raw->end_of_frame &&
1483             !(hidpp->quirks & HIDPP_QUIRK_WTP_PHYSICAL_BUTTONS))
1484                 input_event(wd->input, EV_KEY, BTN_LEFT, raw->button);
1485
1486         if (raw->end_of_frame || raw->finger_count <= 2) {
1487                 input_mt_sync_frame(wd->input);
1488                 input_sync(wd->input);
1489         }
1490 }
1491
1492 static int wtp_mouse_raw_xy_event(struct hidpp_device *hidpp, u8 *data)
1493 {
1494         struct wtp_data *wd = hidpp->private_data;
1495         u8 c1_area = ((data[7] & 0xf) * (data[7] & 0xf) +
1496                       (data[7] >> 4) * (data[7] >> 4)) / 2;
1497         u8 c2_area = ((data[13] & 0xf) * (data[13] & 0xf) +
1498                       (data[13] >> 4) * (data[13] >> 4)) / 2;
1499         struct hidpp_touchpad_raw_xy raw = {
1500                 .timestamp = data[1],
1501                 .fingers = {
1502                         {
1503                                 .contact_type = 0,
1504                                 .contact_status = !!data[7],
1505                                 .x = get_unaligned_le16(&data[3]),
1506                                 .y = get_unaligned_le16(&data[5]),
1507                                 .z = c1_area,
1508                                 .area = c1_area,
1509                                 .finger_id = data[2],
1510                         }, {
1511                                 .contact_type = 0,
1512                                 .contact_status = !!data[13],
1513                                 .x = get_unaligned_le16(&data[9]),
1514                                 .y = get_unaligned_le16(&data[11]),
1515                                 .z = c2_area,
1516                                 .area = c2_area,
1517                                 .finger_id = data[8],
1518                         }
1519                 },
1520                 .finger_count = wd->maxcontacts,
1521                 .spurious_flag = 0,
1522                 .end_of_frame = (data[0] >> 7) == 0,
1523                 .button = data[0] & 0x01,
1524         };
1525
1526         wtp_send_raw_xy_event(hidpp, &raw);
1527
1528         return 1;
1529 }
1530
1531 static int wtp_raw_event(struct hid_device *hdev, u8 *data, int size)
1532 {
1533         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
1534         struct wtp_data *wd = hidpp->private_data;
1535         struct hidpp_report *report = (struct hidpp_report *)data;
1536         struct hidpp_touchpad_raw_xy raw;
1537
1538         if (!wd || !wd->input)
1539                 return 1;
1540
1541         switch (data[0]) {
1542         case 0x02:
1543                 if (size < 2) {
1544                         hid_err(hdev, "Received HID report of bad size (%d)",
1545                                 size);
1546                         return 1;
1547                 }
1548                 if (hidpp->quirks & HIDPP_QUIRK_WTP_PHYSICAL_BUTTONS) {
1549                         input_event(wd->input, EV_KEY, BTN_LEFT,
1550                                         !!(data[1] & 0x01));
1551                         input_event(wd->input, EV_KEY, BTN_RIGHT,
1552                                         !!(data[1] & 0x02));
1553                         input_sync(wd->input);
1554                         return 0;
1555                 } else {
1556                         if (size < 21)
1557                                 return 1;
1558                         return wtp_mouse_raw_xy_event(hidpp, &data[7]);
1559                 }
1560         case REPORT_ID_HIDPP_LONG:
1561                 /* size is already checked in hidpp_raw_event. */
1562                 if ((report->fap.feature_index != wd->mt_feature_index) ||
1563                     (report->fap.funcindex_clientid != EVENT_TOUCHPAD_RAW_XY))
1564                         return 1;
1565                 hidpp_touchpad_raw_xy_event(hidpp, data + 4, &raw);
1566
1567                 wtp_send_raw_xy_event(hidpp, &raw);
1568                 return 0;
1569         }
1570
1571         return 0;
1572 }
1573
1574 static int wtp_get_config(struct hidpp_device *hidpp)
1575 {
1576         struct wtp_data *wd = hidpp->private_data;
1577         struct hidpp_touchpad_raw_info raw_info = {0};
1578         u8 feature_type;
1579         int ret;
1580
1581         ret = hidpp_root_get_feature(hidpp, HIDPP_PAGE_TOUCHPAD_RAW_XY,
1582                 &wd->mt_feature_index, &feature_type);
1583         if (ret)
1584                 /* means that the device is not powered up */
1585                 return ret;
1586
1587         ret = hidpp_touchpad_get_raw_info(hidpp, wd->mt_feature_index,
1588                 &raw_info);
1589         if (ret)
1590                 return ret;
1591
1592         wd->x_size = raw_info.x_size;
1593         wd->y_size = raw_info.y_size;
1594         wd->maxcontacts = raw_info.maxcontacts;
1595         wd->flip_y = raw_info.origin == TOUCHPAD_RAW_XY_ORIGIN_LOWER_LEFT;
1596         wd->resolution = raw_info.res;
1597         if (!wd->resolution)
1598                 wd->resolution = WTP_MANUAL_RESOLUTION;
1599
1600         return 0;
1601 }
1602
1603 static int wtp_allocate(struct hid_device *hdev, const struct hid_device_id *id)
1604 {
1605         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
1606         struct wtp_data *wd;
1607
1608         wd = devm_kzalloc(&hdev->dev, sizeof(struct wtp_data),
1609                         GFP_KERNEL);
1610         if (!wd)
1611                 return -ENOMEM;
1612
1613         hidpp->private_data = wd;
1614
1615         return 0;
1616 };
1617
1618 static int wtp_connect(struct hid_device *hdev, bool connected)
1619 {
1620         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
1621         struct wtp_data *wd = hidpp->private_data;
1622         int ret;
1623
1624         if (!connected)
1625                 return 0;
1626
1627         if (!wd->x_size) {
1628                 ret = wtp_get_config(hidpp);
1629                 if (ret) {
1630                         hid_err(hdev, "Can not get wtp config: %d\n", ret);
1631                         return ret;
1632                 }
1633         }
1634
1635         return hidpp_touchpad_set_raw_report_state(hidpp, wd->mt_feature_index,
1636                         true, true);
1637 }
1638
1639 /* ------------------------------------------------------------------------- */
1640 /* Logitech M560 devices                                                     */
1641 /* ------------------------------------------------------------------------- */
1642
1643 /*
1644  * Logitech M560 protocol overview
1645  *
1646  * The Logitech M560 mouse, is designed for windows 8. When the middle and/or
1647  * the sides buttons are pressed, it sends some keyboard keys events
1648  * instead of buttons ones.
1649  * To complicate things further, the middle button keys sequence
1650  * is different from the odd press and the even press.
1651  *
1652  * forward button -> Super_R
1653  * backward button -> Super_L+'d' (press only)
1654  * middle button -> 1st time: Alt_L+SuperL+XF86TouchpadOff (press only)
1655  *                  2nd time: left-click (press only)
1656  * NB: press-only means that when the button is pressed, the
1657  * KeyPress/ButtonPress and KeyRelease/ButtonRelease events are generated
1658  * together sequentially; instead when the button is released, no event is
1659  * generated !
1660  *
1661  * With the command
1662  *      10<xx>0a 3500af03 (where <xx> is the mouse id),
1663  * the mouse reacts differently:
1664  * - it never sends a keyboard key event
1665  * - for the three mouse button it sends:
1666  *      middle button               press   11<xx>0a 3500af00...
1667  *      side 1 button (forward)     press   11<xx>0a 3500b000...
1668  *      side 2 button (backward)    press   11<xx>0a 3500ae00...
1669  *      middle/side1/side2 button   release 11<xx>0a 35000000...
1670  */
1671
1672 static const u8 m560_config_parameter[] = {0x00, 0xaf, 0x03};
1673
1674 struct m560_private_data {
1675         struct input_dev *input;
1676 };
1677
1678 /* how buttons are mapped in the report */
1679 #define M560_MOUSE_BTN_LEFT             0x01
1680 #define M560_MOUSE_BTN_RIGHT            0x02
1681 #define M560_MOUSE_BTN_WHEEL_LEFT       0x08
1682 #define M560_MOUSE_BTN_WHEEL_RIGHT      0x10
1683
1684 #define M560_SUB_ID                     0x0a
1685 #define M560_BUTTON_MODE_REGISTER       0x35
1686
1687 static int m560_send_config_command(struct hid_device *hdev, bool connected)
1688 {
1689         struct hidpp_report response;
1690         struct hidpp_device *hidpp_dev;
1691
1692         hidpp_dev = hid_get_drvdata(hdev);
1693
1694         if (!connected)
1695                 return -ENODEV;
1696
1697         return hidpp_send_rap_command_sync(
1698                 hidpp_dev,
1699                 REPORT_ID_HIDPP_SHORT,
1700                 M560_SUB_ID,
1701                 M560_BUTTON_MODE_REGISTER,
1702                 (u8 *)m560_config_parameter,
1703                 sizeof(m560_config_parameter),
1704                 &response
1705         );
1706 }
1707
1708 static int m560_allocate(struct hid_device *hdev)
1709 {
1710         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
1711         struct m560_private_data *d;
1712
1713         d = devm_kzalloc(&hdev->dev, sizeof(struct m560_private_data),
1714                         GFP_KERNEL);
1715         if (!d)
1716                 return -ENOMEM;
1717
1718         hidpp->private_data = d;
1719
1720         return 0;
1721 };
1722
1723 static int m560_raw_event(struct hid_device *hdev, u8 *data, int size)
1724 {
1725         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
1726         struct m560_private_data *mydata = hidpp->private_data;
1727
1728         /* sanity check */
1729         if (!mydata || !mydata->input) {
1730                 hid_err(hdev, "error in parameter\n");
1731                 return -EINVAL;
1732         }
1733
1734         if (size < 7) {
1735                 hid_err(hdev, "error in report\n");
1736                 return 0;
1737         }
1738
1739         if (data[0] == REPORT_ID_HIDPP_LONG &&
1740             data[2] == M560_SUB_ID && data[6] == 0x00) {
1741                 /*
1742                  * m560 mouse report for middle, forward and backward button
1743                  *
1744                  * data[0] = 0x11
1745                  * data[1] = device-id
1746                  * data[2] = 0x0a
1747                  * data[5] = 0xaf -> middle
1748                  *           0xb0 -> forward
1749                  *           0xae -> backward
1750                  *           0x00 -> release all
1751                  * data[6] = 0x00
1752                  */
1753
1754                 switch (data[5]) {
1755                 case 0xaf:
1756                         input_report_key(mydata->input, BTN_MIDDLE, 1);
1757                         break;
1758                 case 0xb0:
1759                         input_report_key(mydata->input, BTN_FORWARD, 1);
1760                         break;
1761                 case 0xae:
1762                         input_report_key(mydata->input, BTN_BACK, 1);
1763                         break;
1764                 case 0x00:
1765                         input_report_key(mydata->input, BTN_BACK, 0);
1766                         input_report_key(mydata->input, BTN_FORWARD, 0);
1767                         input_report_key(mydata->input, BTN_MIDDLE, 0);
1768                         break;
1769                 default:
1770                         hid_err(hdev, "error in report\n");
1771                         return 0;
1772                 }
1773                 input_sync(mydata->input);
1774
1775         } else if (data[0] == 0x02) {
1776                 /*
1777                  * Logitech M560 mouse report
1778                  *
1779                  * data[0] = type (0x02)
1780                  * data[1..2] = buttons
1781                  * data[3..5] = xy
1782                  * data[6] = wheel
1783                  */
1784
1785                 int v;
1786
1787                 input_report_key(mydata->input, BTN_LEFT,
1788                         !!(data[1] & M560_MOUSE_BTN_LEFT));
1789                 input_report_key(mydata->input, BTN_RIGHT,
1790                         !!(data[1] & M560_MOUSE_BTN_RIGHT));
1791
1792                 if (data[1] & M560_MOUSE_BTN_WHEEL_LEFT)
1793                         input_report_rel(mydata->input, REL_HWHEEL, -1);
1794                 else if (data[1] & M560_MOUSE_BTN_WHEEL_RIGHT)
1795                         input_report_rel(mydata->input, REL_HWHEEL, 1);
1796
1797                 v = hid_snto32(hid_field_extract(hdev, data+3, 0, 12), 12);
1798                 input_report_rel(mydata->input, REL_X, v);
1799
1800                 v = hid_snto32(hid_field_extract(hdev, data+3, 12, 12), 12);
1801                 input_report_rel(mydata->input, REL_Y, v);
1802
1803                 v = hid_snto32(data[6], 8);
1804                 input_report_rel(mydata->input, REL_WHEEL, v);
1805
1806                 input_sync(mydata->input);
1807         }
1808
1809         return 1;
1810 }
1811
1812 static void m560_populate_input(struct hidpp_device *hidpp,
1813                 struct input_dev *input_dev, bool origin_is_hid_core)
1814 {
1815         struct m560_private_data *mydata = hidpp->private_data;
1816
1817         mydata->input = input_dev;
1818
1819         __set_bit(EV_KEY, mydata->input->evbit);
1820         __set_bit(BTN_MIDDLE, mydata->input->keybit);
1821         __set_bit(BTN_RIGHT, mydata->input->keybit);
1822         __set_bit(BTN_LEFT, mydata->input->keybit);
1823         __set_bit(BTN_BACK, mydata->input->keybit);
1824         __set_bit(BTN_FORWARD, mydata->input->keybit);
1825
1826         __set_bit(EV_REL, mydata->input->evbit);
1827         __set_bit(REL_X, mydata->input->relbit);
1828         __set_bit(REL_Y, mydata->input->relbit);
1829         __set_bit(REL_WHEEL, mydata->input->relbit);
1830         __set_bit(REL_HWHEEL, mydata->input->relbit);
1831 }
1832
1833 static int m560_input_mapping(struct hid_device *hdev, struct hid_input *hi,
1834                 struct hid_field *field, struct hid_usage *usage,
1835                 unsigned long **bit, int *max)
1836 {
1837         return -1;
1838 }
1839
1840 /* ------------------------------------------------------------------------- */
1841 /* Logitech K400 devices                                                     */
1842 /* ------------------------------------------------------------------------- */
1843
1844 /*
1845  * The Logitech K400 keyboard has an embedded touchpad which is seen
1846  * as a mouse from the OS point of view. There is a hardware shortcut to disable
1847  * tap-to-click but the setting is not remembered accross reset, annoying some
1848  * users.
1849  *
1850  * We can toggle this feature from the host by using the feature 0x6010:
1851  * Touchpad FW items
1852  */
1853
1854 struct k400_private_data {
1855         u8 feature_index;
1856 };
1857
1858 static int k400_disable_tap_to_click(struct hidpp_device *hidpp)
1859 {
1860         struct k400_private_data *k400 = hidpp->private_data;
1861         struct hidpp_touchpad_fw_items items = {};
1862         int ret;
1863         u8 feature_type;
1864
1865         if (!k400->feature_index) {
1866                 ret = hidpp_root_get_feature(hidpp,
1867                         HIDPP_PAGE_TOUCHPAD_FW_ITEMS,
1868                         &k400->feature_index, &feature_type);
1869                 if (ret)
1870                         /* means that the device is not powered up */
1871                         return ret;
1872         }
1873
1874         ret = hidpp_touchpad_fw_items_set(hidpp, k400->feature_index, &items);
1875         if (ret)
1876                 return ret;
1877
1878         return 0;
1879 }
1880
1881 static int k400_allocate(struct hid_device *hdev)
1882 {
1883         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
1884         struct k400_private_data *k400;
1885
1886         k400 = devm_kzalloc(&hdev->dev, sizeof(struct k400_private_data),
1887                             GFP_KERNEL);
1888         if (!k400)
1889                 return -ENOMEM;
1890
1891         hidpp->private_data = k400;
1892
1893         return 0;
1894 };
1895
1896 static int k400_connect(struct hid_device *hdev, bool connected)
1897 {
1898         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
1899
1900         if (!connected)
1901                 return 0;
1902
1903         if (!disable_tap_to_click)
1904                 return 0;
1905
1906         return k400_disable_tap_to_click(hidpp);
1907 }
1908
1909 /* ------------------------------------------------------------------------- */
1910 /* Logitech G920 Driving Force Racing Wheel for Xbox One                     */
1911 /* ------------------------------------------------------------------------- */
1912
1913 #define HIDPP_PAGE_G920_FORCE_FEEDBACK                  0x8123
1914
1915 static int g920_get_config(struct hidpp_device *hidpp)
1916 {
1917         u8 feature_type;
1918         u8 feature_index;
1919         int ret;
1920
1921         /* Find feature and store for later use */
1922         ret = hidpp_root_get_feature(hidpp, HIDPP_PAGE_G920_FORCE_FEEDBACK,
1923                 &feature_index, &feature_type);
1924         if (ret)
1925                 return ret;
1926
1927         ret = hidpp_ff_init(hidpp, feature_index);
1928         if (ret)
1929                 hid_warn(hidpp->hid_dev, "Unable to initialize force feedback support, errno %d\n",
1930                                 ret);
1931
1932         return 0;
1933 }
1934
1935 /* -------------------------------------------------------------------------- */
1936 /* Generic HID++ devices                                                      */
1937 /* -------------------------------------------------------------------------- */
1938
1939 static int hidpp_input_mapping(struct hid_device *hdev, struct hid_input *hi,
1940                 struct hid_field *field, struct hid_usage *usage,
1941                 unsigned long **bit, int *max)
1942 {
1943         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
1944
1945         if (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP)
1946                 return wtp_input_mapping(hdev, hi, field, usage, bit, max);
1947         else if (hidpp->quirks & HIDPP_QUIRK_CLASS_M560 &&
1948                         field->application != HID_GD_MOUSE)
1949                 return m560_input_mapping(hdev, hi, field, usage, bit, max);
1950
1951         return 0;
1952 }
1953
1954 static int hidpp_input_mapped(struct hid_device *hdev, struct hid_input *hi,
1955                 struct hid_field *field, struct hid_usage *usage,
1956                 unsigned long **bit, int *max)
1957 {
1958         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
1959
1960         /* Ensure that Logitech G920 is not given a default fuzz/flat value */
1961         if (hidpp->quirks & HIDPP_QUIRK_CLASS_G920) {
1962                 if (usage->type == EV_ABS && (usage->code == ABS_X ||
1963                                 usage->code == ABS_Y || usage->code == ABS_Z ||
1964                                 usage->code == ABS_RZ)) {
1965                         field->application = HID_GD_MULTIAXIS;
1966                 }
1967         }
1968
1969         return 0;
1970 }
1971
1972
1973 static void hidpp_populate_input(struct hidpp_device *hidpp,
1974                 struct input_dev *input, bool origin_is_hid_core)
1975 {
1976         if (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP)
1977                 wtp_populate_input(hidpp, input, origin_is_hid_core);
1978         else if (hidpp->quirks & HIDPP_QUIRK_CLASS_M560)
1979                 m560_populate_input(hidpp, input, origin_is_hid_core);
1980 }
1981
1982 static int hidpp_input_configured(struct hid_device *hdev,
1983                                 struct hid_input *hidinput)
1984 {
1985         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
1986         struct input_dev *input = hidinput->input;
1987
1988         hidpp_populate_input(hidpp, input, true);
1989
1990         return 0;
1991 }
1992
1993 static int hidpp_raw_hidpp_event(struct hidpp_device *hidpp, u8 *data,
1994                 int size)
1995 {
1996         struct hidpp_report *question = hidpp->send_receive_buf;
1997         struct hidpp_report *answer = hidpp->send_receive_buf;
1998         struct hidpp_report *report = (struct hidpp_report *)data;
1999
2000         /*
2001          * If the mutex is locked then we have a pending answer from a
2002          * previously sent command.
2003          */
2004         if (unlikely(mutex_is_locked(&hidpp->send_mutex))) {
2005                 /*
2006                  * Check for a correct hidpp20 answer or the corresponding
2007                  * error
2008                  */
2009                 if (hidpp_match_answer(question, report) ||
2010                                 hidpp_match_error(question, report)) {
2011                         *answer = *report;
2012                         hidpp->answer_available = true;
2013                         wake_up(&hidpp->wait);
2014                         /*
2015                          * This was an answer to a command that this driver sent
2016                          * We return 1 to hid-core to avoid forwarding the
2017                          * command upstream as it has been treated by the driver
2018                          */
2019
2020                         return 1;
2021                 }
2022         }
2023
2024         if (unlikely(hidpp_report_is_connect_event(report))) {
2025                 atomic_set(&hidpp->connected,
2026                                 !(report->rap.params[0] & (1 << 6)));
2027                 if ((hidpp->quirks & HIDPP_QUIRK_CONNECT_EVENTS) &&
2028                     (schedule_work(&hidpp->work) == 0))
2029                         dbg_hid("%s: connect event already queued\n", __func__);
2030                 return 1;
2031         }
2032
2033         return 0;
2034 }
2035
2036 static int hidpp_raw_event(struct hid_device *hdev, struct hid_report *report,
2037                 u8 *data, int size)
2038 {
2039         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2040         int ret = 0;
2041
2042         /* Generic HID++ processing. */
2043         switch (data[0]) {
2044         case REPORT_ID_HIDPP_VERY_LONG:
2045                 if (size != HIDPP_REPORT_VERY_LONG_LENGTH) {
2046                         hid_err(hdev, "received hid++ report of bad size (%d)",
2047                                 size);
2048                         return 1;
2049                 }
2050                 ret = hidpp_raw_hidpp_event(hidpp, data, size);
2051                 break;
2052         case REPORT_ID_HIDPP_LONG:
2053                 if (size != HIDPP_REPORT_LONG_LENGTH) {
2054                         hid_err(hdev, "received hid++ report of bad size (%d)",
2055                                 size);
2056                         return 1;
2057                 }
2058                 ret = hidpp_raw_hidpp_event(hidpp, data, size);
2059                 break;
2060         case REPORT_ID_HIDPP_SHORT:
2061                 if (size != HIDPP_REPORT_SHORT_LENGTH) {
2062                         hid_err(hdev, "received hid++ report of bad size (%d)",
2063                                 size);
2064                         return 1;
2065                 }
2066                 ret = hidpp_raw_hidpp_event(hidpp, data, size);
2067                 break;
2068         }
2069
2070         /* If no report is available for further processing, skip calling
2071          * raw_event of subclasses. */
2072         if (ret != 0)
2073                 return ret;
2074
2075         if (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP)
2076                 return wtp_raw_event(hdev, data, size);
2077         else if (hidpp->quirks & HIDPP_QUIRK_CLASS_M560)
2078                 return m560_raw_event(hdev, data, size);
2079
2080         return 0;
2081 }
2082
2083 static void hidpp_overwrite_name(struct hid_device *hdev, bool use_unifying)
2084 {
2085         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2086         char *name;
2087
2088         if (use_unifying)
2089                 /*
2090                  * the device is connected through an Unifying receiver, and
2091                  * might not be already connected.
2092                  * Ask the receiver for its name.
2093                  */
2094                 name = hidpp_get_unifying_name(hidpp);
2095         else
2096                 name = hidpp_get_device_name(hidpp);
2097
2098         if (!name) {
2099                 hid_err(hdev, "unable to retrieve the name of the device");
2100         } else {
2101                 dbg_hid("HID++: Got name: %s\n", name);
2102                 snprintf(hdev->name, sizeof(hdev->name), "%s", name);
2103         }
2104
2105         kfree(name);
2106 }
2107
2108 static int hidpp_input_open(struct input_dev *dev)
2109 {
2110         struct hid_device *hid = input_get_drvdata(dev);
2111
2112         return hid_hw_open(hid);
2113 }
2114
2115 static void hidpp_input_close(struct input_dev *dev)
2116 {
2117         struct hid_device *hid = input_get_drvdata(dev);
2118
2119         hid_hw_close(hid);
2120 }
2121
2122 static struct input_dev *hidpp_allocate_input(struct hid_device *hdev)
2123 {
2124         struct input_dev *input_dev = devm_input_allocate_device(&hdev->dev);
2125         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2126
2127         if (!input_dev)
2128                 return NULL;
2129
2130         input_set_drvdata(input_dev, hdev);
2131         input_dev->open = hidpp_input_open;
2132         input_dev->close = hidpp_input_close;
2133
2134         input_dev->name = hidpp->name;
2135         input_dev->phys = hdev->phys;
2136         input_dev->uniq = hdev->uniq;
2137         input_dev->id.bustype = hdev->bus;
2138         input_dev->id.vendor  = hdev->vendor;
2139         input_dev->id.product = hdev->product;
2140         input_dev->id.version = hdev->version;
2141         input_dev->dev.parent = &hdev->dev;
2142
2143         return input_dev;
2144 }
2145
2146 static void hidpp_connect_event(struct hidpp_device *hidpp)
2147 {
2148         struct hid_device *hdev = hidpp->hid_dev;
2149         int ret = 0;
2150         bool connected = atomic_read(&hidpp->connected);
2151         struct input_dev *input;
2152         char *name, *devm_name;
2153
2154         if (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP) {
2155                 ret = wtp_connect(hdev, connected);
2156                 if (ret)
2157                         return;
2158         } else if (hidpp->quirks & HIDPP_QUIRK_CLASS_M560) {
2159                 ret = m560_send_config_command(hdev, connected);
2160                 if (ret)
2161                         return;
2162         } else if (hidpp->quirks & HIDPP_QUIRK_CLASS_K400) {
2163                 ret = k400_connect(hdev, connected);
2164                 if (ret)
2165                         return;
2166         }
2167
2168         if (!connected || hidpp->delayed_input)
2169                 return;
2170
2171         /* the device is already connected, we can ask for its name and
2172          * protocol */
2173         if (!hidpp->protocol_major) {
2174                 ret = !hidpp_is_connected(hidpp);
2175                 if (ret) {
2176                         hid_err(hdev, "Can not get the protocol version.\n");
2177                         return;
2178                 }
2179                 hid_info(hdev, "HID++ %u.%u device connected.\n",
2180                          hidpp->protocol_major, hidpp->protocol_minor);
2181         }
2182
2183         if (!(hidpp->quirks & HIDPP_QUIRK_NO_HIDINPUT))
2184                 /* if HID created the input nodes for us, we can stop now */
2185                 return;
2186
2187         if (!hidpp->name || hidpp->name == hdev->name) {
2188                 name = hidpp_get_device_name(hidpp);
2189                 if (!name) {
2190                         hid_err(hdev,
2191                                 "unable to retrieve the name of the device");
2192                         return;
2193                 }
2194
2195                 devm_name = devm_kasprintf(&hdev->dev, GFP_KERNEL, "%s", name);
2196                 kfree(name);
2197                 if (!devm_name)
2198                         return;
2199
2200                 hidpp->name = devm_name;
2201         }
2202
2203         input = hidpp_allocate_input(hdev);
2204         if (!input) {
2205                 hid_err(hdev, "cannot allocate new input device: %d\n", ret);
2206                 return;
2207         }
2208
2209         hidpp_populate_input(hidpp, input, false);
2210
2211         ret = input_register_device(input);
2212         if (ret)
2213                 input_free_device(input);
2214
2215         hidpp->delayed_input = input;
2216 }
2217
2218 static int hidpp_probe(struct hid_device *hdev, const struct hid_device_id *id)
2219 {
2220         struct hidpp_device *hidpp;
2221         int ret;
2222         bool connected;
2223         unsigned int connect_mask = HID_CONNECT_DEFAULT;
2224
2225         hidpp = devm_kzalloc(&hdev->dev, sizeof(struct hidpp_device),
2226                         GFP_KERNEL);
2227         if (!hidpp)
2228                 return -ENOMEM;
2229
2230         hidpp->hid_dev = hdev;
2231         hidpp->name = hdev->name;
2232         hid_set_drvdata(hdev, hidpp);
2233
2234         hidpp->quirks = id->driver_data;
2235
2236         if (disable_raw_mode) {
2237                 hidpp->quirks &= ~HIDPP_QUIRK_CLASS_WTP;
2238                 hidpp->quirks &= ~HIDPP_QUIRK_CONNECT_EVENTS;
2239                 hidpp->quirks &= ~HIDPP_QUIRK_NO_HIDINPUT;
2240         }
2241
2242         if (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP) {
2243                 ret = wtp_allocate(hdev, id);
2244                 if (ret)
2245                         goto allocate_fail;
2246         } else if (hidpp->quirks & HIDPP_QUIRK_CLASS_M560) {
2247                 ret = m560_allocate(hdev);
2248                 if (ret)
2249                         goto allocate_fail;
2250         } else if (hidpp->quirks & HIDPP_QUIRK_CLASS_K400) {
2251                 ret = k400_allocate(hdev);
2252                 if (ret)
2253                         goto allocate_fail;
2254         }
2255
2256         INIT_WORK(&hidpp->work, delayed_work_cb);
2257         mutex_init(&hidpp->send_mutex);
2258         init_waitqueue_head(&hidpp->wait);
2259
2260         ret = hid_parse(hdev);
2261         if (ret) {
2262                 hid_err(hdev, "%s:parse failed\n", __func__);
2263                 goto hid_parse_fail;
2264         }
2265
2266         if (hidpp->quirks & HIDPP_QUIRK_NO_HIDINPUT)
2267                 connect_mask &= ~HID_CONNECT_HIDINPUT;
2268
2269         if (hidpp->quirks & HIDPP_QUIRK_CLASS_G920) {
2270                 ret = hid_hw_start(hdev, connect_mask);
2271                 if (ret) {
2272                         hid_err(hdev, "hw start failed\n");
2273                         goto hid_hw_start_fail;
2274                 }
2275                 ret = hid_hw_open(hdev);
2276                 if (ret < 0) {
2277                         dev_err(&hdev->dev, "%s:hid_hw_open returned error:%d\n",
2278                                 __func__, ret);
2279                         hid_hw_stop(hdev);
2280                         goto hid_hw_start_fail;
2281                 }
2282         }
2283
2284
2285         /* Allow incoming packets */
2286         hid_device_io_start(hdev);
2287
2288         connected = hidpp_is_connected(hidpp);
2289         if (id->group != HID_GROUP_LOGITECH_DJ_DEVICE) {
2290                 if (!connected) {
2291                         ret = -ENODEV;
2292                         hid_err(hdev, "Device not connected");
2293                         goto hid_hw_open_failed;
2294                 }
2295
2296                 hid_info(hdev, "HID++ %u.%u device connected.\n",
2297                          hidpp->protocol_major, hidpp->protocol_minor);
2298         }
2299
2300         hidpp_overwrite_name(hdev, id->group == HID_GROUP_LOGITECH_DJ_DEVICE);
2301         atomic_set(&hidpp->connected, connected);
2302
2303         if (connected && (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP)) {
2304                 ret = wtp_get_config(hidpp);
2305                 if (ret)
2306                         goto hid_hw_open_failed;
2307         } else if (connected && (hidpp->quirks & HIDPP_QUIRK_CLASS_G920)) {
2308                 ret = g920_get_config(hidpp);
2309                 if (ret)
2310                         goto hid_hw_open_failed;
2311         }
2312
2313         /* Block incoming packets */
2314         hid_device_io_stop(hdev);
2315
2316         if (!(hidpp->quirks & HIDPP_QUIRK_CLASS_G920)) {
2317                 ret = hid_hw_start(hdev, connect_mask);
2318                 if (ret) {
2319                         hid_err(hdev, "%s:hid_hw_start returned error\n", __func__);
2320                         goto hid_hw_start_fail;
2321                 }
2322         }
2323
2324         if (hidpp->quirks & HIDPP_QUIRK_CONNECT_EVENTS) {
2325                 /* Allow incoming packets */
2326                 hid_device_io_start(hdev);
2327
2328                 hidpp_connect_event(hidpp);
2329         }
2330
2331         return ret;
2332
2333 hid_hw_open_failed:
2334         hid_device_io_stop(hdev);
2335         if (hidpp->quirks & HIDPP_QUIRK_CLASS_G920) {
2336                 hid_hw_close(hdev);
2337                 hid_hw_stop(hdev);
2338         }
2339 hid_hw_start_fail:
2340 hid_parse_fail:
2341         cancel_work_sync(&hidpp->work);
2342         mutex_destroy(&hidpp->send_mutex);
2343 allocate_fail:
2344         hid_set_drvdata(hdev, NULL);
2345         return ret;
2346 }
2347
2348 static void hidpp_remove(struct hid_device *hdev)
2349 {
2350         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2351
2352         if (hidpp->quirks & HIDPP_QUIRK_CLASS_G920) {
2353                 hidpp_ff_deinit(hdev);
2354                 hid_hw_close(hdev);
2355         }
2356         hid_hw_stop(hdev);
2357         cancel_work_sync(&hidpp->work);
2358         mutex_destroy(&hidpp->send_mutex);
2359 }
2360
2361 static const struct hid_device_id hidpp_devices[] = {
2362         { /* wireless touchpad */
2363           HID_DEVICE(BUS_USB, HID_GROUP_LOGITECH_DJ_DEVICE,
2364                 USB_VENDOR_ID_LOGITECH, 0x4011),
2365           .driver_data = HIDPP_QUIRK_CLASS_WTP | HIDPP_QUIRK_DELAYED_INIT |
2366                          HIDPP_QUIRK_WTP_PHYSICAL_BUTTONS },
2367         { /* wireless touchpad T650 */
2368           HID_DEVICE(BUS_USB, HID_GROUP_LOGITECH_DJ_DEVICE,
2369                 USB_VENDOR_ID_LOGITECH, 0x4101),
2370           .driver_data = HIDPP_QUIRK_CLASS_WTP | HIDPP_QUIRK_DELAYED_INIT },
2371         { /* wireless touchpad T651 */
2372           HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH,
2373                 USB_DEVICE_ID_LOGITECH_T651),
2374           .driver_data = HIDPP_QUIRK_CLASS_WTP },
2375         { /* Mouse logitech M560 */
2376           HID_DEVICE(BUS_USB, HID_GROUP_LOGITECH_DJ_DEVICE,
2377                 USB_VENDOR_ID_LOGITECH, 0x402d),
2378           .driver_data = HIDPP_QUIRK_DELAYED_INIT | HIDPP_QUIRK_CLASS_M560 },
2379         { /* Keyboard logitech K400 */
2380           HID_DEVICE(BUS_USB, HID_GROUP_LOGITECH_DJ_DEVICE,
2381                 USB_VENDOR_ID_LOGITECH, 0x4024),
2382           .driver_data = HIDPP_QUIRK_CONNECT_EVENTS | HIDPP_QUIRK_CLASS_K400 },
2383
2384         { HID_DEVICE(BUS_USB, HID_GROUP_LOGITECH_DJ_DEVICE,
2385                 USB_VENDOR_ID_LOGITECH, HID_ANY_ID)},
2386
2387         { HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_G920_WHEEL),
2388                 .driver_data = HIDPP_QUIRK_CLASS_G920 | HIDPP_QUIRK_FORCE_OUTPUT_REPORTS},
2389         {}
2390 };
2391
2392 MODULE_DEVICE_TABLE(hid, hidpp_devices);
2393
2394 static struct hid_driver hidpp_driver = {
2395         .name = "logitech-hidpp-device",
2396         .id_table = hidpp_devices,
2397         .probe = hidpp_probe,
2398         .remove = hidpp_remove,
2399         .raw_event = hidpp_raw_event,
2400         .input_configured = hidpp_input_configured,
2401         .input_mapping = hidpp_input_mapping,
2402         .input_mapped = hidpp_input_mapped,
2403 };
2404
2405 module_hid_driver(hidpp_driver);