GNU Linux-libre 5.4.241-gnu1
[releases.git] / drivers / hid / hid-logitech-hidpp.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  HIDPP protocol for Logitech Unifying receivers
4  *
5  *  Copyright (c) 2011 Logitech (c)
6  *  Copyright (c) 2012-2013 Google (c)
7  *  Copyright (c) 2013-2014 Red Hat Inc.
8  */
9
10
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12
13 #include <linux/device.h>
14 #include <linux/input.h>
15 #include <linux/usb.h>
16 #include <linux/hid.h>
17 #include <linux/module.h>
18 #include <linux/slab.h>
19 #include <linux/sched.h>
20 #include <linux/sched/clock.h>
21 #include <linux/kfifo.h>
22 #include <linux/input/mt.h>
23 #include <linux/workqueue.h>
24 #include <linux/atomic.h>
25 #include <linux/fixp-arith.h>
26 #include <asm/unaligned.h>
27 #include "usbhid/usbhid.h"
28 #include "hid-ids.h"
29
30 MODULE_LICENSE("GPL");
31 MODULE_AUTHOR("Benjamin Tissoires <benjamin.tissoires@gmail.com>");
32 MODULE_AUTHOR("Nestor Lopez Casado <nlopezcasad@logitech.com>");
33
34 static bool disable_raw_mode;
35 module_param(disable_raw_mode, bool, 0644);
36 MODULE_PARM_DESC(disable_raw_mode,
37         "Disable Raw mode reporting for touchpads and keep firmware gestures.");
38
39 static bool disable_tap_to_click;
40 module_param(disable_tap_to_click, bool, 0644);
41 MODULE_PARM_DESC(disable_tap_to_click,
42         "Disable Tap-To-Click mode reporting for touchpads (only on the K400 currently).");
43
44 #define REPORT_ID_HIDPP_SHORT                   0x10
45 #define REPORT_ID_HIDPP_LONG                    0x11
46 #define REPORT_ID_HIDPP_VERY_LONG               0x12
47
48 #define HIDPP_REPORT_SHORT_LENGTH               7
49 #define HIDPP_REPORT_LONG_LENGTH                20
50 #define HIDPP_REPORT_VERY_LONG_MAX_LENGTH       64
51
52 #define HIDPP_SUB_ID_CONSUMER_VENDOR_KEYS       0x03
53 #define HIDPP_SUB_ID_ROLLER                     0x05
54 #define HIDPP_SUB_ID_MOUSE_EXTRA_BTNS           0x06
55
56 #define HIDPP_QUIRK_CLASS_WTP                   BIT(0)
57 #define HIDPP_QUIRK_CLASS_M560                  BIT(1)
58 #define HIDPP_QUIRK_CLASS_K400                  BIT(2)
59 #define HIDPP_QUIRK_CLASS_G920                  BIT(3)
60 #define HIDPP_QUIRK_CLASS_K750                  BIT(4)
61
62 /* bits 2..20 are reserved for classes */
63 /* #define HIDPP_QUIRK_CONNECT_EVENTS           BIT(21) disabled */
64 #define HIDPP_QUIRK_WTP_PHYSICAL_BUTTONS        BIT(22)
65 #define HIDPP_QUIRK_NO_HIDINPUT                 BIT(23)
66 #define HIDPP_QUIRK_FORCE_OUTPUT_REPORTS        BIT(24)
67 #define HIDPP_QUIRK_UNIFYING                    BIT(25)
68 #define HIDPP_QUIRK_HI_RES_SCROLL_1P0           BIT(26)
69 #define HIDPP_QUIRK_HI_RES_SCROLL_X2120         BIT(27)
70 #define HIDPP_QUIRK_HI_RES_SCROLL_X2121         BIT(28)
71 #define HIDPP_QUIRK_HIDPP_WHEELS                BIT(29)
72 #define HIDPP_QUIRK_HIDPP_EXTRA_MOUSE_BTNS      BIT(30)
73 #define HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS  BIT(31)
74
75 /* These are just aliases for now */
76 #define HIDPP_QUIRK_KBD_SCROLL_WHEEL HIDPP_QUIRK_HIDPP_WHEELS
77 #define HIDPP_QUIRK_KBD_ZOOM_WHEEL   HIDPP_QUIRK_HIDPP_WHEELS
78
79 /* Convenience constant to check for any high-res support. */
80 #define HIDPP_QUIRK_HI_RES_SCROLL       (HIDPP_QUIRK_HI_RES_SCROLL_1P0 | \
81                                          HIDPP_QUIRK_HI_RES_SCROLL_X2120 | \
82                                          HIDPP_QUIRK_HI_RES_SCROLL_X2121)
83
84 #define HIDPP_QUIRK_DELAYED_INIT                HIDPP_QUIRK_NO_HIDINPUT
85
86 #define HIDPP_CAPABILITY_HIDPP10_BATTERY        BIT(0)
87 #define HIDPP_CAPABILITY_HIDPP20_BATTERY        BIT(1)
88 #define HIDPP_CAPABILITY_BATTERY_MILEAGE        BIT(2)
89 #define HIDPP_CAPABILITY_BATTERY_LEVEL_STATUS   BIT(3)
90
91 #define lg_map_key_clear(c)  hid_map_usage_clear(hi, usage, bit, max, EV_KEY, (c))
92
93 /*
94  * There are two hidpp protocols in use, the first version hidpp10 is known
95  * as register access protocol or RAP, the second version hidpp20 is known as
96  * feature access protocol or FAP
97  *
98  * Most older devices (including the Unifying usb receiver) use the RAP protocol
99  * where as most newer devices use the FAP protocol. Both protocols are
100  * compatible with the underlying transport, which could be usb, Unifiying, or
101  * bluetooth. The message lengths are defined by the hid vendor specific report
102  * descriptor for the HIDPP_SHORT report type (total message lenth 7 bytes) and
103  * the HIDPP_LONG report type (total message length 20 bytes)
104  *
105  * The RAP protocol uses both report types, whereas the FAP only uses HIDPP_LONG
106  * messages. The Unifying receiver itself responds to RAP messages (device index
107  * is 0xFF for the receiver), and all messages (short or long) with a device
108  * index between 1 and 6 are passed untouched to the corresponding paired
109  * Unifying device.
110  *
111  * The paired device can be RAP or FAP, it will receive the message untouched
112  * from the Unifiying receiver.
113  */
114
115 struct fap {
116         u8 feature_index;
117         u8 funcindex_clientid;
118         u8 params[HIDPP_REPORT_VERY_LONG_MAX_LENGTH - 4U];
119 };
120
121 struct rap {
122         u8 sub_id;
123         u8 reg_address;
124         u8 params[HIDPP_REPORT_VERY_LONG_MAX_LENGTH - 4U];
125 };
126
127 struct hidpp_report {
128         u8 report_id;
129         u8 device_index;
130         union {
131                 struct fap fap;
132                 struct rap rap;
133                 u8 rawbytes[sizeof(struct fap)];
134         };
135 } __packed;
136
137 struct hidpp_battery {
138         u8 feature_index;
139         u8 solar_feature_index;
140         struct power_supply_desc desc;
141         struct power_supply *ps;
142         char name[64];
143         int status;
144         int capacity;
145         int level;
146         bool online;
147 };
148
149 /**
150  * struct hidpp_scroll_counter - Utility class for processing high-resolution
151  *                             scroll events.
152  * @dev: the input device for which events should be reported.
153  * @wheel_multiplier: the scalar multiplier to be applied to each wheel event
154  * @remainder: counts the number of high-resolution units moved since the last
155  *             low-resolution event (REL_WHEEL or REL_HWHEEL) was sent. Should
156  *             only be used by class methods.
157  * @direction: direction of last movement (1 or -1)
158  * @last_time: last event time, used to reset remainder after inactivity
159  */
160 struct hidpp_scroll_counter {
161         int wheel_multiplier;
162         int remainder;
163         int direction;
164         unsigned long long last_time;
165 };
166
167 struct hidpp_device {
168         struct hid_device *hid_dev;
169         struct input_dev *input;
170         struct mutex send_mutex;
171         void *send_receive_buf;
172         char *name;             /* will never be NULL and should not be freed */
173         wait_queue_head_t wait;
174         int very_long_report_length;
175         bool answer_available;
176         u8 protocol_major;
177         u8 protocol_minor;
178
179         void *private_data;
180
181         struct work_struct work;
182         struct kfifo delayed_work_fifo;
183         atomic_t connected;
184         struct input_dev *delayed_input;
185
186         unsigned long quirks;
187         unsigned long capabilities;
188
189         struct hidpp_battery battery;
190         struct hidpp_scroll_counter vertical_wheel_counter;
191 };
192
193 /* HID++ 1.0 error codes */
194 #define HIDPP_ERROR                             0x8f
195 #define HIDPP_ERROR_SUCCESS                     0x00
196 #define HIDPP_ERROR_INVALID_SUBID               0x01
197 #define HIDPP_ERROR_INVALID_ADRESS              0x02
198 #define HIDPP_ERROR_INVALID_VALUE               0x03
199 #define HIDPP_ERROR_CONNECT_FAIL                0x04
200 #define HIDPP_ERROR_TOO_MANY_DEVICES            0x05
201 #define HIDPP_ERROR_ALREADY_EXISTS              0x06
202 #define HIDPP_ERROR_BUSY                        0x07
203 #define HIDPP_ERROR_UNKNOWN_DEVICE              0x08
204 #define HIDPP_ERROR_RESOURCE_ERROR              0x09
205 #define HIDPP_ERROR_REQUEST_UNAVAILABLE         0x0a
206 #define HIDPP_ERROR_INVALID_PARAM_VALUE         0x0b
207 #define HIDPP_ERROR_WRONG_PIN_CODE              0x0c
208 /* HID++ 2.0 error codes */
209 #define HIDPP20_ERROR                           0xff
210
211 static void hidpp_connect_event(struct hidpp_device *hidpp_dev);
212
213 static int __hidpp_send_report(struct hid_device *hdev,
214                                 struct hidpp_report *hidpp_report)
215 {
216         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
217         int fields_count, ret;
218
219         switch (hidpp_report->report_id) {
220         case REPORT_ID_HIDPP_SHORT:
221                 fields_count = HIDPP_REPORT_SHORT_LENGTH;
222                 break;
223         case REPORT_ID_HIDPP_LONG:
224                 fields_count = HIDPP_REPORT_LONG_LENGTH;
225                 break;
226         case REPORT_ID_HIDPP_VERY_LONG:
227                 fields_count = hidpp->very_long_report_length;
228                 break;
229         default:
230                 return -ENODEV;
231         }
232
233         /*
234          * set the device_index as the receiver, it will be overwritten by
235          * hid_hw_request if needed
236          */
237         hidpp_report->device_index = 0xff;
238
239         if (hidpp->quirks & HIDPP_QUIRK_FORCE_OUTPUT_REPORTS) {
240                 ret = hid_hw_output_report(hdev, (u8 *)hidpp_report, fields_count);
241         } else {
242                 ret = hid_hw_raw_request(hdev, hidpp_report->report_id,
243                         (u8 *)hidpp_report, fields_count, HID_OUTPUT_REPORT,
244                         HID_REQ_SET_REPORT);
245         }
246
247         return ret == fields_count ? 0 : -1;
248 }
249
250 /**
251  * hidpp_send_message_sync() returns 0 in case of success, and something else
252  * in case of a failure.
253  * - If ' something else' is positive, that means that an error has been raised
254  *   by the protocol itself.
255  * - If ' something else' is negative, that means that we had a classic error
256  *   (-ENOMEM, -EPIPE, etc...)
257  */
258 static int hidpp_send_message_sync(struct hidpp_device *hidpp,
259         struct hidpp_report *message,
260         struct hidpp_report *response)
261 {
262         int ret;
263
264         mutex_lock(&hidpp->send_mutex);
265
266         hidpp->send_receive_buf = response;
267         hidpp->answer_available = false;
268
269         /*
270          * So that we can later validate the answer when it arrives
271          * in hidpp_raw_event
272          */
273         *response = *message;
274
275         ret = __hidpp_send_report(hidpp->hid_dev, message);
276
277         if (ret) {
278                 dbg_hid("__hidpp_send_report returned err: %d\n", ret);
279                 memset(response, 0, sizeof(struct hidpp_report));
280                 goto exit;
281         }
282
283         if (!wait_event_timeout(hidpp->wait, hidpp->answer_available,
284                                 5*HZ)) {
285                 dbg_hid("%s:timeout waiting for response\n", __func__);
286                 memset(response, 0, sizeof(struct hidpp_report));
287                 ret = -ETIMEDOUT;
288         }
289
290         if (response->report_id == REPORT_ID_HIDPP_SHORT &&
291             response->rap.sub_id == HIDPP_ERROR) {
292                 ret = response->rap.params[1];
293                 dbg_hid("%s:got hidpp error %02X\n", __func__, ret);
294                 goto exit;
295         }
296
297         if ((response->report_id == REPORT_ID_HIDPP_LONG ||
298                         response->report_id == REPORT_ID_HIDPP_VERY_LONG) &&
299                         response->fap.feature_index == HIDPP20_ERROR) {
300                 ret = response->fap.params[1];
301                 dbg_hid("%s:got hidpp 2.0 error %02X\n", __func__, ret);
302                 goto exit;
303         }
304
305 exit:
306         mutex_unlock(&hidpp->send_mutex);
307         return ret;
308
309 }
310
311 static int hidpp_send_fap_command_sync(struct hidpp_device *hidpp,
312         u8 feat_index, u8 funcindex_clientid, u8 *params, int param_count,
313         struct hidpp_report *response)
314 {
315         struct hidpp_report *message;
316         int ret;
317
318         if (param_count > sizeof(message->fap.params))
319                 return -EINVAL;
320
321         message = kzalloc(sizeof(struct hidpp_report), GFP_KERNEL);
322         if (!message)
323                 return -ENOMEM;
324
325         if (param_count > (HIDPP_REPORT_LONG_LENGTH - 4))
326                 message->report_id = REPORT_ID_HIDPP_VERY_LONG;
327         else
328                 message->report_id = REPORT_ID_HIDPP_LONG;
329         message->fap.feature_index = feat_index;
330         message->fap.funcindex_clientid = funcindex_clientid;
331         memcpy(&message->fap.params, params, param_count);
332
333         ret = hidpp_send_message_sync(hidpp, message, response);
334         kfree(message);
335         return ret;
336 }
337
338 static int hidpp_send_rap_command_sync(struct hidpp_device *hidpp_dev,
339         u8 report_id, u8 sub_id, u8 reg_address, u8 *params, int param_count,
340         struct hidpp_report *response)
341 {
342         struct hidpp_report *message;
343         int ret, max_count;
344
345         switch (report_id) {
346         case REPORT_ID_HIDPP_SHORT:
347                 max_count = HIDPP_REPORT_SHORT_LENGTH - 4;
348                 break;
349         case REPORT_ID_HIDPP_LONG:
350                 max_count = HIDPP_REPORT_LONG_LENGTH - 4;
351                 break;
352         case REPORT_ID_HIDPP_VERY_LONG:
353                 max_count = hidpp_dev->very_long_report_length - 4;
354                 break;
355         default:
356                 return -EINVAL;
357         }
358
359         if (param_count > max_count)
360                 return -EINVAL;
361
362         message = kzalloc(sizeof(struct hidpp_report), GFP_KERNEL);
363         if (!message)
364                 return -ENOMEM;
365         message->report_id = report_id;
366         message->rap.sub_id = sub_id;
367         message->rap.reg_address = reg_address;
368         memcpy(&message->rap.params, params, param_count);
369
370         ret = hidpp_send_message_sync(hidpp_dev, message, response);
371         kfree(message);
372         return ret;
373 }
374
375 static void delayed_work_cb(struct work_struct *work)
376 {
377         struct hidpp_device *hidpp = container_of(work, struct hidpp_device,
378                                                         work);
379         hidpp_connect_event(hidpp);
380 }
381
382 static inline bool hidpp_match_answer(struct hidpp_report *question,
383                 struct hidpp_report *answer)
384 {
385         return (answer->fap.feature_index == question->fap.feature_index) &&
386            (answer->fap.funcindex_clientid == question->fap.funcindex_clientid);
387 }
388
389 static inline bool hidpp_match_error(struct hidpp_report *question,
390                 struct hidpp_report *answer)
391 {
392         return ((answer->rap.sub_id == HIDPP_ERROR) ||
393             (answer->fap.feature_index == HIDPP20_ERROR)) &&
394             (answer->fap.funcindex_clientid == question->fap.feature_index) &&
395             (answer->fap.params[0] == question->fap.funcindex_clientid);
396 }
397
398 static inline bool hidpp_report_is_connect_event(struct hidpp_report *report)
399 {
400         return (report->report_id == REPORT_ID_HIDPP_SHORT) &&
401                 (report->rap.sub_id == 0x41);
402 }
403
404 /**
405  * hidpp_prefix_name() prefixes the current given name with "Logitech ".
406  */
407 static void hidpp_prefix_name(char **name, int name_length)
408 {
409 #define PREFIX_LENGTH 9 /* "Logitech " */
410
411         int new_length;
412         char *new_name;
413
414         if (name_length > PREFIX_LENGTH &&
415             strncmp(*name, "Logitech ", PREFIX_LENGTH) == 0)
416                 /* The prefix has is already in the name */
417                 return;
418
419         new_length = PREFIX_LENGTH + name_length;
420         new_name = kzalloc(new_length, GFP_KERNEL);
421         if (!new_name)
422                 return;
423
424         snprintf(new_name, new_length, "Logitech %s", *name);
425
426         kfree(*name);
427
428         *name = new_name;
429 }
430
431 /**
432  * hidpp_scroll_counter_handle_scroll() - Send high- and low-resolution scroll
433  *                                        events given a high-resolution wheel
434  *                                        movement.
435  * @counter: a hid_scroll_counter struct describing the wheel.
436  * @hi_res_value: the movement of the wheel, in the mouse's high-resolution
437  *                units.
438  *
439  * Given a high-resolution movement, this function converts the movement into
440  * fractions of 120 and emits high-resolution scroll events for the input
441  * device. It also uses the multiplier from &struct hid_scroll_counter to
442  * emit low-resolution scroll events when appropriate for
443  * backwards-compatibility with userspace input libraries.
444  */
445 static void hidpp_scroll_counter_handle_scroll(struct input_dev *input_dev,
446                                                struct hidpp_scroll_counter *counter,
447                                                int hi_res_value)
448 {
449         int low_res_value, remainder, direction;
450         unsigned long long now, previous;
451
452         hi_res_value = hi_res_value * 120/counter->wheel_multiplier;
453         input_report_rel(input_dev, REL_WHEEL_HI_RES, hi_res_value);
454
455         remainder = counter->remainder;
456         direction = hi_res_value > 0 ? 1 : -1;
457
458         now = sched_clock();
459         previous = counter->last_time;
460         counter->last_time = now;
461         /*
462          * Reset the remainder after a period of inactivity or when the
463          * direction changes. This prevents the REL_WHEEL emulation point
464          * from sliding for devices that don't always provide the same
465          * number of movements per detent.
466          */
467         if (now - previous > 1000000000 || direction != counter->direction)
468                 remainder = 0;
469
470         counter->direction = direction;
471         remainder += hi_res_value;
472
473         /* Some wheels will rest 7/8ths of a detent from the previous detent
474          * after slow movement, so we want the threshold for low-res events to
475          * be in the middle between two detents (e.g. after 4/8ths) as
476          * opposed to on the detents themselves (8/8ths).
477          */
478         if (abs(remainder) >= 60) {
479                 /* Add (or subtract) 1 because we want to trigger when the wheel
480                  * is half-way to the next detent (i.e. scroll 1 detent after a
481                  * 1/2 detent movement, 2 detents after a 1 1/2 detent movement,
482                  * etc.).
483                  */
484                 low_res_value = remainder / 120;
485                 if (low_res_value == 0)
486                         low_res_value = (hi_res_value > 0 ? 1 : -1);
487                 input_report_rel(input_dev, REL_WHEEL, low_res_value);
488                 remainder -= low_res_value * 120;
489         }
490         counter->remainder = remainder;
491 }
492
493 /* -------------------------------------------------------------------------- */
494 /* HIDP++ 1.0 commands                                                        */
495 /* -------------------------------------------------------------------------- */
496
497 #define HIDPP_SET_REGISTER                              0x80
498 #define HIDPP_GET_REGISTER                              0x81
499 #define HIDPP_SET_LONG_REGISTER                         0x82
500 #define HIDPP_GET_LONG_REGISTER                         0x83
501
502 /**
503  * hidpp10_set_register - Modify a HID++ 1.0 register.
504  * @hidpp_dev: the device to set the register on.
505  * @register_address: the address of the register to modify.
506  * @byte: the byte of the register to modify. Should be less than 3.
507  * @mask: mask of the bits to modify
508  * @value: new values for the bits in mask
509  * Return: 0 if successful, otherwise a negative error code.
510  */
511 static int hidpp10_set_register(struct hidpp_device *hidpp_dev,
512         u8 register_address, u8 byte, u8 mask, u8 value)
513 {
514         struct hidpp_report response;
515         int ret;
516         u8 params[3] = { 0 };
517
518         ret = hidpp_send_rap_command_sync(hidpp_dev,
519                                           REPORT_ID_HIDPP_SHORT,
520                                           HIDPP_GET_REGISTER,
521                                           register_address,
522                                           NULL, 0, &response);
523         if (ret)
524                 return ret;
525
526         memcpy(params, response.rap.params, 3);
527
528         params[byte] &= ~mask;
529         params[byte] |= value & mask;
530
531         return hidpp_send_rap_command_sync(hidpp_dev,
532                                            REPORT_ID_HIDPP_SHORT,
533                                            HIDPP_SET_REGISTER,
534                                            register_address,
535                                            params, 3, &response);
536 }
537
538 #define HIDPP_REG_ENABLE_REPORTS                        0x00
539 #define HIDPP_ENABLE_CONSUMER_REPORT                    BIT(0)
540 #define HIDPP_ENABLE_WHEEL_REPORT                       BIT(2)
541 #define HIDPP_ENABLE_MOUSE_EXTRA_BTN_REPORT             BIT(3)
542 #define HIDPP_ENABLE_BAT_REPORT                         BIT(4)
543 #define HIDPP_ENABLE_HWHEEL_REPORT                      BIT(5)
544
545 static int hidpp10_enable_battery_reporting(struct hidpp_device *hidpp_dev)
546 {
547         return hidpp10_set_register(hidpp_dev, HIDPP_REG_ENABLE_REPORTS, 0,
548                           HIDPP_ENABLE_BAT_REPORT, HIDPP_ENABLE_BAT_REPORT);
549 }
550
551 #define HIDPP_REG_FEATURES                              0x01
552 #define HIDPP_ENABLE_SPECIAL_BUTTON_FUNC                BIT(1)
553 #define HIDPP_ENABLE_FAST_SCROLL                        BIT(6)
554
555 /* On HID++ 1.0 devices, high-res scroll was called "scrolling acceleration". */
556 static int hidpp10_enable_scrolling_acceleration(struct hidpp_device *hidpp_dev)
557 {
558         return hidpp10_set_register(hidpp_dev, HIDPP_REG_FEATURES, 0,
559                           HIDPP_ENABLE_FAST_SCROLL, HIDPP_ENABLE_FAST_SCROLL);
560 }
561
562 #define HIDPP_REG_BATTERY_STATUS                        0x07
563
564 static int hidpp10_battery_status_map_level(u8 param)
565 {
566         int level;
567
568         switch (param) {
569         case 1 ... 2:
570                 level = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
571                 break;
572         case 3 ... 4:
573                 level = POWER_SUPPLY_CAPACITY_LEVEL_LOW;
574                 break;
575         case 5 ... 6:
576                 level = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
577                 break;
578         case 7:
579                 level = POWER_SUPPLY_CAPACITY_LEVEL_HIGH;
580                 break;
581         default:
582                 level = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
583         }
584
585         return level;
586 }
587
588 static int hidpp10_battery_status_map_status(u8 param)
589 {
590         int status;
591
592         switch (param) {
593         case 0x00:
594                 /* discharging (in use) */
595                 status = POWER_SUPPLY_STATUS_DISCHARGING;
596                 break;
597         case 0x21: /* (standard) charging */
598         case 0x24: /* fast charging */
599         case 0x25: /* slow charging */
600                 status = POWER_SUPPLY_STATUS_CHARGING;
601                 break;
602         case 0x26: /* topping charge */
603         case 0x22: /* charge complete */
604                 status = POWER_SUPPLY_STATUS_FULL;
605                 break;
606         case 0x20: /* unknown */
607                 status = POWER_SUPPLY_STATUS_UNKNOWN;
608                 break;
609         /*
610          * 0x01...0x1F = reserved (not charging)
611          * 0x23 = charging error
612          * 0x27..0xff = reserved
613          */
614         default:
615                 status = POWER_SUPPLY_STATUS_NOT_CHARGING;
616                 break;
617         }
618
619         return status;
620 }
621
622 static int hidpp10_query_battery_status(struct hidpp_device *hidpp)
623 {
624         struct hidpp_report response;
625         int ret, status;
626
627         ret = hidpp_send_rap_command_sync(hidpp,
628                                         REPORT_ID_HIDPP_SHORT,
629                                         HIDPP_GET_REGISTER,
630                                         HIDPP_REG_BATTERY_STATUS,
631                                         NULL, 0, &response);
632         if (ret)
633                 return ret;
634
635         hidpp->battery.level =
636                 hidpp10_battery_status_map_level(response.rap.params[0]);
637         status = hidpp10_battery_status_map_status(response.rap.params[1]);
638         hidpp->battery.status = status;
639         /* the capacity is only available when discharging or full */
640         hidpp->battery.online = status == POWER_SUPPLY_STATUS_DISCHARGING ||
641                                 status == POWER_SUPPLY_STATUS_FULL;
642
643         return 0;
644 }
645
646 #define HIDPP_REG_BATTERY_MILEAGE                       0x0D
647
648 static int hidpp10_battery_mileage_map_status(u8 param)
649 {
650         int status;
651
652         switch (param >> 6) {
653         case 0x00:
654                 /* discharging (in use) */
655                 status = POWER_SUPPLY_STATUS_DISCHARGING;
656                 break;
657         case 0x01: /* charging */
658                 status = POWER_SUPPLY_STATUS_CHARGING;
659                 break;
660         case 0x02: /* charge complete */
661                 status = POWER_SUPPLY_STATUS_FULL;
662                 break;
663         /*
664          * 0x03 = charging error
665          */
666         default:
667                 status = POWER_SUPPLY_STATUS_NOT_CHARGING;
668                 break;
669         }
670
671         return status;
672 }
673
674 static int hidpp10_query_battery_mileage(struct hidpp_device *hidpp)
675 {
676         struct hidpp_report response;
677         int ret, status;
678
679         ret = hidpp_send_rap_command_sync(hidpp,
680                                         REPORT_ID_HIDPP_SHORT,
681                                         HIDPP_GET_REGISTER,
682                                         HIDPP_REG_BATTERY_MILEAGE,
683                                         NULL, 0, &response);
684         if (ret)
685                 return ret;
686
687         hidpp->battery.capacity = response.rap.params[0];
688         status = hidpp10_battery_mileage_map_status(response.rap.params[2]);
689         hidpp->battery.status = status;
690         /* the capacity is only available when discharging or full */
691         hidpp->battery.online = status == POWER_SUPPLY_STATUS_DISCHARGING ||
692                                 status == POWER_SUPPLY_STATUS_FULL;
693
694         return 0;
695 }
696
697 static int hidpp10_battery_event(struct hidpp_device *hidpp, u8 *data, int size)
698 {
699         struct hidpp_report *report = (struct hidpp_report *)data;
700         int status, capacity, level;
701         bool changed;
702
703         if (report->report_id != REPORT_ID_HIDPP_SHORT)
704                 return 0;
705
706         switch (report->rap.sub_id) {
707         case HIDPP_REG_BATTERY_STATUS:
708                 capacity = hidpp->battery.capacity;
709                 level = hidpp10_battery_status_map_level(report->rawbytes[1]);
710                 status = hidpp10_battery_status_map_status(report->rawbytes[2]);
711                 break;
712         case HIDPP_REG_BATTERY_MILEAGE:
713                 capacity = report->rap.params[0];
714                 level = hidpp->battery.level;
715                 status = hidpp10_battery_mileage_map_status(report->rawbytes[3]);
716                 break;
717         default:
718                 return 0;
719         }
720
721         changed = capacity != hidpp->battery.capacity ||
722                   level != hidpp->battery.level ||
723                   status != hidpp->battery.status;
724
725         /* the capacity is only available when discharging or full */
726         hidpp->battery.online = status == POWER_SUPPLY_STATUS_DISCHARGING ||
727                                 status == POWER_SUPPLY_STATUS_FULL;
728
729         if (changed) {
730                 hidpp->battery.level = level;
731                 hidpp->battery.status = status;
732                 if (hidpp->battery.ps)
733                         power_supply_changed(hidpp->battery.ps);
734         }
735
736         return 0;
737 }
738
739 #define HIDPP_REG_PAIRING_INFORMATION                   0xB5
740 #define HIDPP_EXTENDED_PAIRING                          0x30
741 #define HIDPP_DEVICE_NAME                               0x40
742
743 static char *hidpp_unifying_get_name(struct hidpp_device *hidpp_dev)
744 {
745         struct hidpp_report response;
746         int ret;
747         u8 params[1] = { HIDPP_DEVICE_NAME };
748         char *name;
749         int len;
750
751         ret = hidpp_send_rap_command_sync(hidpp_dev,
752                                         REPORT_ID_HIDPP_SHORT,
753                                         HIDPP_GET_LONG_REGISTER,
754                                         HIDPP_REG_PAIRING_INFORMATION,
755                                         params, 1, &response);
756         if (ret)
757                 return NULL;
758
759         len = response.rap.params[1];
760
761         if (2 + len > sizeof(response.rap.params))
762                 return NULL;
763
764         if (len < 4) /* logitech devices are usually at least Xddd */
765                 return NULL;
766
767         name = kzalloc(len + 1, GFP_KERNEL);
768         if (!name)
769                 return NULL;
770
771         memcpy(name, &response.rap.params[2], len);
772
773         /* include the terminating '\0' */
774         hidpp_prefix_name(&name, len + 1);
775
776         return name;
777 }
778
779 static int hidpp_unifying_get_serial(struct hidpp_device *hidpp, u32 *serial)
780 {
781         struct hidpp_report response;
782         int ret;
783         u8 params[1] = { HIDPP_EXTENDED_PAIRING };
784
785         ret = hidpp_send_rap_command_sync(hidpp,
786                                         REPORT_ID_HIDPP_SHORT,
787                                         HIDPP_GET_LONG_REGISTER,
788                                         HIDPP_REG_PAIRING_INFORMATION,
789                                         params, 1, &response);
790         if (ret)
791                 return ret;
792
793         /*
794          * We don't care about LE or BE, we will output it as a string
795          * with %4phD, so we need to keep the order.
796          */
797         *serial = *((u32 *)&response.rap.params[1]);
798         return 0;
799 }
800
801 static int hidpp_unifying_init(struct hidpp_device *hidpp)
802 {
803         struct hid_device *hdev = hidpp->hid_dev;
804         const char *name;
805         u32 serial;
806         int ret;
807
808         ret = hidpp_unifying_get_serial(hidpp, &serial);
809         if (ret)
810                 return ret;
811
812         snprintf(hdev->uniq, sizeof(hdev->uniq), "%04x-%4phD",
813                  hdev->product, &serial);
814         dbg_hid("HID++ Unifying: Got serial: %s\n", hdev->uniq);
815
816         name = hidpp_unifying_get_name(hidpp);
817         if (!name)
818                 return -EIO;
819
820         snprintf(hdev->name, sizeof(hdev->name), "%s", name);
821         dbg_hid("HID++ Unifying: Got name: %s\n", name);
822
823         kfree(name);
824         return 0;
825 }
826
827 /* -------------------------------------------------------------------------- */
828 /* 0x0000: Root                                                               */
829 /* -------------------------------------------------------------------------- */
830
831 #define HIDPP_PAGE_ROOT                                 0x0000
832 #define HIDPP_PAGE_ROOT_IDX                             0x00
833
834 #define CMD_ROOT_GET_FEATURE                            0x01
835 #define CMD_ROOT_GET_PROTOCOL_VERSION                   0x11
836
837 static int hidpp_root_get_feature(struct hidpp_device *hidpp, u16 feature,
838         u8 *feature_index, u8 *feature_type)
839 {
840         struct hidpp_report response;
841         int ret;
842         u8 params[2] = { feature >> 8, feature & 0x00FF };
843
844         ret = hidpp_send_fap_command_sync(hidpp,
845                         HIDPP_PAGE_ROOT_IDX,
846                         CMD_ROOT_GET_FEATURE,
847                         params, 2, &response);
848         if (ret)
849                 return ret;
850
851         if (response.fap.params[0] == 0)
852                 return -ENOENT;
853
854         *feature_index = response.fap.params[0];
855         *feature_type = response.fap.params[1];
856
857         return ret;
858 }
859
860 static int hidpp_root_get_protocol_version(struct hidpp_device *hidpp)
861 {
862         const u8 ping_byte = 0x5a;
863         u8 ping_data[3] = { 0, 0, ping_byte };
864         struct hidpp_report response;
865         int ret;
866
867         ret = hidpp_send_rap_command_sync(hidpp,
868                         REPORT_ID_HIDPP_SHORT,
869                         HIDPP_PAGE_ROOT_IDX,
870                         CMD_ROOT_GET_PROTOCOL_VERSION,
871                         ping_data, sizeof(ping_data), &response);
872
873         if (ret == HIDPP_ERROR_INVALID_SUBID) {
874                 hidpp->protocol_major = 1;
875                 hidpp->protocol_minor = 0;
876                 goto print_version;
877         }
878
879         /* the device might not be connected */
880         if (ret == HIDPP_ERROR_RESOURCE_ERROR)
881                 return -EIO;
882
883         if (ret > 0) {
884                 hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
885                         __func__, ret);
886                 return -EPROTO;
887         }
888         if (ret)
889                 return ret;
890
891         if (response.rap.params[2] != ping_byte) {
892                 hid_err(hidpp->hid_dev, "%s: ping mismatch 0x%02x != 0x%02x\n",
893                         __func__, response.rap.params[2], ping_byte);
894                 return -EPROTO;
895         }
896
897         hidpp->protocol_major = response.rap.params[0];
898         hidpp->protocol_minor = response.rap.params[1];
899
900 print_version:
901         hid_info(hidpp->hid_dev, "HID++ %u.%u device connected.\n",
902                  hidpp->protocol_major, hidpp->protocol_minor);
903         return 0;
904 }
905
906 /* -------------------------------------------------------------------------- */
907 /* 0x0005: GetDeviceNameType                                                  */
908 /* -------------------------------------------------------------------------- */
909
910 #define HIDPP_PAGE_GET_DEVICE_NAME_TYPE                 0x0005
911
912 #define CMD_GET_DEVICE_NAME_TYPE_GET_COUNT              0x01
913 #define CMD_GET_DEVICE_NAME_TYPE_GET_DEVICE_NAME        0x11
914 #define CMD_GET_DEVICE_NAME_TYPE_GET_TYPE               0x21
915
916 static int hidpp_devicenametype_get_count(struct hidpp_device *hidpp,
917         u8 feature_index, u8 *nameLength)
918 {
919         struct hidpp_report response;
920         int ret;
921
922         ret = hidpp_send_fap_command_sync(hidpp, feature_index,
923                 CMD_GET_DEVICE_NAME_TYPE_GET_COUNT, NULL, 0, &response);
924
925         if (ret > 0) {
926                 hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
927                         __func__, ret);
928                 return -EPROTO;
929         }
930         if (ret)
931                 return ret;
932
933         *nameLength = response.fap.params[0];
934
935         return ret;
936 }
937
938 static int hidpp_devicenametype_get_device_name(struct hidpp_device *hidpp,
939         u8 feature_index, u8 char_index, char *device_name, int len_buf)
940 {
941         struct hidpp_report response;
942         int ret, i;
943         int count;
944
945         ret = hidpp_send_fap_command_sync(hidpp, feature_index,
946                 CMD_GET_DEVICE_NAME_TYPE_GET_DEVICE_NAME, &char_index, 1,
947                 &response);
948
949         if (ret > 0) {
950                 hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
951                         __func__, ret);
952                 return -EPROTO;
953         }
954         if (ret)
955                 return ret;
956
957         switch (response.report_id) {
958         case REPORT_ID_HIDPP_VERY_LONG:
959                 count = hidpp->very_long_report_length - 4;
960                 break;
961         case REPORT_ID_HIDPP_LONG:
962                 count = HIDPP_REPORT_LONG_LENGTH - 4;
963                 break;
964         case REPORT_ID_HIDPP_SHORT:
965                 count = HIDPP_REPORT_SHORT_LENGTH - 4;
966                 break;
967         default:
968                 return -EPROTO;
969         }
970
971         if (len_buf < count)
972                 count = len_buf;
973
974         for (i = 0; i < count; i++)
975                 device_name[i] = response.fap.params[i];
976
977         return count;
978 }
979
980 static char *hidpp_get_device_name(struct hidpp_device *hidpp)
981 {
982         u8 feature_type;
983         u8 feature_index;
984         u8 __name_length;
985         char *name;
986         unsigned index = 0;
987         int ret;
988
989         ret = hidpp_root_get_feature(hidpp, HIDPP_PAGE_GET_DEVICE_NAME_TYPE,
990                 &feature_index, &feature_type);
991         if (ret)
992                 return NULL;
993
994         ret = hidpp_devicenametype_get_count(hidpp, feature_index,
995                 &__name_length);
996         if (ret)
997                 return NULL;
998
999         name = kzalloc(__name_length + 1, GFP_KERNEL);
1000         if (!name)
1001                 return NULL;
1002
1003         while (index < __name_length) {
1004                 ret = hidpp_devicenametype_get_device_name(hidpp,
1005                         feature_index, index, name + index,
1006                         __name_length - index);
1007                 if (ret <= 0) {
1008                         kfree(name);
1009                         return NULL;
1010                 }
1011                 index += ret;
1012         }
1013
1014         /* include the terminating '\0' */
1015         hidpp_prefix_name(&name, __name_length + 1);
1016
1017         return name;
1018 }
1019
1020 /* -------------------------------------------------------------------------- */
1021 /* 0x1000: Battery level status                                               */
1022 /* -------------------------------------------------------------------------- */
1023
1024 #define HIDPP_PAGE_BATTERY_LEVEL_STATUS                         0x1000
1025
1026 #define CMD_BATTERY_LEVEL_STATUS_GET_BATTERY_LEVEL_STATUS       0x00
1027 #define CMD_BATTERY_LEVEL_STATUS_GET_BATTERY_CAPABILITY         0x10
1028
1029 #define EVENT_BATTERY_LEVEL_STATUS_BROADCAST                    0x00
1030
1031 #define FLAG_BATTERY_LEVEL_DISABLE_OSD                          BIT(0)
1032 #define FLAG_BATTERY_LEVEL_MILEAGE                              BIT(1)
1033 #define FLAG_BATTERY_LEVEL_RECHARGEABLE                         BIT(2)
1034
1035 static int hidpp_map_battery_level(int capacity)
1036 {
1037         if (capacity < 11)
1038                 return POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
1039         /*
1040          * The spec says this should be < 31 but some devices report 30
1041          * with brand new batteries and Windows reports 30 as "Good".
1042          */
1043         else if (capacity < 30)
1044                 return POWER_SUPPLY_CAPACITY_LEVEL_LOW;
1045         else if (capacity < 81)
1046                 return POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
1047         return POWER_SUPPLY_CAPACITY_LEVEL_FULL;
1048 }
1049
1050 static int hidpp20_batterylevel_map_status_capacity(u8 data[3], int *capacity,
1051                                                     int *next_capacity,
1052                                                     int *level)
1053 {
1054         int status;
1055
1056         *capacity = data[0];
1057         *next_capacity = data[1];
1058         *level = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
1059
1060         /* When discharging, we can rely on the device reported capacity.
1061          * For all other states the device reports 0 (unknown).
1062          */
1063         switch (data[2]) {
1064                 case 0: /* discharging (in use) */
1065                         status = POWER_SUPPLY_STATUS_DISCHARGING;
1066                         *level = hidpp_map_battery_level(*capacity);
1067                         break;
1068                 case 1: /* recharging */
1069                         status = POWER_SUPPLY_STATUS_CHARGING;
1070                         break;
1071                 case 2: /* charge in final stage */
1072                         status = POWER_SUPPLY_STATUS_CHARGING;
1073                         break;
1074                 case 3: /* charge complete */
1075                         status = POWER_SUPPLY_STATUS_FULL;
1076                         *level = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
1077                         *capacity = 100;
1078                         break;
1079                 case 4: /* recharging below optimal speed */
1080                         status = POWER_SUPPLY_STATUS_CHARGING;
1081                         break;
1082                 /* 5 = invalid battery type
1083                    6 = thermal error
1084                    7 = other charging error */
1085                 default:
1086                         status = POWER_SUPPLY_STATUS_NOT_CHARGING;
1087                         break;
1088         }
1089
1090         return status;
1091 }
1092
1093 static int hidpp20_batterylevel_get_battery_capacity(struct hidpp_device *hidpp,
1094                                                      u8 feature_index,
1095                                                      int *status,
1096                                                      int *capacity,
1097                                                      int *next_capacity,
1098                                                      int *level)
1099 {
1100         struct hidpp_report response;
1101         int ret;
1102         u8 *params = (u8 *)response.fap.params;
1103
1104         ret = hidpp_send_fap_command_sync(hidpp, feature_index,
1105                                           CMD_BATTERY_LEVEL_STATUS_GET_BATTERY_LEVEL_STATUS,
1106                                           NULL, 0, &response);
1107         /* Ignore these intermittent errors */
1108         if (ret == HIDPP_ERROR_RESOURCE_ERROR)
1109                 return -EIO;
1110         if (ret > 0) {
1111                 hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
1112                         __func__, ret);
1113                 return -EPROTO;
1114         }
1115         if (ret)
1116                 return ret;
1117
1118         *status = hidpp20_batterylevel_map_status_capacity(params, capacity,
1119                                                            next_capacity,
1120                                                            level);
1121
1122         return 0;
1123 }
1124
1125 static int hidpp20_batterylevel_get_battery_info(struct hidpp_device *hidpp,
1126                                                   u8 feature_index)
1127 {
1128         struct hidpp_report response;
1129         int ret;
1130         u8 *params = (u8 *)response.fap.params;
1131         unsigned int level_count, flags;
1132
1133         ret = hidpp_send_fap_command_sync(hidpp, feature_index,
1134                                           CMD_BATTERY_LEVEL_STATUS_GET_BATTERY_CAPABILITY,
1135                                           NULL, 0, &response);
1136         if (ret > 0) {
1137                 hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
1138                         __func__, ret);
1139                 return -EPROTO;
1140         }
1141         if (ret)
1142                 return ret;
1143
1144         level_count = params[0];
1145         flags = params[1];
1146
1147         if (level_count < 10 || !(flags & FLAG_BATTERY_LEVEL_MILEAGE))
1148                 hidpp->capabilities |= HIDPP_CAPABILITY_BATTERY_LEVEL_STATUS;
1149         else
1150                 hidpp->capabilities |= HIDPP_CAPABILITY_BATTERY_MILEAGE;
1151
1152         return 0;
1153 }
1154
1155 static int hidpp20_query_battery_info(struct hidpp_device *hidpp)
1156 {
1157         u8 feature_type;
1158         int ret;
1159         int status, capacity, next_capacity, level;
1160
1161         if (hidpp->battery.feature_index == 0xff) {
1162                 ret = hidpp_root_get_feature(hidpp,
1163                                              HIDPP_PAGE_BATTERY_LEVEL_STATUS,
1164                                              &hidpp->battery.feature_index,
1165                                              &feature_type);
1166                 if (ret)
1167                         return ret;
1168         }
1169
1170         ret = hidpp20_batterylevel_get_battery_capacity(hidpp,
1171                                                 hidpp->battery.feature_index,
1172                                                 &status, &capacity,
1173                                                 &next_capacity, &level);
1174         if (ret)
1175                 return ret;
1176
1177         ret = hidpp20_batterylevel_get_battery_info(hidpp,
1178                                                 hidpp->battery.feature_index);
1179         if (ret)
1180                 return ret;
1181
1182         hidpp->battery.status = status;
1183         hidpp->battery.capacity = capacity;
1184         hidpp->battery.level = level;
1185         /* the capacity is only available when discharging or full */
1186         hidpp->battery.online = status == POWER_SUPPLY_STATUS_DISCHARGING ||
1187                                 status == POWER_SUPPLY_STATUS_FULL;
1188
1189         return 0;
1190 }
1191
1192 static int hidpp20_battery_event(struct hidpp_device *hidpp,
1193                                  u8 *data, int size)
1194 {
1195         struct hidpp_report *report = (struct hidpp_report *)data;
1196         int status, capacity, next_capacity, level;
1197         bool changed;
1198
1199         if (report->fap.feature_index != hidpp->battery.feature_index ||
1200             report->fap.funcindex_clientid != EVENT_BATTERY_LEVEL_STATUS_BROADCAST)
1201                 return 0;
1202
1203         status = hidpp20_batterylevel_map_status_capacity(report->fap.params,
1204                                                           &capacity,
1205                                                           &next_capacity,
1206                                                           &level);
1207
1208         /* the capacity is only available when discharging or full */
1209         hidpp->battery.online = status == POWER_SUPPLY_STATUS_DISCHARGING ||
1210                                 status == POWER_SUPPLY_STATUS_FULL;
1211
1212         changed = capacity != hidpp->battery.capacity ||
1213                   level != hidpp->battery.level ||
1214                   status != hidpp->battery.status;
1215
1216         if (changed) {
1217                 hidpp->battery.level = level;
1218                 hidpp->battery.capacity = capacity;
1219                 hidpp->battery.status = status;
1220                 if (hidpp->battery.ps)
1221                         power_supply_changed(hidpp->battery.ps);
1222         }
1223
1224         return 0;
1225 }
1226
1227 static enum power_supply_property hidpp_battery_props[] = {
1228         POWER_SUPPLY_PROP_ONLINE,
1229         POWER_SUPPLY_PROP_STATUS,
1230         POWER_SUPPLY_PROP_SCOPE,
1231         POWER_SUPPLY_PROP_MODEL_NAME,
1232         POWER_SUPPLY_PROP_MANUFACTURER,
1233         POWER_SUPPLY_PROP_SERIAL_NUMBER,
1234         0, /* placeholder for POWER_SUPPLY_PROP_CAPACITY, */
1235         0, /* placeholder for POWER_SUPPLY_PROP_CAPACITY_LEVEL, */
1236 };
1237
1238 static int hidpp_battery_get_property(struct power_supply *psy,
1239                                       enum power_supply_property psp,
1240                                       union power_supply_propval *val)
1241 {
1242         struct hidpp_device *hidpp = power_supply_get_drvdata(psy);
1243         int ret = 0;
1244
1245         switch(psp) {
1246                 case POWER_SUPPLY_PROP_STATUS:
1247                         val->intval = hidpp->battery.status;
1248                         break;
1249                 case POWER_SUPPLY_PROP_CAPACITY:
1250                         val->intval = hidpp->battery.capacity;
1251                         break;
1252                 case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
1253                         val->intval = hidpp->battery.level;
1254                         break;
1255                 case POWER_SUPPLY_PROP_SCOPE:
1256                         val->intval = POWER_SUPPLY_SCOPE_DEVICE;
1257                         break;
1258                 case POWER_SUPPLY_PROP_ONLINE:
1259                         val->intval = hidpp->battery.online;
1260                         break;
1261                 case POWER_SUPPLY_PROP_MODEL_NAME:
1262                         if (!strncmp(hidpp->name, "Logitech ", 9))
1263                                 val->strval = hidpp->name + 9;
1264                         else
1265                                 val->strval = hidpp->name;
1266                         break;
1267                 case POWER_SUPPLY_PROP_MANUFACTURER:
1268                         val->strval = "Logitech";
1269                         break;
1270                 case POWER_SUPPLY_PROP_SERIAL_NUMBER:
1271                         val->strval = hidpp->hid_dev->uniq;
1272                         break;
1273                 default:
1274                         ret = -EINVAL;
1275                         break;
1276         }
1277
1278         return ret;
1279 }
1280
1281 /* -------------------------------------------------------------------------- */
1282 /* 0x2120: Hi-resolution scrolling                                            */
1283 /* -------------------------------------------------------------------------- */
1284
1285 #define HIDPP_PAGE_HI_RESOLUTION_SCROLLING                      0x2120
1286
1287 #define CMD_HI_RESOLUTION_SCROLLING_SET_HIGHRES_SCROLLING_MODE  0x10
1288
1289 static int hidpp_hrs_set_highres_scrolling_mode(struct hidpp_device *hidpp,
1290         bool enabled, u8 *multiplier)
1291 {
1292         u8 feature_index;
1293         u8 feature_type;
1294         int ret;
1295         u8 params[1];
1296         struct hidpp_report response;
1297
1298         ret = hidpp_root_get_feature(hidpp,
1299                                      HIDPP_PAGE_HI_RESOLUTION_SCROLLING,
1300                                      &feature_index,
1301                                      &feature_type);
1302         if (ret)
1303                 return ret;
1304
1305         params[0] = enabled ? BIT(0) : 0;
1306         ret = hidpp_send_fap_command_sync(hidpp, feature_index,
1307                                           CMD_HI_RESOLUTION_SCROLLING_SET_HIGHRES_SCROLLING_MODE,
1308                                           params, sizeof(params), &response);
1309         if (ret)
1310                 return ret;
1311         *multiplier = response.fap.params[1];
1312         return 0;
1313 }
1314
1315 /* -------------------------------------------------------------------------- */
1316 /* 0x2121: HiRes Wheel                                                        */
1317 /* -------------------------------------------------------------------------- */
1318
1319 #define HIDPP_PAGE_HIRES_WHEEL          0x2121
1320
1321 #define CMD_HIRES_WHEEL_GET_WHEEL_CAPABILITY    0x00
1322 #define CMD_HIRES_WHEEL_SET_WHEEL_MODE          0x20
1323
1324 static int hidpp_hrw_get_wheel_capability(struct hidpp_device *hidpp,
1325         u8 *multiplier)
1326 {
1327         u8 feature_index;
1328         u8 feature_type;
1329         int ret;
1330         struct hidpp_report response;
1331
1332         ret = hidpp_root_get_feature(hidpp, HIDPP_PAGE_HIRES_WHEEL,
1333                                      &feature_index, &feature_type);
1334         if (ret)
1335                 goto return_default;
1336
1337         ret = hidpp_send_fap_command_sync(hidpp, feature_index,
1338                                           CMD_HIRES_WHEEL_GET_WHEEL_CAPABILITY,
1339                                           NULL, 0, &response);
1340         if (ret)
1341                 goto return_default;
1342
1343         *multiplier = response.fap.params[0];
1344         return 0;
1345 return_default:
1346         hid_warn(hidpp->hid_dev,
1347                  "Couldn't get wheel multiplier (error %d)\n", ret);
1348         return ret;
1349 }
1350
1351 static int hidpp_hrw_set_wheel_mode(struct hidpp_device *hidpp, bool invert,
1352         bool high_resolution, bool use_hidpp)
1353 {
1354         u8 feature_index;
1355         u8 feature_type;
1356         int ret;
1357         u8 params[1];
1358         struct hidpp_report response;
1359
1360         ret = hidpp_root_get_feature(hidpp, HIDPP_PAGE_HIRES_WHEEL,
1361                                      &feature_index, &feature_type);
1362         if (ret)
1363                 return ret;
1364
1365         params[0] = (invert          ? BIT(2) : 0) |
1366                     (high_resolution ? BIT(1) : 0) |
1367                     (use_hidpp       ? BIT(0) : 0);
1368
1369         return hidpp_send_fap_command_sync(hidpp, feature_index,
1370                                            CMD_HIRES_WHEEL_SET_WHEEL_MODE,
1371                                            params, sizeof(params), &response);
1372 }
1373
1374 /* -------------------------------------------------------------------------- */
1375 /* 0x4301: Solar Keyboard                                                     */
1376 /* -------------------------------------------------------------------------- */
1377
1378 #define HIDPP_PAGE_SOLAR_KEYBOARD                       0x4301
1379
1380 #define CMD_SOLAR_SET_LIGHT_MEASURE                     0x00
1381
1382 #define EVENT_SOLAR_BATTERY_BROADCAST                   0x00
1383 #define EVENT_SOLAR_BATTERY_LIGHT_MEASURE               0x10
1384 #define EVENT_SOLAR_CHECK_LIGHT_BUTTON                  0x20
1385
1386 static int hidpp_solar_request_battery_event(struct hidpp_device *hidpp)
1387 {
1388         struct hidpp_report response;
1389         u8 params[2] = { 1, 1 };
1390         u8 feature_type;
1391         int ret;
1392
1393         if (hidpp->battery.feature_index == 0xff) {
1394                 ret = hidpp_root_get_feature(hidpp,
1395                                              HIDPP_PAGE_SOLAR_KEYBOARD,
1396                                              &hidpp->battery.solar_feature_index,
1397                                              &feature_type);
1398                 if (ret)
1399                         return ret;
1400         }
1401
1402         ret = hidpp_send_fap_command_sync(hidpp,
1403                                           hidpp->battery.solar_feature_index,
1404                                           CMD_SOLAR_SET_LIGHT_MEASURE,
1405                                           params, 2, &response);
1406         if (ret > 0) {
1407                 hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
1408                         __func__, ret);
1409                 return -EPROTO;
1410         }
1411         if (ret)
1412                 return ret;
1413
1414         hidpp->capabilities |= HIDPP_CAPABILITY_BATTERY_MILEAGE;
1415
1416         return 0;
1417 }
1418
1419 static int hidpp_solar_battery_event(struct hidpp_device *hidpp,
1420                                      u8 *data, int size)
1421 {
1422         struct hidpp_report *report = (struct hidpp_report *)data;
1423         int capacity, lux, status;
1424         u8 function;
1425
1426         function = report->fap.funcindex_clientid;
1427
1428
1429         if (report->fap.feature_index != hidpp->battery.solar_feature_index ||
1430             !(function == EVENT_SOLAR_BATTERY_BROADCAST ||
1431               function == EVENT_SOLAR_BATTERY_LIGHT_MEASURE ||
1432               function == EVENT_SOLAR_CHECK_LIGHT_BUTTON))
1433                 return 0;
1434
1435         capacity = report->fap.params[0];
1436
1437         switch (function) {
1438         case EVENT_SOLAR_BATTERY_LIGHT_MEASURE:
1439                 lux = (report->fap.params[1] << 8) | report->fap.params[2];
1440                 if (lux > 200)
1441                         status = POWER_SUPPLY_STATUS_CHARGING;
1442                 else
1443                         status = POWER_SUPPLY_STATUS_DISCHARGING;
1444                 break;
1445         case EVENT_SOLAR_CHECK_LIGHT_BUTTON:
1446         default:
1447                 if (capacity < hidpp->battery.capacity)
1448                         status = POWER_SUPPLY_STATUS_DISCHARGING;
1449                 else
1450                         status = POWER_SUPPLY_STATUS_CHARGING;
1451
1452         }
1453
1454         if (capacity == 100)
1455                 status = POWER_SUPPLY_STATUS_FULL;
1456
1457         hidpp->battery.online = true;
1458         if (capacity != hidpp->battery.capacity ||
1459             status != hidpp->battery.status) {
1460                 hidpp->battery.capacity = capacity;
1461                 hidpp->battery.status = status;
1462                 if (hidpp->battery.ps)
1463                         power_supply_changed(hidpp->battery.ps);
1464         }
1465
1466         return 0;
1467 }
1468
1469 /* -------------------------------------------------------------------------- */
1470 /* 0x6010: Touchpad FW items                                                  */
1471 /* -------------------------------------------------------------------------- */
1472
1473 #define HIDPP_PAGE_TOUCHPAD_FW_ITEMS                    0x6010
1474
1475 #define CMD_TOUCHPAD_FW_ITEMS_SET                       0x10
1476
1477 struct hidpp_touchpad_fw_items {
1478         uint8_t presence;
1479         uint8_t desired_state;
1480         uint8_t state;
1481         uint8_t persistent;
1482 };
1483
1484 /**
1485  * send a set state command to the device by reading the current items->state
1486  * field. items is then filled with the current state.
1487  */
1488 static int hidpp_touchpad_fw_items_set(struct hidpp_device *hidpp,
1489                                        u8 feature_index,
1490                                        struct hidpp_touchpad_fw_items *items)
1491 {
1492         struct hidpp_report response;
1493         int ret;
1494         u8 *params = (u8 *)response.fap.params;
1495
1496         ret = hidpp_send_fap_command_sync(hidpp, feature_index,
1497                 CMD_TOUCHPAD_FW_ITEMS_SET, &items->state, 1, &response);
1498
1499         if (ret > 0) {
1500                 hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
1501                         __func__, ret);
1502                 return -EPROTO;
1503         }
1504         if (ret)
1505                 return ret;
1506
1507         items->presence = params[0];
1508         items->desired_state = params[1];
1509         items->state = params[2];
1510         items->persistent = params[3];
1511
1512         return 0;
1513 }
1514
1515 /* -------------------------------------------------------------------------- */
1516 /* 0x6100: TouchPadRawXY                                                      */
1517 /* -------------------------------------------------------------------------- */
1518
1519 #define HIDPP_PAGE_TOUCHPAD_RAW_XY                      0x6100
1520
1521 #define CMD_TOUCHPAD_GET_RAW_INFO                       0x01
1522 #define CMD_TOUCHPAD_SET_RAW_REPORT_STATE               0x21
1523
1524 #define EVENT_TOUCHPAD_RAW_XY                           0x00
1525
1526 #define TOUCHPAD_RAW_XY_ORIGIN_LOWER_LEFT               0x01
1527 #define TOUCHPAD_RAW_XY_ORIGIN_UPPER_LEFT               0x03
1528
1529 struct hidpp_touchpad_raw_info {
1530         u16 x_size;
1531         u16 y_size;
1532         u8 z_range;
1533         u8 area_range;
1534         u8 timestamp_unit;
1535         u8 maxcontacts;
1536         u8 origin;
1537         u16 res;
1538 };
1539
1540 struct hidpp_touchpad_raw_xy_finger {
1541         u8 contact_type;
1542         u8 contact_status;
1543         u16 x;
1544         u16 y;
1545         u8 z;
1546         u8 area;
1547         u8 finger_id;
1548 };
1549
1550 struct hidpp_touchpad_raw_xy {
1551         u16 timestamp;
1552         struct hidpp_touchpad_raw_xy_finger fingers[2];
1553         u8 spurious_flag;
1554         u8 end_of_frame;
1555         u8 finger_count;
1556         u8 button;
1557 };
1558
1559 static int hidpp_touchpad_get_raw_info(struct hidpp_device *hidpp,
1560         u8 feature_index, struct hidpp_touchpad_raw_info *raw_info)
1561 {
1562         struct hidpp_report response;
1563         int ret;
1564         u8 *params = (u8 *)response.fap.params;
1565
1566         ret = hidpp_send_fap_command_sync(hidpp, feature_index,
1567                 CMD_TOUCHPAD_GET_RAW_INFO, NULL, 0, &response);
1568
1569         if (ret > 0) {
1570                 hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
1571                         __func__, ret);
1572                 return -EPROTO;
1573         }
1574         if (ret)
1575                 return ret;
1576
1577         raw_info->x_size = get_unaligned_be16(&params[0]);
1578         raw_info->y_size = get_unaligned_be16(&params[2]);
1579         raw_info->z_range = params[4];
1580         raw_info->area_range = params[5];
1581         raw_info->maxcontacts = params[7];
1582         raw_info->origin = params[8];
1583         /* res is given in unit per inch */
1584         raw_info->res = get_unaligned_be16(&params[13]) * 2 / 51;
1585
1586         return ret;
1587 }
1588
1589 static int hidpp_touchpad_set_raw_report_state(struct hidpp_device *hidpp_dev,
1590                 u8 feature_index, bool send_raw_reports,
1591                 bool sensor_enhanced_settings)
1592 {
1593         struct hidpp_report response;
1594
1595         /*
1596          * Params:
1597          *   bit 0 - enable raw
1598          *   bit 1 - 16bit Z, no area
1599          *   bit 2 - enhanced sensitivity
1600          *   bit 3 - width, height (4 bits each) instead of area
1601          *   bit 4 - send raw + gestures (degrades smoothness)
1602          *   remaining bits - reserved
1603          */
1604         u8 params = send_raw_reports | (sensor_enhanced_settings << 2);
1605
1606         return hidpp_send_fap_command_sync(hidpp_dev, feature_index,
1607                 CMD_TOUCHPAD_SET_RAW_REPORT_STATE, &params, 1, &response);
1608 }
1609
1610 static void hidpp_touchpad_touch_event(u8 *data,
1611         struct hidpp_touchpad_raw_xy_finger *finger)
1612 {
1613         u8 x_m = data[0] << 2;
1614         u8 y_m = data[2] << 2;
1615
1616         finger->x = x_m << 6 | data[1];
1617         finger->y = y_m << 6 | data[3];
1618
1619         finger->contact_type = data[0] >> 6;
1620         finger->contact_status = data[2] >> 6;
1621
1622         finger->z = data[4];
1623         finger->area = data[5];
1624         finger->finger_id = data[6] >> 4;
1625 }
1626
1627 static void hidpp_touchpad_raw_xy_event(struct hidpp_device *hidpp_dev,
1628                 u8 *data, struct hidpp_touchpad_raw_xy *raw_xy)
1629 {
1630         memset(raw_xy, 0, sizeof(struct hidpp_touchpad_raw_xy));
1631         raw_xy->end_of_frame = data[8] & 0x01;
1632         raw_xy->spurious_flag = (data[8] >> 1) & 0x01;
1633         raw_xy->finger_count = data[15] & 0x0f;
1634         raw_xy->button = (data[8] >> 2) & 0x01;
1635
1636         if (raw_xy->finger_count) {
1637                 hidpp_touchpad_touch_event(&data[2], &raw_xy->fingers[0]);
1638                 hidpp_touchpad_touch_event(&data[9], &raw_xy->fingers[1]);
1639         }
1640 }
1641
1642 /* -------------------------------------------------------------------------- */
1643 /* 0x8123: Force feedback support                                             */
1644 /* -------------------------------------------------------------------------- */
1645
1646 #define HIDPP_FF_GET_INFO               0x01
1647 #define HIDPP_FF_RESET_ALL              0x11
1648 #define HIDPP_FF_DOWNLOAD_EFFECT        0x21
1649 #define HIDPP_FF_SET_EFFECT_STATE       0x31
1650 #define HIDPP_FF_DESTROY_EFFECT         0x41
1651 #define HIDPP_FF_GET_APERTURE           0x51
1652 #define HIDPP_FF_SET_APERTURE           0x61
1653 #define HIDPP_FF_GET_GLOBAL_GAINS       0x71
1654 #define HIDPP_FF_SET_GLOBAL_GAINS       0x81
1655
1656 #define HIDPP_FF_EFFECT_STATE_GET       0x00
1657 #define HIDPP_FF_EFFECT_STATE_STOP      0x01
1658 #define HIDPP_FF_EFFECT_STATE_PLAY      0x02
1659 #define HIDPP_FF_EFFECT_STATE_PAUSE     0x03
1660
1661 #define HIDPP_FF_EFFECT_CONSTANT        0x00
1662 #define HIDPP_FF_EFFECT_PERIODIC_SINE           0x01
1663 #define HIDPP_FF_EFFECT_PERIODIC_SQUARE         0x02
1664 #define HIDPP_FF_EFFECT_PERIODIC_TRIANGLE       0x03
1665 #define HIDPP_FF_EFFECT_PERIODIC_SAWTOOTHUP     0x04
1666 #define HIDPP_FF_EFFECT_PERIODIC_SAWTOOTHDOWN   0x05
1667 #define HIDPP_FF_EFFECT_SPRING          0x06
1668 #define HIDPP_FF_EFFECT_DAMPER          0x07
1669 #define HIDPP_FF_EFFECT_FRICTION        0x08
1670 #define HIDPP_FF_EFFECT_INERTIA         0x09
1671 #define HIDPP_FF_EFFECT_RAMP            0x0A
1672
1673 #define HIDPP_FF_EFFECT_AUTOSTART       0x80
1674
1675 #define HIDPP_FF_EFFECTID_NONE          -1
1676 #define HIDPP_FF_EFFECTID_AUTOCENTER    -2
1677 #define HIDPP_AUTOCENTER_PARAMS_LENGTH  18
1678
1679 #define HIDPP_FF_MAX_PARAMS     20
1680 #define HIDPP_FF_RESERVED_SLOTS 1
1681
1682 struct hidpp_ff_private_data {
1683         struct hidpp_device *hidpp;
1684         u8 feature_index;
1685         u8 version;
1686         u16 gain;
1687         s16 range;
1688         u8 slot_autocenter;
1689         u8 num_effects;
1690         int *effect_ids;
1691         struct workqueue_struct *wq;
1692         atomic_t workqueue_size;
1693 };
1694
1695 struct hidpp_ff_work_data {
1696         struct work_struct work;
1697         struct hidpp_ff_private_data *data;
1698         int effect_id;
1699         u8 command;
1700         u8 params[HIDPP_FF_MAX_PARAMS];
1701         u8 size;
1702 };
1703
1704 static const signed short hidpp_ff_effects[] = {
1705         FF_CONSTANT,
1706         FF_PERIODIC,
1707         FF_SINE,
1708         FF_SQUARE,
1709         FF_SAW_UP,
1710         FF_SAW_DOWN,
1711         FF_TRIANGLE,
1712         FF_SPRING,
1713         FF_DAMPER,
1714         FF_AUTOCENTER,
1715         FF_GAIN,
1716         -1
1717 };
1718
1719 static const signed short hidpp_ff_effects_v2[] = {
1720         FF_RAMP,
1721         FF_FRICTION,
1722         FF_INERTIA,
1723         -1
1724 };
1725
1726 static const u8 HIDPP_FF_CONDITION_CMDS[] = {
1727         HIDPP_FF_EFFECT_SPRING,
1728         HIDPP_FF_EFFECT_FRICTION,
1729         HIDPP_FF_EFFECT_DAMPER,
1730         HIDPP_FF_EFFECT_INERTIA
1731 };
1732
1733 static const char *HIDPP_FF_CONDITION_NAMES[] = {
1734         "spring",
1735         "friction",
1736         "damper",
1737         "inertia"
1738 };
1739
1740
1741 static u8 hidpp_ff_find_effect(struct hidpp_ff_private_data *data, int effect_id)
1742 {
1743         int i;
1744
1745         for (i = 0; i < data->num_effects; i++)
1746                 if (data->effect_ids[i] == effect_id)
1747                         return i+1;
1748
1749         return 0;
1750 }
1751
1752 static void hidpp_ff_work_handler(struct work_struct *w)
1753 {
1754         struct hidpp_ff_work_data *wd = container_of(w, struct hidpp_ff_work_data, work);
1755         struct hidpp_ff_private_data *data = wd->data;
1756         struct hidpp_report response;
1757         u8 slot;
1758         int ret;
1759
1760         /* add slot number if needed */
1761         switch (wd->effect_id) {
1762         case HIDPP_FF_EFFECTID_AUTOCENTER:
1763                 wd->params[0] = data->slot_autocenter;
1764                 break;
1765         case HIDPP_FF_EFFECTID_NONE:
1766                 /* leave slot as zero */
1767                 break;
1768         default:
1769                 /* find current slot for effect */
1770                 wd->params[0] = hidpp_ff_find_effect(data, wd->effect_id);
1771                 break;
1772         }
1773
1774         /* send command and wait for reply */
1775         ret = hidpp_send_fap_command_sync(data->hidpp, data->feature_index,
1776                 wd->command, wd->params, wd->size, &response);
1777
1778         if (ret) {
1779                 hid_err(data->hidpp->hid_dev, "Failed to send command to device!\n");
1780                 goto out;
1781         }
1782
1783         /* parse return data */
1784         switch (wd->command) {
1785         case HIDPP_FF_DOWNLOAD_EFFECT:
1786                 slot = response.fap.params[0];
1787                 if (slot > 0 && slot <= data->num_effects) {
1788                         if (wd->effect_id >= 0)
1789                                 /* regular effect uploaded */
1790                                 data->effect_ids[slot-1] = wd->effect_id;
1791                         else if (wd->effect_id >= HIDPP_FF_EFFECTID_AUTOCENTER)
1792                                 /* autocenter spring uploaded */
1793                                 data->slot_autocenter = slot;
1794                 }
1795                 break;
1796         case HIDPP_FF_DESTROY_EFFECT:
1797                 if (wd->effect_id >= 0)
1798                         /* regular effect destroyed */
1799                         data->effect_ids[wd->params[0]-1] = -1;
1800                 else if (wd->effect_id >= HIDPP_FF_EFFECTID_AUTOCENTER)
1801                         /* autocenter spring destoyed */
1802                         data->slot_autocenter = 0;
1803                 break;
1804         case HIDPP_FF_SET_GLOBAL_GAINS:
1805                 data->gain = (wd->params[0] << 8) + wd->params[1];
1806                 break;
1807         case HIDPP_FF_SET_APERTURE:
1808                 data->range = (wd->params[0] << 8) + wd->params[1];
1809                 break;
1810         default:
1811                 /* no action needed */
1812                 break;
1813         }
1814
1815 out:
1816         atomic_dec(&data->workqueue_size);
1817         kfree(wd);
1818 }
1819
1820 static int hidpp_ff_queue_work(struct hidpp_ff_private_data *data, int effect_id, u8 command, u8 *params, u8 size)
1821 {
1822         struct hidpp_ff_work_data *wd = kzalloc(sizeof(*wd), GFP_KERNEL);
1823         int s;
1824
1825         if (!wd)
1826                 return -ENOMEM;
1827
1828         INIT_WORK(&wd->work, hidpp_ff_work_handler);
1829
1830         wd->data = data;
1831         wd->effect_id = effect_id;
1832         wd->command = command;
1833         wd->size = size;
1834         memcpy(wd->params, params, size);
1835
1836         atomic_inc(&data->workqueue_size);
1837         queue_work(data->wq, &wd->work);
1838
1839         /* warn about excessive queue size */
1840         s = atomic_read(&data->workqueue_size);
1841         if (s >= 20 && s % 20 == 0)
1842                 hid_warn(data->hidpp->hid_dev, "Force feedback command queue contains %d commands, causing substantial delays!", s);
1843
1844         return 0;
1845 }
1846
1847 static int hidpp_ff_upload_effect(struct input_dev *dev, struct ff_effect *effect, struct ff_effect *old)
1848 {
1849         struct hidpp_ff_private_data *data = dev->ff->private;
1850         u8 params[20];
1851         u8 size;
1852         int force;
1853
1854         /* set common parameters */
1855         params[2] = effect->replay.length >> 8;
1856         params[3] = effect->replay.length & 255;
1857         params[4] = effect->replay.delay >> 8;
1858         params[5] = effect->replay.delay & 255;
1859
1860         switch (effect->type) {
1861         case FF_CONSTANT:
1862                 force = (effect->u.constant.level * fixp_sin16((effect->direction * 360) >> 16)) >> 15;
1863                 params[1] = HIDPP_FF_EFFECT_CONSTANT;
1864                 params[6] = force >> 8;
1865                 params[7] = force & 255;
1866                 params[8] = effect->u.constant.envelope.attack_level >> 7;
1867                 params[9] = effect->u.constant.envelope.attack_length >> 8;
1868                 params[10] = effect->u.constant.envelope.attack_length & 255;
1869                 params[11] = effect->u.constant.envelope.fade_level >> 7;
1870                 params[12] = effect->u.constant.envelope.fade_length >> 8;
1871                 params[13] = effect->u.constant.envelope.fade_length & 255;
1872                 size = 14;
1873                 dbg_hid("Uploading constant force level=%d in dir %d = %d\n",
1874                                 effect->u.constant.level,
1875                                 effect->direction, force);
1876                 dbg_hid("          envelope attack=(%d, %d ms) fade=(%d, %d ms)\n",
1877                                 effect->u.constant.envelope.attack_level,
1878                                 effect->u.constant.envelope.attack_length,
1879                                 effect->u.constant.envelope.fade_level,
1880                                 effect->u.constant.envelope.fade_length);
1881                 break;
1882         case FF_PERIODIC:
1883         {
1884                 switch (effect->u.periodic.waveform) {
1885                 case FF_SINE:
1886                         params[1] = HIDPP_FF_EFFECT_PERIODIC_SINE;
1887                         break;
1888                 case FF_SQUARE:
1889                         params[1] = HIDPP_FF_EFFECT_PERIODIC_SQUARE;
1890                         break;
1891                 case FF_SAW_UP:
1892                         params[1] = HIDPP_FF_EFFECT_PERIODIC_SAWTOOTHUP;
1893                         break;
1894                 case FF_SAW_DOWN:
1895                         params[1] = HIDPP_FF_EFFECT_PERIODIC_SAWTOOTHDOWN;
1896                         break;
1897                 case FF_TRIANGLE:
1898                         params[1] = HIDPP_FF_EFFECT_PERIODIC_TRIANGLE;
1899                         break;
1900                 default:
1901                         hid_err(data->hidpp->hid_dev, "Unexpected periodic waveform type %i!\n", effect->u.periodic.waveform);
1902                         return -EINVAL;
1903                 }
1904                 force = (effect->u.periodic.magnitude * fixp_sin16((effect->direction * 360) >> 16)) >> 15;
1905                 params[6] = effect->u.periodic.magnitude >> 8;
1906                 params[7] = effect->u.periodic.magnitude & 255;
1907                 params[8] = effect->u.periodic.offset >> 8;
1908                 params[9] = effect->u.periodic.offset & 255;
1909                 params[10] = effect->u.periodic.period >> 8;
1910                 params[11] = effect->u.periodic.period & 255;
1911                 params[12] = effect->u.periodic.phase >> 8;
1912                 params[13] = effect->u.periodic.phase & 255;
1913                 params[14] = effect->u.periodic.envelope.attack_level >> 7;
1914                 params[15] = effect->u.periodic.envelope.attack_length >> 8;
1915                 params[16] = effect->u.periodic.envelope.attack_length & 255;
1916                 params[17] = effect->u.periodic.envelope.fade_level >> 7;
1917                 params[18] = effect->u.periodic.envelope.fade_length >> 8;
1918                 params[19] = effect->u.periodic.envelope.fade_length & 255;
1919                 size = 20;
1920                 dbg_hid("Uploading periodic force mag=%d/dir=%d, offset=%d, period=%d ms, phase=%d\n",
1921                                 effect->u.periodic.magnitude, effect->direction,
1922                                 effect->u.periodic.offset,
1923                                 effect->u.periodic.period,
1924                                 effect->u.periodic.phase);
1925                 dbg_hid("          envelope attack=(%d, %d ms) fade=(%d, %d ms)\n",
1926                                 effect->u.periodic.envelope.attack_level,
1927                                 effect->u.periodic.envelope.attack_length,
1928                                 effect->u.periodic.envelope.fade_level,
1929                                 effect->u.periodic.envelope.fade_length);
1930                 break;
1931         }
1932         case FF_RAMP:
1933                 params[1] = HIDPP_FF_EFFECT_RAMP;
1934                 force = (effect->u.ramp.start_level * fixp_sin16((effect->direction * 360) >> 16)) >> 15;
1935                 params[6] = force >> 8;
1936                 params[7] = force & 255;
1937                 force = (effect->u.ramp.end_level * fixp_sin16((effect->direction * 360) >> 16)) >> 15;
1938                 params[8] = force >> 8;
1939                 params[9] = force & 255;
1940                 params[10] = effect->u.ramp.envelope.attack_level >> 7;
1941                 params[11] = effect->u.ramp.envelope.attack_length >> 8;
1942                 params[12] = effect->u.ramp.envelope.attack_length & 255;
1943                 params[13] = effect->u.ramp.envelope.fade_level >> 7;
1944                 params[14] = effect->u.ramp.envelope.fade_length >> 8;
1945                 params[15] = effect->u.ramp.envelope.fade_length & 255;
1946                 size = 16;
1947                 dbg_hid("Uploading ramp force level=%d -> %d in dir %d = %d\n",
1948                                 effect->u.ramp.start_level,
1949                                 effect->u.ramp.end_level,
1950                                 effect->direction, force);
1951                 dbg_hid("          envelope attack=(%d, %d ms) fade=(%d, %d ms)\n",
1952                                 effect->u.ramp.envelope.attack_level,
1953                                 effect->u.ramp.envelope.attack_length,
1954                                 effect->u.ramp.envelope.fade_level,
1955                                 effect->u.ramp.envelope.fade_length);
1956                 break;
1957         case FF_FRICTION:
1958         case FF_INERTIA:
1959         case FF_SPRING:
1960         case FF_DAMPER:
1961                 params[1] = HIDPP_FF_CONDITION_CMDS[effect->type - FF_SPRING];
1962                 params[6] = effect->u.condition[0].left_saturation >> 9;
1963                 params[7] = (effect->u.condition[0].left_saturation >> 1) & 255;
1964                 params[8] = effect->u.condition[0].left_coeff >> 8;
1965                 params[9] = effect->u.condition[0].left_coeff & 255;
1966                 params[10] = effect->u.condition[0].deadband >> 9;
1967                 params[11] = (effect->u.condition[0].deadband >> 1) & 255;
1968                 params[12] = effect->u.condition[0].center >> 8;
1969                 params[13] = effect->u.condition[0].center & 255;
1970                 params[14] = effect->u.condition[0].right_coeff >> 8;
1971                 params[15] = effect->u.condition[0].right_coeff & 255;
1972                 params[16] = effect->u.condition[0].right_saturation >> 9;
1973                 params[17] = (effect->u.condition[0].right_saturation >> 1) & 255;
1974                 size = 18;
1975                 dbg_hid("Uploading %s force left coeff=%d, left sat=%d, right coeff=%d, right sat=%d\n",
1976                                 HIDPP_FF_CONDITION_NAMES[effect->type - FF_SPRING],
1977                                 effect->u.condition[0].left_coeff,
1978                                 effect->u.condition[0].left_saturation,
1979                                 effect->u.condition[0].right_coeff,
1980                                 effect->u.condition[0].right_saturation);
1981                 dbg_hid("          deadband=%d, center=%d\n",
1982                                 effect->u.condition[0].deadband,
1983                                 effect->u.condition[0].center);
1984                 break;
1985         default:
1986                 hid_err(data->hidpp->hid_dev, "Unexpected force type %i!\n", effect->type);
1987                 return -EINVAL;
1988         }
1989
1990         return hidpp_ff_queue_work(data, effect->id, HIDPP_FF_DOWNLOAD_EFFECT, params, size);
1991 }
1992
1993 static int hidpp_ff_playback(struct input_dev *dev, int effect_id, int value)
1994 {
1995         struct hidpp_ff_private_data *data = dev->ff->private;
1996         u8 params[2];
1997
1998         params[1] = value ? HIDPP_FF_EFFECT_STATE_PLAY : HIDPP_FF_EFFECT_STATE_STOP;
1999
2000         dbg_hid("St%sing playback of effect %d.\n", value?"art":"opp", effect_id);
2001
2002         return hidpp_ff_queue_work(data, effect_id, HIDPP_FF_SET_EFFECT_STATE, params, ARRAY_SIZE(params));
2003 }
2004
2005 static int hidpp_ff_erase_effect(struct input_dev *dev, int effect_id)
2006 {
2007         struct hidpp_ff_private_data *data = dev->ff->private;
2008         u8 slot = 0;
2009
2010         dbg_hid("Erasing effect %d.\n", effect_id);
2011
2012         return hidpp_ff_queue_work(data, effect_id, HIDPP_FF_DESTROY_EFFECT, &slot, 1);
2013 }
2014
2015 static void hidpp_ff_set_autocenter(struct input_dev *dev, u16 magnitude)
2016 {
2017         struct hidpp_ff_private_data *data = dev->ff->private;
2018         u8 params[HIDPP_AUTOCENTER_PARAMS_LENGTH];
2019
2020         dbg_hid("Setting autocenter to %d.\n", magnitude);
2021
2022         /* start a standard spring effect */
2023         params[1] = HIDPP_FF_EFFECT_SPRING | HIDPP_FF_EFFECT_AUTOSTART;
2024         /* zero delay and duration */
2025         params[2] = params[3] = params[4] = params[5] = 0;
2026         /* set coeff to 25% of saturation */
2027         params[8] = params[14] = magnitude >> 11;
2028         params[9] = params[15] = (magnitude >> 3) & 255;
2029         params[6] = params[16] = magnitude >> 9;
2030         params[7] = params[17] = (magnitude >> 1) & 255;
2031         /* zero deadband and center */
2032         params[10] = params[11] = params[12] = params[13] = 0;
2033
2034         hidpp_ff_queue_work(data, HIDPP_FF_EFFECTID_AUTOCENTER, HIDPP_FF_DOWNLOAD_EFFECT, params, ARRAY_SIZE(params));
2035 }
2036
2037 static void hidpp_ff_set_gain(struct input_dev *dev, u16 gain)
2038 {
2039         struct hidpp_ff_private_data *data = dev->ff->private;
2040         u8 params[4];
2041
2042         dbg_hid("Setting gain to %d.\n", gain);
2043
2044         params[0] = gain >> 8;
2045         params[1] = gain & 255;
2046         params[2] = 0; /* no boost */
2047         params[3] = 0;
2048
2049         hidpp_ff_queue_work(data, HIDPP_FF_EFFECTID_NONE, HIDPP_FF_SET_GLOBAL_GAINS, params, ARRAY_SIZE(params));
2050 }
2051
2052 static ssize_t hidpp_ff_range_show(struct device *dev, struct device_attribute *attr, char *buf)
2053 {
2054         struct hid_device *hid = to_hid_device(dev);
2055         struct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list);
2056         struct input_dev *idev = hidinput->input;
2057         struct hidpp_ff_private_data *data = idev->ff->private;
2058
2059         return scnprintf(buf, PAGE_SIZE, "%u\n", data->range);
2060 }
2061
2062 static ssize_t hidpp_ff_range_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
2063 {
2064         struct hid_device *hid = to_hid_device(dev);
2065         struct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list);
2066         struct input_dev *idev = hidinput->input;
2067         struct hidpp_ff_private_data *data = idev->ff->private;
2068         u8 params[2];
2069         int range = simple_strtoul(buf, NULL, 10);
2070
2071         range = clamp(range, 180, 900);
2072
2073         params[0] = range >> 8;
2074         params[1] = range & 0x00FF;
2075
2076         hidpp_ff_queue_work(data, -1, HIDPP_FF_SET_APERTURE, params, ARRAY_SIZE(params));
2077
2078         return count;
2079 }
2080
2081 static DEVICE_ATTR(range, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH, hidpp_ff_range_show, hidpp_ff_range_store);
2082
2083 static void hidpp_ff_destroy(struct ff_device *ff)
2084 {
2085         struct hidpp_ff_private_data *data = ff->private;
2086         struct hid_device *hid = data->hidpp->hid_dev;
2087
2088         hid_info(hid, "Unloading HID++ force feedback.\n");
2089
2090         device_remove_file(&hid->dev, &dev_attr_range);
2091         destroy_workqueue(data->wq);
2092         kfree(data->effect_ids);
2093 }
2094
2095 static int hidpp_ff_init(struct hidpp_device *hidpp,
2096                          struct hidpp_ff_private_data *data)
2097 {
2098         struct hid_device *hid = hidpp->hid_dev;
2099         struct hid_input *hidinput;
2100         struct input_dev *dev;
2101         const struct usb_device_descriptor *udesc = &(hid_to_usb_dev(hid)->descriptor);
2102         const u16 bcdDevice = le16_to_cpu(udesc->bcdDevice);
2103         struct ff_device *ff;
2104         int error, j, num_slots = data->num_effects;
2105         u8 version;
2106
2107         if (list_empty(&hid->inputs)) {
2108                 hid_err(hid, "no inputs found\n");
2109                 return -ENODEV;
2110         }
2111         hidinput = list_entry(hid->inputs.next, struct hid_input, list);
2112         dev = hidinput->input;
2113
2114         if (!dev) {
2115                 hid_err(hid, "Struct input_dev not set!\n");
2116                 return -EINVAL;
2117         }
2118
2119         /* Get firmware release */
2120         version = bcdDevice & 255;
2121
2122         /* Set supported force feedback capabilities */
2123         for (j = 0; hidpp_ff_effects[j] >= 0; j++)
2124                 set_bit(hidpp_ff_effects[j], dev->ffbit);
2125         if (version > 1)
2126                 for (j = 0; hidpp_ff_effects_v2[j] >= 0; j++)
2127                         set_bit(hidpp_ff_effects_v2[j], dev->ffbit);
2128
2129         error = input_ff_create(dev, num_slots);
2130
2131         if (error) {
2132                 hid_err(dev, "Failed to create FF device!\n");
2133                 return error;
2134         }
2135         /*
2136          * Create a copy of passed data, so we can transfer memory
2137          * ownership to FF core
2138          */
2139         data = kmemdup(data, sizeof(*data), GFP_KERNEL);
2140         if (!data)
2141                 return -ENOMEM;
2142         data->effect_ids = kcalloc(num_slots, sizeof(int), GFP_KERNEL);
2143         if (!data->effect_ids) {
2144                 kfree(data);
2145                 return -ENOMEM;
2146         }
2147         data->wq = create_singlethread_workqueue("hidpp-ff-sendqueue");
2148         if (!data->wq) {
2149                 kfree(data->effect_ids);
2150                 kfree(data);
2151                 return -ENOMEM;
2152         }
2153
2154         data->hidpp = hidpp;
2155         data->version = version;
2156         for (j = 0; j < num_slots; j++)
2157                 data->effect_ids[j] = -1;
2158
2159         ff = dev->ff;
2160         ff->private = data;
2161
2162         ff->upload = hidpp_ff_upload_effect;
2163         ff->erase = hidpp_ff_erase_effect;
2164         ff->playback = hidpp_ff_playback;
2165         ff->set_gain = hidpp_ff_set_gain;
2166         ff->set_autocenter = hidpp_ff_set_autocenter;
2167         ff->destroy = hidpp_ff_destroy;
2168
2169         /* Create sysfs interface */
2170         error = device_create_file(&(hidpp->hid_dev->dev), &dev_attr_range);
2171         if (error)
2172                 hid_warn(hidpp->hid_dev, "Unable to create sysfs interface for \"range\", errno %d!\n", error);
2173
2174         /* init the hardware command queue */
2175         atomic_set(&data->workqueue_size, 0);
2176
2177         hid_info(hid, "Force feedback support loaded (firmware release %d).\n",
2178                  version);
2179
2180         return 0;
2181 }
2182
2183 /* ************************************************************************** */
2184 /*                                                                            */
2185 /* Device Support                                                             */
2186 /*                                                                            */
2187 /* ************************************************************************** */
2188
2189 /* -------------------------------------------------------------------------- */
2190 /* Touchpad HID++ devices                                                     */
2191 /* -------------------------------------------------------------------------- */
2192
2193 #define WTP_MANUAL_RESOLUTION                           39
2194
2195 struct wtp_data {
2196         u16 x_size, y_size;
2197         u8 finger_count;
2198         u8 mt_feature_index;
2199         u8 button_feature_index;
2200         u8 maxcontacts;
2201         bool flip_y;
2202         unsigned int resolution;
2203 };
2204
2205 static int wtp_input_mapping(struct hid_device *hdev, struct hid_input *hi,
2206                 struct hid_field *field, struct hid_usage *usage,
2207                 unsigned long **bit, int *max)
2208 {
2209         return -1;
2210 }
2211
2212 static void wtp_populate_input(struct hidpp_device *hidpp,
2213                                struct input_dev *input_dev)
2214 {
2215         struct wtp_data *wd = hidpp->private_data;
2216
2217         __set_bit(EV_ABS, input_dev->evbit);
2218         __set_bit(EV_KEY, input_dev->evbit);
2219         __clear_bit(EV_REL, input_dev->evbit);
2220         __clear_bit(EV_LED, input_dev->evbit);
2221
2222         input_set_abs_params(input_dev, ABS_MT_POSITION_X, 0, wd->x_size, 0, 0);
2223         input_abs_set_res(input_dev, ABS_MT_POSITION_X, wd->resolution);
2224         input_set_abs_params(input_dev, ABS_MT_POSITION_Y, 0, wd->y_size, 0, 0);
2225         input_abs_set_res(input_dev, ABS_MT_POSITION_Y, wd->resolution);
2226
2227         /* Max pressure is not given by the devices, pick one */
2228         input_set_abs_params(input_dev, ABS_MT_PRESSURE, 0, 50, 0, 0);
2229
2230         input_set_capability(input_dev, EV_KEY, BTN_LEFT);
2231
2232         if (hidpp->quirks & HIDPP_QUIRK_WTP_PHYSICAL_BUTTONS)
2233                 input_set_capability(input_dev, EV_KEY, BTN_RIGHT);
2234         else
2235                 __set_bit(INPUT_PROP_BUTTONPAD, input_dev->propbit);
2236
2237         input_mt_init_slots(input_dev, wd->maxcontacts, INPUT_MT_POINTER |
2238                 INPUT_MT_DROP_UNUSED);
2239 }
2240
2241 static void wtp_touch_event(struct hidpp_device *hidpp,
2242         struct hidpp_touchpad_raw_xy_finger *touch_report)
2243 {
2244         struct wtp_data *wd = hidpp->private_data;
2245         int slot;
2246
2247         if (!touch_report->finger_id || touch_report->contact_type)
2248                 /* no actual data */
2249                 return;
2250
2251         slot = input_mt_get_slot_by_key(hidpp->input, touch_report->finger_id);
2252
2253         input_mt_slot(hidpp->input, slot);
2254         input_mt_report_slot_state(hidpp->input, MT_TOOL_FINGER,
2255                                         touch_report->contact_status);
2256         if (touch_report->contact_status) {
2257                 input_event(hidpp->input, EV_ABS, ABS_MT_POSITION_X,
2258                                 touch_report->x);
2259                 input_event(hidpp->input, EV_ABS, ABS_MT_POSITION_Y,
2260                                 wd->flip_y ? wd->y_size - touch_report->y :
2261                                              touch_report->y);
2262                 input_event(hidpp->input, EV_ABS, ABS_MT_PRESSURE,
2263                                 touch_report->area);
2264         }
2265 }
2266
2267 static void wtp_send_raw_xy_event(struct hidpp_device *hidpp,
2268                 struct hidpp_touchpad_raw_xy *raw)
2269 {
2270         int i;
2271
2272         for (i = 0; i < 2; i++)
2273                 wtp_touch_event(hidpp, &(raw->fingers[i]));
2274
2275         if (raw->end_of_frame &&
2276             !(hidpp->quirks & HIDPP_QUIRK_WTP_PHYSICAL_BUTTONS))
2277                 input_event(hidpp->input, EV_KEY, BTN_LEFT, raw->button);
2278
2279         if (raw->end_of_frame || raw->finger_count <= 2) {
2280                 input_mt_sync_frame(hidpp->input);
2281                 input_sync(hidpp->input);
2282         }
2283 }
2284
2285 static int wtp_mouse_raw_xy_event(struct hidpp_device *hidpp, u8 *data)
2286 {
2287         struct wtp_data *wd = hidpp->private_data;
2288         u8 c1_area = ((data[7] & 0xf) * (data[7] & 0xf) +
2289                       (data[7] >> 4) * (data[7] >> 4)) / 2;
2290         u8 c2_area = ((data[13] & 0xf) * (data[13] & 0xf) +
2291                       (data[13] >> 4) * (data[13] >> 4)) / 2;
2292         struct hidpp_touchpad_raw_xy raw = {
2293                 .timestamp = data[1],
2294                 .fingers = {
2295                         {
2296                                 .contact_type = 0,
2297                                 .contact_status = !!data[7],
2298                                 .x = get_unaligned_le16(&data[3]),
2299                                 .y = get_unaligned_le16(&data[5]),
2300                                 .z = c1_area,
2301                                 .area = c1_area,
2302                                 .finger_id = data[2],
2303                         }, {
2304                                 .contact_type = 0,
2305                                 .contact_status = !!data[13],
2306                                 .x = get_unaligned_le16(&data[9]),
2307                                 .y = get_unaligned_le16(&data[11]),
2308                                 .z = c2_area,
2309                                 .area = c2_area,
2310                                 .finger_id = data[8],
2311                         }
2312                 },
2313                 .finger_count = wd->maxcontacts,
2314                 .spurious_flag = 0,
2315                 .end_of_frame = (data[0] >> 7) == 0,
2316                 .button = data[0] & 0x01,
2317         };
2318
2319         wtp_send_raw_xy_event(hidpp, &raw);
2320
2321         return 1;
2322 }
2323
2324 static int wtp_raw_event(struct hid_device *hdev, u8 *data, int size)
2325 {
2326         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2327         struct wtp_data *wd = hidpp->private_data;
2328         struct hidpp_report *report = (struct hidpp_report *)data;
2329         struct hidpp_touchpad_raw_xy raw;
2330
2331         if (!wd || !hidpp->input)
2332                 return 1;
2333
2334         switch (data[0]) {
2335         case 0x02:
2336                 if (size < 2) {
2337                         hid_err(hdev, "Received HID report of bad size (%d)",
2338                                 size);
2339                         return 1;
2340                 }
2341                 if (hidpp->quirks & HIDPP_QUIRK_WTP_PHYSICAL_BUTTONS) {
2342                         input_event(hidpp->input, EV_KEY, BTN_LEFT,
2343                                         !!(data[1] & 0x01));
2344                         input_event(hidpp->input, EV_KEY, BTN_RIGHT,
2345                                         !!(data[1] & 0x02));
2346                         input_sync(hidpp->input);
2347                         return 0;
2348                 } else {
2349                         if (size < 21)
2350                                 return 1;
2351                         return wtp_mouse_raw_xy_event(hidpp, &data[7]);
2352                 }
2353         case REPORT_ID_HIDPP_LONG:
2354                 /* size is already checked in hidpp_raw_event. */
2355                 if ((report->fap.feature_index != wd->mt_feature_index) ||
2356                     (report->fap.funcindex_clientid != EVENT_TOUCHPAD_RAW_XY))
2357                         return 1;
2358                 hidpp_touchpad_raw_xy_event(hidpp, data + 4, &raw);
2359
2360                 wtp_send_raw_xy_event(hidpp, &raw);
2361                 return 0;
2362         }
2363
2364         return 0;
2365 }
2366
2367 static int wtp_get_config(struct hidpp_device *hidpp)
2368 {
2369         struct wtp_data *wd = hidpp->private_data;
2370         struct hidpp_touchpad_raw_info raw_info = {0};
2371         u8 feature_type;
2372         int ret;
2373
2374         ret = hidpp_root_get_feature(hidpp, HIDPP_PAGE_TOUCHPAD_RAW_XY,
2375                 &wd->mt_feature_index, &feature_type);
2376         if (ret)
2377                 /* means that the device is not powered up */
2378                 return ret;
2379
2380         ret = hidpp_touchpad_get_raw_info(hidpp, wd->mt_feature_index,
2381                 &raw_info);
2382         if (ret)
2383                 return ret;
2384
2385         wd->x_size = raw_info.x_size;
2386         wd->y_size = raw_info.y_size;
2387         wd->maxcontacts = raw_info.maxcontacts;
2388         wd->flip_y = raw_info.origin == TOUCHPAD_RAW_XY_ORIGIN_LOWER_LEFT;
2389         wd->resolution = raw_info.res;
2390         if (!wd->resolution)
2391                 wd->resolution = WTP_MANUAL_RESOLUTION;
2392
2393         return 0;
2394 }
2395
2396 static int wtp_allocate(struct hid_device *hdev, const struct hid_device_id *id)
2397 {
2398         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2399         struct wtp_data *wd;
2400
2401         wd = devm_kzalloc(&hdev->dev, sizeof(struct wtp_data),
2402                         GFP_KERNEL);
2403         if (!wd)
2404                 return -ENOMEM;
2405
2406         hidpp->private_data = wd;
2407
2408         return 0;
2409 };
2410
2411 static int wtp_connect(struct hid_device *hdev, bool connected)
2412 {
2413         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2414         struct wtp_data *wd = hidpp->private_data;
2415         int ret;
2416
2417         if (!wd->x_size) {
2418                 ret = wtp_get_config(hidpp);
2419                 if (ret) {
2420                         hid_err(hdev, "Can not get wtp config: %d\n", ret);
2421                         return ret;
2422                 }
2423         }
2424
2425         return hidpp_touchpad_set_raw_report_state(hidpp, wd->mt_feature_index,
2426                         true, true);
2427 }
2428
2429 /* ------------------------------------------------------------------------- */
2430 /* Logitech M560 devices                                                     */
2431 /* ------------------------------------------------------------------------- */
2432
2433 /*
2434  * Logitech M560 protocol overview
2435  *
2436  * The Logitech M560 mouse, is designed for windows 8. When the middle and/or
2437  * the sides buttons are pressed, it sends some keyboard keys events
2438  * instead of buttons ones.
2439  * To complicate things further, the middle button keys sequence
2440  * is different from the odd press and the even press.
2441  *
2442  * forward button -> Super_R
2443  * backward button -> Super_L+'d' (press only)
2444  * middle button -> 1st time: Alt_L+SuperL+XF86TouchpadOff (press only)
2445  *                  2nd time: left-click (press only)
2446  * NB: press-only means that when the button is pressed, the
2447  * KeyPress/ButtonPress and KeyRelease/ButtonRelease events are generated
2448  * together sequentially; instead when the button is released, no event is
2449  * generated !
2450  *
2451  * With the command
2452  *      10<xx>0a 3500af03 (where <xx> is the mouse id),
2453  * the mouse reacts differently:
2454  * - it never sends a keyboard key event
2455  * - for the three mouse button it sends:
2456  *      middle button               press   11<xx>0a 3500af00...
2457  *      side 1 button (forward)     press   11<xx>0a 3500b000...
2458  *      side 2 button (backward)    press   11<xx>0a 3500ae00...
2459  *      middle/side1/side2 button   release 11<xx>0a 35000000...
2460  */
2461
2462 static const u8 m560_config_parameter[] = {0x00, 0xaf, 0x03};
2463
2464 /* how buttons are mapped in the report */
2465 #define M560_MOUSE_BTN_LEFT             0x01
2466 #define M560_MOUSE_BTN_RIGHT            0x02
2467 #define M560_MOUSE_BTN_WHEEL_LEFT       0x08
2468 #define M560_MOUSE_BTN_WHEEL_RIGHT      0x10
2469
2470 #define M560_SUB_ID                     0x0a
2471 #define M560_BUTTON_MODE_REGISTER       0x35
2472
2473 static int m560_send_config_command(struct hid_device *hdev, bool connected)
2474 {
2475         struct hidpp_report response;
2476         struct hidpp_device *hidpp_dev;
2477
2478         hidpp_dev = hid_get_drvdata(hdev);
2479
2480         return hidpp_send_rap_command_sync(
2481                 hidpp_dev,
2482                 REPORT_ID_HIDPP_SHORT,
2483                 M560_SUB_ID,
2484                 M560_BUTTON_MODE_REGISTER,
2485                 (u8 *)m560_config_parameter,
2486                 sizeof(m560_config_parameter),
2487                 &response
2488         );
2489 }
2490
2491 static int m560_raw_event(struct hid_device *hdev, u8 *data, int size)
2492 {
2493         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2494
2495         /* sanity check */
2496         if (!hidpp->input) {
2497                 hid_err(hdev, "error in parameter\n");
2498                 return -EINVAL;
2499         }
2500
2501         if (size < 7) {
2502                 hid_err(hdev, "error in report\n");
2503                 return 0;
2504         }
2505
2506         if (data[0] == REPORT_ID_HIDPP_LONG &&
2507             data[2] == M560_SUB_ID && data[6] == 0x00) {
2508                 /*
2509                  * m560 mouse report for middle, forward and backward button
2510                  *
2511                  * data[0] = 0x11
2512                  * data[1] = device-id
2513                  * data[2] = 0x0a
2514                  * data[5] = 0xaf -> middle
2515                  *           0xb0 -> forward
2516                  *           0xae -> backward
2517                  *           0x00 -> release all
2518                  * data[6] = 0x00
2519                  */
2520
2521                 switch (data[5]) {
2522                 case 0xaf:
2523                         input_report_key(hidpp->input, BTN_MIDDLE, 1);
2524                         break;
2525                 case 0xb0:
2526                         input_report_key(hidpp->input, BTN_FORWARD, 1);
2527                         break;
2528                 case 0xae:
2529                         input_report_key(hidpp->input, BTN_BACK, 1);
2530                         break;
2531                 case 0x00:
2532                         input_report_key(hidpp->input, BTN_BACK, 0);
2533                         input_report_key(hidpp->input, BTN_FORWARD, 0);
2534                         input_report_key(hidpp->input, BTN_MIDDLE, 0);
2535                         break;
2536                 default:
2537                         hid_err(hdev, "error in report\n");
2538                         return 0;
2539                 }
2540                 input_sync(hidpp->input);
2541
2542         } else if (data[0] == 0x02) {
2543                 /*
2544                  * Logitech M560 mouse report
2545                  *
2546                  * data[0] = type (0x02)
2547                  * data[1..2] = buttons
2548                  * data[3..5] = xy
2549                  * data[6] = wheel
2550                  */
2551
2552                 int v;
2553
2554                 input_report_key(hidpp->input, BTN_LEFT,
2555                         !!(data[1] & M560_MOUSE_BTN_LEFT));
2556                 input_report_key(hidpp->input, BTN_RIGHT,
2557                         !!(data[1] & M560_MOUSE_BTN_RIGHT));
2558
2559                 if (data[1] & M560_MOUSE_BTN_WHEEL_LEFT) {
2560                         input_report_rel(hidpp->input, REL_HWHEEL, -1);
2561                         input_report_rel(hidpp->input, REL_HWHEEL_HI_RES,
2562                                          -120);
2563                 } else if (data[1] & M560_MOUSE_BTN_WHEEL_RIGHT) {
2564                         input_report_rel(hidpp->input, REL_HWHEEL, 1);
2565                         input_report_rel(hidpp->input, REL_HWHEEL_HI_RES,
2566                                          120);
2567                 }
2568
2569                 v = hid_snto32(hid_field_extract(hdev, data+3, 0, 12), 12);
2570                 input_report_rel(hidpp->input, REL_X, v);
2571
2572                 v = hid_snto32(hid_field_extract(hdev, data+3, 12, 12), 12);
2573                 input_report_rel(hidpp->input, REL_Y, v);
2574
2575                 v = hid_snto32(data[6], 8);
2576                 if (v != 0)
2577                         hidpp_scroll_counter_handle_scroll(hidpp->input,
2578                                         &hidpp->vertical_wheel_counter, v);
2579
2580                 input_sync(hidpp->input);
2581         }
2582
2583         return 1;
2584 }
2585
2586 static void m560_populate_input(struct hidpp_device *hidpp,
2587                                 struct input_dev *input_dev)
2588 {
2589         __set_bit(EV_KEY, input_dev->evbit);
2590         __set_bit(BTN_MIDDLE, input_dev->keybit);
2591         __set_bit(BTN_RIGHT, input_dev->keybit);
2592         __set_bit(BTN_LEFT, input_dev->keybit);
2593         __set_bit(BTN_BACK, input_dev->keybit);
2594         __set_bit(BTN_FORWARD, input_dev->keybit);
2595
2596         __set_bit(EV_REL, input_dev->evbit);
2597         __set_bit(REL_X, input_dev->relbit);
2598         __set_bit(REL_Y, input_dev->relbit);
2599         __set_bit(REL_WHEEL, input_dev->relbit);
2600         __set_bit(REL_HWHEEL, input_dev->relbit);
2601         __set_bit(REL_WHEEL_HI_RES, input_dev->relbit);
2602         __set_bit(REL_HWHEEL_HI_RES, input_dev->relbit);
2603 }
2604
2605 static int m560_input_mapping(struct hid_device *hdev, struct hid_input *hi,
2606                 struct hid_field *field, struct hid_usage *usage,
2607                 unsigned long **bit, int *max)
2608 {
2609         return -1;
2610 }
2611
2612 /* ------------------------------------------------------------------------- */
2613 /* Logitech K400 devices                                                     */
2614 /* ------------------------------------------------------------------------- */
2615
2616 /*
2617  * The Logitech K400 keyboard has an embedded touchpad which is seen
2618  * as a mouse from the OS point of view. There is a hardware shortcut to disable
2619  * tap-to-click but the setting is not remembered accross reset, annoying some
2620  * users.
2621  *
2622  * We can toggle this feature from the host by using the feature 0x6010:
2623  * Touchpad FW items
2624  */
2625
2626 struct k400_private_data {
2627         u8 feature_index;
2628 };
2629
2630 static int k400_disable_tap_to_click(struct hidpp_device *hidpp)
2631 {
2632         struct k400_private_data *k400 = hidpp->private_data;
2633         struct hidpp_touchpad_fw_items items = {};
2634         int ret;
2635         u8 feature_type;
2636
2637         if (!k400->feature_index) {
2638                 ret = hidpp_root_get_feature(hidpp,
2639                         HIDPP_PAGE_TOUCHPAD_FW_ITEMS,
2640                         &k400->feature_index, &feature_type);
2641                 if (ret)
2642                         /* means that the device is not powered up */
2643                         return ret;
2644         }
2645
2646         ret = hidpp_touchpad_fw_items_set(hidpp, k400->feature_index, &items);
2647         if (ret)
2648                 return ret;
2649
2650         return 0;
2651 }
2652
2653 static int k400_allocate(struct hid_device *hdev)
2654 {
2655         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2656         struct k400_private_data *k400;
2657
2658         k400 = devm_kzalloc(&hdev->dev, sizeof(struct k400_private_data),
2659                             GFP_KERNEL);
2660         if (!k400)
2661                 return -ENOMEM;
2662
2663         hidpp->private_data = k400;
2664
2665         return 0;
2666 };
2667
2668 static int k400_connect(struct hid_device *hdev, bool connected)
2669 {
2670         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2671
2672         if (!disable_tap_to_click)
2673                 return 0;
2674
2675         return k400_disable_tap_to_click(hidpp);
2676 }
2677
2678 /* ------------------------------------------------------------------------- */
2679 /* Logitech G920 Driving Force Racing Wheel for Xbox One                     */
2680 /* ------------------------------------------------------------------------- */
2681
2682 #define HIDPP_PAGE_G920_FORCE_FEEDBACK                  0x8123
2683
2684 static int g920_ff_set_autocenter(struct hidpp_device *hidpp,
2685                                   struct hidpp_ff_private_data *data)
2686 {
2687         struct hidpp_report response;
2688         u8 params[HIDPP_AUTOCENTER_PARAMS_LENGTH] = {
2689                 [1] = HIDPP_FF_EFFECT_SPRING | HIDPP_FF_EFFECT_AUTOSTART,
2690         };
2691         int ret;
2692
2693         /* initialize with zero autocenter to get wheel in usable state */
2694
2695         dbg_hid("Setting autocenter to 0.\n");
2696         ret = hidpp_send_fap_command_sync(hidpp, data->feature_index,
2697                                           HIDPP_FF_DOWNLOAD_EFFECT,
2698                                           params, ARRAY_SIZE(params),
2699                                           &response);
2700         if (ret)
2701                 hid_warn(hidpp->hid_dev, "Failed to autocenter device!\n");
2702         else
2703                 data->slot_autocenter = response.fap.params[0];
2704
2705         return ret;
2706 }
2707
2708 static int g920_get_config(struct hidpp_device *hidpp,
2709                            struct hidpp_ff_private_data *data)
2710 {
2711         struct hidpp_report response;
2712         u8 feature_type;
2713         int ret;
2714
2715         memset(data, 0, sizeof(*data));
2716
2717         /* Find feature and store for later use */
2718         ret = hidpp_root_get_feature(hidpp, HIDPP_PAGE_G920_FORCE_FEEDBACK,
2719                                      &data->feature_index, &feature_type);
2720         if (ret)
2721                 return ret;
2722
2723         /* Read number of slots available in device */
2724         ret = hidpp_send_fap_command_sync(hidpp, data->feature_index,
2725                                           HIDPP_FF_GET_INFO,
2726                                           NULL, 0,
2727                                           &response);
2728         if (ret) {
2729                 if (ret < 0)
2730                         return ret;
2731                 hid_err(hidpp->hid_dev,
2732                         "%s: received protocol error 0x%02x\n", __func__, ret);
2733                 return -EPROTO;
2734         }
2735
2736         data->num_effects = response.fap.params[0] - HIDPP_FF_RESERVED_SLOTS;
2737
2738         /* reset all forces */
2739         ret = hidpp_send_fap_command_sync(hidpp, data->feature_index,
2740                                           HIDPP_FF_RESET_ALL,
2741                                           NULL, 0,
2742                                           &response);
2743         if (ret)
2744                 hid_warn(hidpp->hid_dev, "Failed to reset all forces!\n");
2745
2746         ret = hidpp_send_fap_command_sync(hidpp, data->feature_index,
2747                                           HIDPP_FF_GET_APERTURE,
2748                                           NULL, 0,
2749                                           &response);
2750         if (ret) {
2751                 hid_warn(hidpp->hid_dev,
2752                          "Failed to read range from device!\n");
2753         }
2754         data->range = ret ?
2755                 900 : get_unaligned_be16(&response.fap.params[0]);
2756
2757         /* Read the current gain values */
2758         ret = hidpp_send_fap_command_sync(hidpp, data->feature_index,
2759                                           HIDPP_FF_GET_GLOBAL_GAINS,
2760                                           NULL, 0,
2761                                           &response);
2762         if (ret)
2763                 hid_warn(hidpp->hid_dev,
2764                          "Failed to read gain values from device!\n");
2765         data->gain = ret ?
2766                 0xffff : get_unaligned_be16(&response.fap.params[0]);
2767
2768         /* ignore boost value at response.fap.params[2] */
2769
2770         return g920_ff_set_autocenter(hidpp, data);
2771 }
2772
2773 /* -------------------------------------------------------------------------- */
2774 /* Logitech Dinovo Mini keyboard with builtin touchpad                        */
2775 /* -------------------------------------------------------------------------- */
2776 #define DINOVO_MINI_PRODUCT_ID          0xb30c
2777
2778 static int lg_dinovo_input_mapping(struct hid_device *hdev, struct hid_input *hi,
2779                 struct hid_field *field, struct hid_usage *usage,
2780                 unsigned long **bit, int *max)
2781 {
2782         if ((usage->hid & HID_USAGE_PAGE) != HID_UP_LOGIVENDOR)
2783                 return 0;
2784
2785         switch (usage->hid & HID_USAGE) {
2786         case 0x00d: lg_map_key_clear(KEY_MEDIA);        break;
2787         default:
2788                 return 0;
2789         }
2790         return 1;
2791 }
2792
2793 /* -------------------------------------------------------------------------- */
2794 /* HID++1.0 devices which use HID++ reports for their wheels                  */
2795 /* -------------------------------------------------------------------------- */
2796 static int hidpp10_wheel_connect(struct hidpp_device *hidpp)
2797 {
2798         return hidpp10_set_register(hidpp, HIDPP_REG_ENABLE_REPORTS, 0,
2799                         HIDPP_ENABLE_WHEEL_REPORT | HIDPP_ENABLE_HWHEEL_REPORT,
2800                         HIDPP_ENABLE_WHEEL_REPORT | HIDPP_ENABLE_HWHEEL_REPORT);
2801 }
2802
2803 static int hidpp10_wheel_raw_event(struct hidpp_device *hidpp,
2804                                    u8 *data, int size)
2805 {
2806         s8 value, hvalue;
2807
2808         if (!hidpp->input)
2809                 return -EINVAL;
2810
2811         if (size < 7)
2812                 return 0;
2813
2814         if (data[0] != REPORT_ID_HIDPP_SHORT || data[2] != HIDPP_SUB_ID_ROLLER)
2815                 return 0;
2816
2817         value = data[3];
2818         hvalue = data[4];
2819
2820         input_report_rel(hidpp->input, REL_WHEEL, value);
2821         input_report_rel(hidpp->input, REL_WHEEL_HI_RES, value * 120);
2822         input_report_rel(hidpp->input, REL_HWHEEL, hvalue);
2823         input_report_rel(hidpp->input, REL_HWHEEL_HI_RES, hvalue * 120);
2824         input_sync(hidpp->input);
2825
2826         return 1;
2827 }
2828
2829 static void hidpp10_wheel_populate_input(struct hidpp_device *hidpp,
2830                                          struct input_dev *input_dev)
2831 {
2832         __set_bit(EV_REL, input_dev->evbit);
2833         __set_bit(REL_WHEEL, input_dev->relbit);
2834         __set_bit(REL_WHEEL_HI_RES, input_dev->relbit);
2835         __set_bit(REL_HWHEEL, input_dev->relbit);
2836         __set_bit(REL_HWHEEL_HI_RES, input_dev->relbit);
2837 }
2838
2839 /* -------------------------------------------------------------------------- */
2840 /* HID++1.0 mice which use HID++ reports for extra mouse buttons              */
2841 /* -------------------------------------------------------------------------- */
2842 static int hidpp10_extra_mouse_buttons_connect(struct hidpp_device *hidpp)
2843 {
2844         return hidpp10_set_register(hidpp, HIDPP_REG_ENABLE_REPORTS, 0,
2845                                     HIDPP_ENABLE_MOUSE_EXTRA_BTN_REPORT,
2846                                     HIDPP_ENABLE_MOUSE_EXTRA_BTN_REPORT);
2847 }
2848
2849 static int hidpp10_extra_mouse_buttons_raw_event(struct hidpp_device *hidpp,
2850                                     u8 *data, int size)
2851 {
2852         int i;
2853
2854         if (!hidpp->input)
2855                 return -EINVAL;
2856
2857         if (size < 7)
2858                 return 0;
2859
2860         if (data[0] != REPORT_ID_HIDPP_SHORT ||
2861             data[2] != HIDPP_SUB_ID_MOUSE_EXTRA_BTNS)
2862                 return 0;
2863
2864         /*
2865          * Buttons are either delivered through the regular mouse report *or*
2866          * through the extra buttons report. At least for button 6 how it is
2867          * delivered differs per receiver firmware version. Even receivers with
2868          * the same usb-id show different behavior, so we handle both cases.
2869          */
2870         for (i = 0; i < 8; i++)
2871                 input_report_key(hidpp->input, BTN_MOUSE + i,
2872                                  (data[3] & (1 << i)));
2873
2874         /* Some mice report events on button 9+, use BTN_MISC */
2875         for (i = 0; i < 8; i++)
2876                 input_report_key(hidpp->input, BTN_MISC + i,
2877                                  (data[4] & (1 << i)));
2878
2879         input_sync(hidpp->input);
2880         return 1;
2881 }
2882
2883 static void hidpp10_extra_mouse_buttons_populate_input(
2884                         struct hidpp_device *hidpp, struct input_dev *input_dev)
2885 {
2886         /* BTN_MOUSE - BTN_MOUSE+7 are set already by the descriptor */
2887         __set_bit(BTN_0, input_dev->keybit);
2888         __set_bit(BTN_1, input_dev->keybit);
2889         __set_bit(BTN_2, input_dev->keybit);
2890         __set_bit(BTN_3, input_dev->keybit);
2891         __set_bit(BTN_4, input_dev->keybit);
2892         __set_bit(BTN_5, input_dev->keybit);
2893         __set_bit(BTN_6, input_dev->keybit);
2894         __set_bit(BTN_7, input_dev->keybit);
2895 }
2896
2897 /* -------------------------------------------------------------------------- */
2898 /* HID++1.0 kbds which only report 0x10xx consumer usages through sub-id 0x03 */
2899 /* -------------------------------------------------------------------------- */
2900
2901 /* Find the consumer-page input report desc and change Maximums to 0x107f */
2902 static u8 *hidpp10_consumer_keys_report_fixup(struct hidpp_device *hidpp,
2903                                               u8 *_rdesc, unsigned int *rsize)
2904 {
2905         /* Note 0 terminated so we can use strnstr to search for this. */
2906         static const char consumer_rdesc_start[] = {
2907                 0x05, 0x0C,     /* USAGE_PAGE (Consumer Devices)       */
2908                 0x09, 0x01,     /* USAGE (Consumer Control)            */
2909                 0xA1, 0x01,     /* COLLECTION (Application)            */
2910                 0x85, 0x03,     /* REPORT_ID = 3                       */
2911                 0x75, 0x10,     /* REPORT_SIZE (16)                    */
2912                 0x95, 0x02,     /* REPORT_COUNT (2)                    */
2913                 0x15, 0x01,     /* LOGICAL_MIN (1)                     */
2914                 0x26, 0x00      /* LOGICAL_MAX (...                    */
2915         };
2916         char *consumer_rdesc, *rdesc = (char *)_rdesc;
2917         unsigned int size;
2918
2919         consumer_rdesc = strnstr(rdesc, consumer_rdesc_start, *rsize);
2920         size = *rsize - (consumer_rdesc - rdesc);
2921         if (consumer_rdesc && size >= 25) {
2922                 consumer_rdesc[15] = 0x7f;
2923                 consumer_rdesc[16] = 0x10;
2924                 consumer_rdesc[20] = 0x7f;
2925                 consumer_rdesc[21] = 0x10;
2926         }
2927         return _rdesc;
2928 }
2929
2930 static int hidpp10_consumer_keys_connect(struct hidpp_device *hidpp)
2931 {
2932         return hidpp10_set_register(hidpp, HIDPP_REG_ENABLE_REPORTS, 0,
2933                                     HIDPP_ENABLE_CONSUMER_REPORT,
2934                                     HIDPP_ENABLE_CONSUMER_REPORT);
2935 }
2936
2937 static int hidpp10_consumer_keys_raw_event(struct hidpp_device *hidpp,
2938                                            u8 *data, int size)
2939 {
2940         u8 consumer_report[5];
2941
2942         if (size < 7)
2943                 return 0;
2944
2945         if (data[0] != REPORT_ID_HIDPP_SHORT ||
2946             data[2] != HIDPP_SUB_ID_CONSUMER_VENDOR_KEYS)
2947                 return 0;
2948
2949         /*
2950          * Build a normal consumer report (3) out of the data, this detour
2951          * is necessary to get some keyboards to report their 0x10xx usages.
2952          */
2953         consumer_report[0] = 0x03;
2954         memcpy(&consumer_report[1], &data[3], 4);
2955         /* We are called from atomic context */
2956         hid_report_raw_event(hidpp->hid_dev, HID_INPUT_REPORT,
2957                              consumer_report, 5, 1);
2958
2959         return 1;
2960 }
2961
2962 /* -------------------------------------------------------------------------- */
2963 /* High-resolution scroll wheels                                              */
2964 /* -------------------------------------------------------------------------- */
2965
2966 static int hi_res_scroll_enable(struct hidpp_device *hidpp)
2967 {
2968         int ret;
2969         u8 multiplier = 1;
2970
2971         if (hidpp->quirks & HIDPP_QUIRK_HI_RES_SCROLL_X2121) {
2972                 ret = hidpp_hrw_set_wheel_mode(hidpp, false, true, false);
2973                 if (ret == 0)
2974                         ret = hidpp_hrw_get_wheel_capability(hidpp, &multiplier);
2975         } else if (hidpp->quirks & HIDPP_QUIRK_HI_RES_SCROLL_X2120) {
2976                 ret = hidpp_hrs_set_highres_scrolling_mode(hidpp, true,
2977                                                            &multiplier);
2978         } else /* if (hidpp->quirks & HIDPP_QUIRK_HI_RES_SCROLL_1P0) */ {
2979                 ret = hidpp10_enable_scrolling_acceleration(hidpp);
2980                 multiplier = 8;
2981         }
2982         if (ret)
2983                 return ret;
2984
2985         if (multiplier == 0)
2986                 multiplier = 1;
2987
2988         hidpp->vertical_wheel_counter.wheel_multiplier = multiplier;
2989         hid_dbg(hidpp->hid_dev, "wheel multiplier = %d\n", multiplier);
2990         return 0;
2991 }
2992
2993 /* -------------------------------------------------------------------------- */
2994 /* Generic HID++ devices                                                      */
2995 /* -------------------------------------------------------------------------- */
2996
2997 static u8 *hidpp_report_fixup(struct hid_device *hdev, u8 *rdesc,
2998                               unsigned int *rsize)
2999 {
3000         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3001
3002         if (!hidpp)
3003                 return rdesc;
3004
3005         /* For 27 MHz keyboards the quirk gets set after hid_parse. */
3006         if (hdev->group == HID_GROUP_LOGITECH_27MHZ_DEVICE ||
3007             (hidpp->quirks & HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS))
3008                 rdesc = hidpp10_consumer_keys_report_fixup(hidpp, rdesc, rsize);
3009
3010         return rdesc;
3011 }
3012
3013 static int hidpp_input_mapping(struct hid_device *hdev, struct hid_input *hi,
3014                 struct hid_field *field, struct hid_usage *usage,
3015                 unsigned long **bit, int *max)
3016 {
3017         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3018
3019         if (!hidpp)
3020                 return 0;
3021
3022         if (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP)
3023                 return wtp_input_mapping(hdev, hi, field, usage, bit, max);
3024         else if (hidpp->quirks & HIDPP_QUIRK_CLASS_M560 &&
3025                         field->application != HID_GD_MOUSE)
3026                 return m560_input_mapping(hdev, hi, field, usage, bit, max);
3027
3028         if (hdev->product == DINOVO_MINI_PRODUCT_ID)
3029                 return lg_dinovo_input_mapping(hdev, hi, field, usage, bit, max);
3030
3031         return 0;
3032 }
3033
3034 static int hidpp_input_mapped(struct hid_device *hdev, struct hid_input *hi,
3035                 struct hid_field *field, struct hid_usage *usage,
3036                 unsigned long **bit, int *max)
3037 {
3038         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3039
3040         if (!hidpp)
3041                 return 0;
3042
3043         /* Ensure that Logitech G920 is not given a default fuzz/flat value */
3044         if (hidpp->quirks & HIDPP_QUIRK_CLASS_G920) {
3045                 if (usage->type == EV_ABS && (usage->code == ABS_X ||
3046                                 usage->code == ABS_Y || usage->code == ABS_Z ||
3047                                 usage->code == ABS_RZ)) {
3048                         field->application = HID_GD_MULTIAXIS;
3049                 }
3050         }
3051
3052         return 0;
3053 }
3054
3055
3056 static void hidpp_populate_input(struct hidpp_device *hidpp,
3057                                  struct input_dev *input)
3058 {
3059         hidpp->input = input;
3060
3061         if (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP)
3062                 wtp_populate_input(hidpp, input);
3063         else if (hidpp->quirks & HIDPP_QUIRK_CLASS_M560)
3064                 m560_populate_input(hidpp, input);
3065
3066         if (hidpp->quirks & HIDPP_QUIRK_HIDPP_WHEELS)
3067                 hidpp10_wheel_populate_input(hidpp, input);
3068
3069         if (hidpp->quirks & HIDPP_QUIRK_HIDPP_EXTRA_MOUSE_BTNS)
3070                 hidpp10_extra_mouse_buttons_populate_input(hidpp, input);
3071 }
3072
3073 static int hidpp_input_configured(struct hid_device *hdev,
3074                                 struct hid_input *hidinput)
3075 {
3076         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3077         struct input_dev *input = hidinput->input;
3078
3079         if (!hidpp)
3080                 return 0;
3081
3082         hidpp_populate_input(hidpp, input);
3083
3084         return 0;
3085 }
3086
3087 static int hidpp_raw_hidpp_event(struct hidpp_device *hidpp, u8 *data,
3088                 int size)
3089 {
3090         struct hidpp_report *question = hidpp->send_receive_buf;
3091         struct hidpp_report *answer = hidpp->send_receive_buf;
3092         struct hidpp_report *report = (struct hidpp_report *)data;
3093         int ret;
3094
3095         /*
3096          * If the mutex is locked then we have a pending answer from a
3097          * previously sent command.
3098          */
3099         if (unlikely(mutex_is_locked(&hidpp->send_mutex))) {
3100                 /*
3101                  * Check for a correct hidpp20 answer or the corresponding
3102                  * error
3103                  */
3104                 if (hidpp_match_answer(question, report) ||
3105                                 hidpp_match_error(question, report)) {
3106                         *answer = *report;
3107                         hidpp->answer_available = true;
3108                         wake_up(&hidpp->wait);
3109                         /*
3110                          * This was an answer to a command that this driver sent
3111                          * We return 1 to hid-core to avoid forwarding the
3112                          * command upstream as it has been treated by the driver
3113                          */
3114
3115                         return 1;
3116                 }
3117         }
3118
3119         if (unlikely(hidpp_report_is_connect_event(report))) {
3120                 atomic_set(&hidpp->connected,
3121                                 !(report->rap.params[0] & (1 << 6)));
3122                 if (schedule_work(&hidpp->work) == 0)
3123                         dbg_hid("%s: connect event already queued\n", __func__);
3124                 return 1;
3125         }
3126
3127         if (hidpp->capabilities & HIDPP_CAPABILITY_HIDPP20_BATTERY) {
3128                 ret = hidpp20_battery_event(hidpp, data, size);
3129                 if (ret != 0)
3130                         return ret;
3131                 ret = hidpp_solar_battery_event(hidpp, data, size);
3132                 if (ret != 0)
3133                         return ret;
3134         }
3135
3136         if (hidpp->capabilities & HIDPP_CAPABILITY_HIDPP10_BATTERY) {
3137                 ret = hidpp10_battery_event(hidpp, data, size);
3138                 if (ret != 0)
3139                         return ret;
3140         }
3141
3142         if (hidpp->quirks & HIDPP_QUIRK_HIDPP_WHEELS) {
3143                 ret = hidpp10_wheel_raw_event(hidpp, data, size);
3144                 if (ret != 0)
3145                         return ret;
3146         }
3147
3148         if (hidpp->quirks & HIDPP_QUIRK_HIDPP_EXTRA_MOUSE_BTNS) {
3149                 ret = hidpp10_extra_mouse_buttons_raw_event(hidpp, data, size);
3150                 if (ret != 0)
3151                         return ret;
3152         }
3153
3154         if (hidpp->quirks & HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS) {
3155                 ret = hidpp10_consumer_keys_raw_event(hidpp, data, size);
3156                 if (ret != 0)
3157                         return ret;
3158         }
3159
3160         return 0;
3161 }
3162
3163 static int hidpp_raw_event(struct hid_device *hdev, struct hid_report *report,
3164                 u8 *data, int size)
3165 {
3166         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3167         int ret = 0;
3168
3169         if (!hidpp)
3170                 return 0;
3171
3172         /* Generic HID++ processing. */
3173         switch (data[0]) {
3174         case REPORT_ID_HIDPP_VERY_LONG:
3175                 if (size != hidpp->very_long_report_length) {
3176                         hid_err(hdev, "received hid++ report of bad size (%d)",
3177                                 size);
3178                         return 1;
3179                 }
3180                 ret = hidpp_raw_hidpp_event(hidpp, data, size);
3181                 break;
3182         case REPORT_ID_HIDPP_LONG:
3183                 if (size != HIDPP_REPORT_LONG_LENGTH) {
3184                         hid_err(hdev, "received hid++ report of bad size (%d)",
3185                                 size);
3186                         return 1;
3187                 }
3188                 ret = hidpp_raw_hidpp_event(hidpp, data, size);
3189                 break;
3190         case REPORT_ID_HIDPP_SHORT:
3191                 if (size != HIDPP_REPORT_SHORT_LENGTH) {
3192                         hid_err(hdev, "received hid++ report of bad size (%d)",
3193                                 size);
3194                         return 1;
3195                 }
3196                 ret = hidpp_raw_hidpp_event(hidpp, data, size);
3197                 break;
3198         }
3199
3200         /* If no report is available for further processing, skip calling
3201          * raw_event of subclasses. */
3202         if (ret != 0)
3203                 return ret;
3204
3205         if (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP)
3206                 return wtp_raw_event(hdev, data, size);
3207         else if (hidpp->quirks & HIDPP_QUIRK_CLASS_M560)
3208                 return m560_raw_event(hdev, data, size);
3209
3210         return 0;
3211 }
3212
3213 static int hidpp_event(struct hid_device *hdev, struct hid_field *field,
3214         struct hid_usage *usage, __s32 value)
3215 {
3216         /* This function will only be called for scroll events, due to the
3217          * restriction imposed in hidpp_usages.
3218          */
3219         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3220         struct hidpp_scroll_counter *counter;
3221
3222         if (!hidpp)
3223                 return 0;
3224
3225         counter = &hidpp->vertical_wheel_counter;
3226         /* A scroll event may occur before the multiplier has been retrieved or
3227          * the input device set, or high-res scroll enabling may fail. In such
3228          * cases we must return early (falling back to default behaviour) to
3229          * avoid a crash in hidpp_scroll_counter_handle_scroll.
3230          */
3231         if (!(hidpp->quirks & HIDPP_QUIRK_HI_RES_SCROLL) || value == 0
3232             || hidpp->input == NULL || counter->wheel_multiplier == 0)
3233                 return 0;
3234
3235         hidpp_scroll_counter_handle_scroll(hidpp->input, counter, value);
3236         return 1;
3237 }
3238
3239 static int hidpp_initialize_battery(struct hidpp_device *hidpp)
3240 {
3241         static atomic_t battery_no = ATOMIC_INIT(0);
3242         struct power_supply_config cfg = { .drv_data = hidpp };
3243         struct power_supply_desc *desc = &hidpp->battery.desc;
3244         enum power_supply_property *battery_props;
3245         struct hidpp_battery *battery;
3246         unsigned int num_battery_props;
3247         unsigned long n;
3248         int ret;
3249
3250         if (hidpp->battery.ps)
3251                 return 0;
3252
3253         hidpp->battery.feature_index = 0xff;
3254         hidpp->battery.solar_feature_index = 0xff;
3255
3256         if (hidpp->protocol_major >= 2) {
3257                 if (hidpp->quirks & HIDPP_QUIRK_CLASS_K750)
3258                         ret = hidpp_solar_request_battery_event(hidpp);
3259                 else
3260                         ret = hidpp20_query_battery_info(hidpp);
3261
3262                 if (ret)
3263                         return ret;
3264                 hidpp->capabilities |= HIDPP_CAPABILITY_HIDPP20_BATTERY;
3265         } else {
3266                 ret = hidpp10_query_battery_status(hidpp);
3267                 if (ret) {
3268                         ret = hidpp10_query_battery_mileage(hidpp);
3269                         if (ret)
3270                                 return -ENOENT;
3271                         hidpp->capabilities |= HIDPP_CAPABILITY_BATTERY_MILEAGE;
3272                 } else {
3273                         hidpp->capabilities |= HIDPP_CAPABILITY_BATTERY_LEVEL_STATUS;
3274                 }
3275                 hidpp->capabilities |= HIDPP_CAPABILITY_HIDPP10_BATTERY;
3276         }
3277
3278         battery_props = devm_kmemdup(&hidpp->hid_dev->dev,
3279                                      hidpp_battery_props,
3280                                      sizeof(hidpp_battery_props),
3281                                      GFP_KERNEL);
3282         if (!battery_props)
3283                 return -ENOMEM;
3284
3285         num_battery_props = ARRAY_SIZE(hidpp_battery_props) - 2;
3286
3287         if (hidpp->capabilities & HIDPP_CAPABILITY_BATTERY_MILEAGE)
3288                 battery_props[num_battery_props++] =
3289                                 POWER_SUPPLY_PROP_CAPACITY;
3290
3291         if (hidpp->capabilities & HIDPP_CAPABILITY_BATTERY_LEVEL_STATUS)
3292                 battery_props[num_battery_props++] =
3293                                 POWER_SUPPLY_PROP_CAPACITY_LEVEL;
3294
3295         battery = &hidpp->battery;
3296
3297         n = atomic_inc_return(&battery_no) - 1;
3298         desc->properties = battery_props;
3299         desc->num_properties = num_battery_props;
3300         desc->get_property = hidpp_battery_get_property;
3301         sprintf(battery->name, "hidpp_battery_%ld", n);
3302         desc->name = battery->name;
3303         desc->type = POWER_SUPPLY_TYPE_BATTERY;
3304         desc->use_for_apm = 0;
3305
3306         battery->ps = devm_power_supply_register(&hidpp->hid_dev->dev,
3307                                                  &battery->desc,
3308                                                  &cfg);
3309         if (IS_ERR(battery->ps))
3310                 return PTR_ERR(battery->ps);
3311
3312         power_supply_powers(battery->ps, &hidpp->hid_dev->dev);
3313
3314         return ret;
3315 }
3316
3317 static void hidpp_overwrite_name(struct hid_device *hdev)
3318 {
3319         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3320         char *name;
3321
3322         if (hidpp->protocol_major < 2)
3323                 return;
3324
3325         name = hidpp_get_device_name(hidpp);
3326
3327         if (!name) {
3328                 hid_err(hdev, "unable to retrieve the name of the device");
3329         } else {
3330                 dbg_hid("HID++: Got name: %s\n", name);
3331                 snprintf(hdev->name, sizeof(hdev->name), "%s", name);
3332         }
3333
3334         kfree(name);
3335 }
3336
3337 static int hidpp_input_open(struct input_dev *dev)
3338 {
3339         struct hid_device *hid = input_get_drvdata(dev);
3340
3341         return hid_hw_open(hid);
3342 }
3343
3344 static void hidpp_input_close(struct input_dev *dev)
3345 {
3346         struct hid_device *hid = input_get_drvdata(dev);
3347
3348         hid_hw_close(hid);
3349 }
3350
3351 static struct input_dev *hidpp_allocate_input(struct hid_device *hdev)
3352 {
3353         struct input_dev *input_dev = devm_input_allocate_device(&hdev->dev);
3354         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3355
3356         if (!input_dev)
3357                 return NULL;
3358
3359         input_set_drvdata(input_dev, hdev);
3360         input_dev->open = hidpp_input_open;
3361         input_dev->close = hidpp_input_close;
3362
3363         input_dev->name = hidpp->name;
3364         input_dev->phys = hdev->phys;
3365         input_dev->uniq = hdev->uniq;
3366         input_dev->id.bustype = hdev->bus;
3367         input_dev->id.vendor  = hdev->vendor;
3368         input_dev->id.product = hdev->product;
3369         input_dev->id.version = hdev->version;
3370         input_dev->dev.parent = &hdev->dev;
3371
3372         return input_dev;
3373 }
3374
3375 static void hidpp_connect_event(struct hidpp_device *hidpp)
3376 {
3377         struct hid_device *hdev = hidpp->hid_dev;
3378         int ret = 0;
3379         bool connected = atomic_read(&hidpp->connected);
3380         struct input_dev *input;
3381         char *name, *devm_name;
3382
3383         if (!connected) {
3384                 if (hidpp->battery.ps) {
3385                         hidpp->battery.online = false;
3386                         hidpp->battery.status = POWER_SUPPLY_STATUS_UNKNOWN;
3387                         hidpp->battery.level = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
3388                         power_supply_changed(hidpp->battery.ps);
3389                 }
3390                 return;
3391         }
3392
3393         if (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP) {
3394                 ret = wtp_connect(hdev, connected);
3395                 if (ret)
3396                         return;
3397         } else if (hidpp->quirks & HIDPP_QUIRK_CLASS_M560) {
3398                 ret = m560_send_config_command(hdev, connected);
3399                 if (ret)
3400                         return;
3401         } else if (hidpp->quirks & HIDPP_QUIRK_CLASS_K400) {
3402                 ret = k400_connect(hdev, connected);
3403                 if (ret)
3404                         return;
3405         }
3406
3407         if (hidpp->quirks & HIDPP_QUIRK_HIDPP_WHEELS) {
3408                 ret = hidpp10_wheel_connect(hidpp);
3409                 if (ret)
3410                         return;
3411         }
3412
3413         if (hidpp->quirks & HIDPP_QUIRK_HIDPP_EXTRA_MOUSE_BTNS) {
3414                 ret = hidpp10_extra_mouse_buttons_connect(hidpp);
3415                 if (ret)
3416                         return;
3417         }
3418
3419         if (hidpp->quirks & HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS) {
3420                 ret = hidpp10_consumer_keys_connect(hidpp);
3421                 if (ret)
3422                         return;
3423         }
3424
3425         /* the device is already connected, we can ask for its name and
3426          * protocol */
3427         if (!hidpp->protocol_major) {
3428                 ret = hidpp_root_get_protocol_version(hidpp);
3429                 if (ret) {
3430                         hid_err(hdev, "Can not get the protocol version.\n");
3431                         return;
3432                 }
3433         }
3434
3435         if (hidpp->name == hdev->name && hidpp->protocol_major >= 2) {
3436                 name = hidpp_get_device_name(hidpp);
3437                 if (name) {
3438                         devm_name = devm_kasprintf(&hdev->dev, GFP_KERNEL,
3439                                                    "%s", name);
3440                         kfree(name);
3441                         if (!devm_name)
3442                                 return;
3443
3444                         hidpp->name = devm_name;
3445                 }
3446         }
3447
3448         hidpp_initialize_battery(hidpp);
3449
3450         /* forward current battery state */
3451         if (hidpp->capabilities & HIDPP_CAPABILITY_HIDPP10_BATTERY) {
3452                 hidpp10_enable_battery_reporting(hidpp);
3453                 if (hidpp->capabilities & HIDPP_CAPABILITY_BATTERY_MILEAGE)
3454                         hidpp10_query_battery_mileage(hidpp);
3455                 else
3456                         hidpp10_query_battery_status(hidpp);
3457         } else if (hidpp->capabilities & HIDPP_CAPABILITY_HIDPP20_BATTERY) {
3458                 hidpp20_query_battery_info(hidpp);
3459         }
3460         if (hidpp->battery.ps)
3461                 power_supply_changed(hidpp->battery.ps);
3462
3463         if (hidpp->quirks & HIDPP_QUIRK_HI_RES_SCROLL)
3464                 hi_res_scroll_enable(hidpp);
3465
3466         if (!(hidpp->quirks & HIDPP_QUIRK_NO_HIDINPUT) || hidpp->delayed_input)
3467                 /* if the input nodes are already created, we can stop now */
3468                 return;
3469
3470         input = hidpp_allocate_input(hdev);
3471         if (!input) {
3472                 hid_err(hdev, "cannot allocate new input device: %d\n", ret);
3473                 return;
3474         }
3475
3476         hidpp_populate_input(hidpp, input);
3477
3478         ret = input_register_device(input);
3479         if (ret)
3480                 input_free_device(input);
3481
3482         hidpp->delayed_input = input;
3483 }
3484
3485 static DEVICE_ATTR(builtin_power_supply, 0000, NULL, NULL);
3486
3487 static struct attribute *sysfs_attrs[] = {
3488         &dev_attr_builtin_power_supply.attr,
3489         NULL
3490 };
3491
3492 static const struct attribute_group ps_attribute_group = {
3493         .attrs = sysfs_attrs
3494 };
3495
3496 static int hidpp_get_report_length(struct hid_device *hdev, int id)
3497 {
3498         struct hid_report_enum *re;
3499         struct hid_report *report;
3500
3501         re = &(hdev->report_enum[HID_OUTPUT_REPORT]);
3502         report = re->report_id_hash[id];
3503         if (!report)
3504                 return 0;
3505
3506         return report->field[0]->report_count + 1;
3507 }
3508
3509 static bool hidpp_validate_device(struct hid_device *hdev)
3510 {
3511         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3512         int id, report_length, supported_reports = 0;
3513
3514         id = REPORT_ID_HIDPP_SHORT;
3515         report_length = hidpp_get_report_length(hdev, id);
3516         if (report_length) {
3517                 if (report_length < HIDPP_REPORT_SHORT_LENGTH)
3518                         goto bad_device;
3519
3520                 supported_reports++;
3521         }
3522
3523         id = REPORT_ID_HIDPP_LONG;
3524         report_length = hidpp_get_report_length(hdev, id);
3525         if (report_length) {
3526                 if (report_length < HIDPP_REPORT_LONG_LENGTH)
3527                         goto bad_device;
3528
3529                 supported_reports++;
3530         }
3531
3532         id = REPORT_ID_HIDPP_VERY_LONG;
3533         report_length = hidpp_get_report_length(hdev, id);
3534         if (report_length) {
3535                 if (report_length < HIDPP_REPORT_LONG_LENGTH ||
3536                     report_length > HIDPP_REPORT_VERY_LONG_MAX_LENGTH)
3537                         goto bad_device;
3538
3539                 supported_reports++;
3540                 hidpp->very_long_report_length = report_length;
3541         }
3542
3543         return supported_reports;
3544
3545 bad_device:
3546         hid_warn(hdev, "not enough values in hidpp report %d\n", id);
3547         return false;
3548 }
3549
3550 static bool hidpp_application_equals(struct hid_device *hdev,
3551                                      unsigned int application)
3552 {
3553         struct list_head *report_list;
3554         struct hid_report *report;
3555
3556         report_list = &hdev->report_enum[HID_INPUT_REPORT].report_list;
3557         report = list_first_entry_or_null(report_list, struct hid_report, list);
3558         return report && report->application == application;
3559 }
3560
3561 static int hidpp_probe(struct hid_device *hdev, const struct hid_device_id *id)
3562 {
3563         struct hidpp_device *hidpp;
3564         int ret;
3565         bool connected;
3566         unsigned int connect_mask = HID_CONNECT_DEFAULT;
3567         struct hidpp_ff_private_data data;
3568
3569         /* report_fixup needs drvdata to be set before we call hid_parse */
3570         hidpp = devm_kzalloc(&hdev->dev, sizeof(*hidpp), GFP_KERNEL);
3571         if (!hidpp)
3572                 return -ENOMEM;
3573
3574         hidpp->hid_dev = hdev;
3575         hidpp->name = hdev->name;
3576         hidpp->quirks = id->driver_data;
3577         hid_set_drvdata(hdev, hidpp);
3578
3579         ret = hid_parse(hdev);
3580         if (ret) {
3581                 hid_err(hdev, "%s:parse failed\n", __func__);
3582                 return ret;
3583         }
3584
3585         /*
3586          * Make sure the device is HID++ capable, otherwise treat as generic HID
3587          */
3588         if (!hidpp_validate_device(hdev)) {
3589                 hid_set_drvdata(hdev, NULL);
3590                 devm_kfree(&hdev->dev, hidpp);
3591                 return hid_hw_start(hdev, HID_CONNECT_DEFAULT);
3592         }
3593
3594         if (id->group == HID_GROUP_LOGITECH_DJ_DEVICE)
3595                 hidpp->quirks |= HIDPP_QUIRK_UNIFYING;
3596
3597         if (id->group == HID_GROUP_LOGITECH_27MHZ_DEVICE &&
3598             hidpp_application_equals(hdev, HID_GD_MOUSE))
3599                 hidpp->quirks |= HIDPP_QUIRK_HIDPP_WHEELS |
3600                                  HIDPP_QUIRK_HIDPP_EXTRA_MOUSE_BTNS;
3601
3602         if (id->group == HID_GROUP_LOGITECH_27MHZ_DEVICE &&
3603             hidpp_application_equals(hdev, HID_GD_KEYBOARD))
3604                 hidpp->quirks |= HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS;
3605
3606         if (disable_raw_mode) {
3607                 hidpp->quirks &= ~HIDPP_QUIRK_CLASS_WTP;
3608                 hidpp->quirks &= ~HIDPP_QUIRK_NO_HIDINPUT;
3609         }
3610
3611         if (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP) {
3612                 ret = wtp_allocate(hdev, id);
3613                 if (ret)
3614                         return ret;
3615         } else if (hidpp->quirks & HIDPP_QUIRK_CLASS_K400) {
3616                 ret = k400_allocate(hdev);
3617                 if (ret)
3618                         return ret;
3619         }
3620
3621         INIT_WORK(&hidpp->work, delayed_work_cb);
3622         mutex_init(&hidpp->send_mutex);
3623         init_waitqueue_head(&hidpp->wait);
3624
3625         /* indicates we are handling the battery properties in the kernel */
3626         ret = sysfs_create_group(&hdev->dev.kobj, &ps_attribute_group);
3627         if (ret)
3628                 hid_warn(hdev, "Cannot allocate sysfs group for %s\n",
3629                          hdev->name);
3630
3631         /*
3632          * Plain USB connections need to actually call start and open
3633          * on the transport driver to allow incoming data.
3634          */
3635         ret = hid_hw_start(hdev, 0);
3636         if (ret) {
3637                 hid_err(hdev, "hw start failed\n");
3638                 goto hid_hw_start_fail;
3639         }
3640
3641         ret = hid_hw_open(hdev);
3642         if (ret < 0) {
3643                 dev_err(&hdev->dev, "%s:hid_hw_open returned error:%d\n",
3644                         __func__, ret);
3645                 hid_hw_stop(hdev);
3646                 goto hid_hw_open_fail;
3647         }
3648
3649         /* Allow incoming packets */
3650         hid_device_io_start(hdev);
3651
3652         if (hidpp->quirks & HIDPP_QUIRK_UNIFYING)
3653                 hidpp_unifying_init(hidpp);
3654
3655         connected = hidpp_root_get_protocol_version(hidpp) == 0;
3656         atomic_set(&hidpp->connected, connected);
3657         if (!(hidpp->quirks & HIDPP_QUIRK_UNIFYING)) {
3658                 if (!connected) {
3659                         ret = -ENODEV;
3660                         hid_err(hdev, "Device not connected");
3661                         goto hid_hw_init_fail;
3662                 }
3663
3664                 hidpp_overwrite_name(hdev);
3665         }
3666
3667         if (connected && (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP)) {
3668                 ret = wtp_get_config(hidpp);
3669                 if (ret)
3670                         goto hid_hw_init_fail;
3671         } else if (connected && (hidpp->quirks & HIDPP_QUIRK_CLASS_G920)) {
3672                 ret = g920_get_config(hidpp, &data);
3673                 if (ret)
3674                         goto hid_hw_init_fail;
3675         }
3676
3677         hidpp_connect_event(hidpp);
3678
3679         /* Reset the HID node state */
3680         hid_device_io_stop(hdev);
3681         hid_hw_close(hdev);
3682         hid_hw_stop(hdev);
3683
3684         if (hidpp->quirks & HIDPP_QUIRK_NO_HIDINPUT)
3685                 connect_mask &= ~HID_CONNECT_HIDINPUT;
3686
3687         /* Now export the actual inputs and hidraw nodes to the world */
3688         ret = hid_hw_start(hdev, connect_mask);
3689         if (ret) {
3690                 hid_err(hdev, "%s:hid_hw_start returned error\n", __func__);
3691                 goto hid_hw_start_fail;
3692         }
3693
3694         if (hidpp->quirks & HIDPP_QUIRK_CLASS_G920) {
3695                 ret = hidpp_ff_init(hidpp, &data);
3696                 if (ret)
3697                         hid_warn(hidpp->hid_dev,
3698                      "Unable to initialize force feedback support, errno %d\n",
3699                                  ret);
3700         }
3701
3702         return ret;
3703
3704 hid_hw_init_fail:
3705         hid_hw_close(hdev);
3706 hid_hw_open_fail:
3707         hid_hw_stop(hdev);
3708 hid_hw_start_fail:
3709         sysfs_remove_group(&hdev->dev.kobj, &ps_attribute_group);
3710         cancel_work_sync(&hidpp->work);
3711         mutex_destroy(&hidpp->send_mutex);
3712         return ret;
3713 }
3714
3715 static void hidpp_remove(struct hid_device *hdev)
3716 {
3717         struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3718
3719         if (!hidpp)
3720                 return hid_hw_stop(hdev);
3721
3722         sysfs_remove_group(&hdev->dev.kobj, &ps_attribute_group);
3723
3724         hid_hw_stop(hdev);
3725         cancel_work_sync(&hidpp->work);
3726         mutex_destroy(&hidpp->send_mutex);
3727 }
3728
3729 #define LDJ_DEVICE(product) \
3730         HID_DEVICE(BUS_USB, HID_GROUP_LOGITECH_DJ_DEVICE, \
3731                    USB_VENDOR_ID_LOGITECH, (product))
3732
3733 #define L27MHZ_DEVICE(product) \
3734         HID_DEVICE(BUS_USB, HID_GROUP_LOGITECH_27MHZ_DEVICE, \
3735                    USB_VENDOR_ID_LOGITECH, (product))
3736
3737 static const struct hid_device_id hidpp_devices[] = {
3738         { /* wireless touchpad */
3739           LDJ_DEVICE(0x4011),
3740           .driver_data = HIDPP_QUIRK_CLASS_WTP | HIDPP_QUIRK_DELAYED_INIT |
3741                          HIDPP_QUIRK_WTP_PHYSICAL_BUTTONS },
3742         { /* wireless touchpad T650 */
3743           LDJ_DEVICE(0x4101),
3744           .driver_data = HIDPP_QUIRK_CLASS_WTP | HIDPP_QUIRK_DELAYED_INIT },
3745         { /* wireless touchpad T651 */
3746           HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH,
3747                 USB_DEVICE_ID_LOGITECH_T651),
3748           .driver_data = HIDPP_QUIRK_CLASS_WTP },
3749         { /* Mouse Logitech Anywhere MX */
3750           LDJ_DEVICE(0x1017), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_1P0 },
3751         { /* Mouse Logitech Cube */
3752           LDJ_DEVICE(0x4010), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2120 },
3753         { /* Mouse Logitech M335 */
3754           LDJ_DEVICE(0x4050), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3755         { /* Mouse Logitech M515 */
3756           LDJ_DEVICE(0x4007), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2120 },
3757         { /* Mouse logitech M560 */
3758           LDJ_DEVICE(0x402d),
3759           .driver_data = HIDPP_QUIRK_DELAYED_INIT | HIDPP_QUIRK_CLASS_M560
3760                 | HIDPP_QUIRK_HI_RES_SCROLL_X2120 },
3761         { /* Mouse Logitech M705 (firmware RQM17) */
3762           LDJ_DEVICE(0x101b), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_1P0 },
3763         { /* Mouse Logitech M705 (firmware RQM67) */
3764           LDJ_DEVICE(0x406d), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3765         { /* Mouse Logitech M720 */
3766           LDJ_DEVICE(0x405e), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3767         { /* Mouse Logitech MX Anywhere 2 */
3768           LDJ_DEVICE(0x404a), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3769         { LDJ_DEVICE(0x4072), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3770         { LDJ_DEVICE(0xb013), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3771         { LDJ_DEVICE(0xb018), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3772         { LDJ_DEVICE(0xb01f), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3773         { /* Mouse Logitech MX Anywhere 2S */
3774           LDJ_DEVICE(0x406a), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3775         { /* Mouse Logitech MX Master */
3776           LDJ_DEVICE(0x4041), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3777         { LDJ_DEVICE(0x4060), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3778         { LDJ_DEVICE(0x4071), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3779         { /* Mouse Logitech MX Master 2S */
3780           LDJ_DEVICE(0x4069), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3781         { /* Mouse Logitech Performance MX */
3782           LDJ_DEVICE(0x101a), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_1P0 },
3783         { /* Keyboard logitech K400 */
3784           LDJ_DEVICE(0x4024),
3785           .driver_data = HIDPP_QUIRK_CLASS_K400 },
3786         { /* Solar Keyboard Logitech K750 */
3787           LDJ_DEVICE(0x4002),
3788           .driver_data = HIDPP_QUIRK_CLASS_K750 },
3789         { /* Keyboard MX5000 (Bluetooth-receiver in HID proxy mode) */
3790           LDJ_DEVICE(0xb305),
3791           .driver_data = HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS },
3792         { /* Dinovo Edge (Bluetooth-receiver in HID proxy mode) */
3793           LDJ_DEVICE(0xb309),
3794           .driver_data = HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS },
3795         { /* Keyboard MX5500 (Bluetooth-receiver in HID proxy mode) */
3796           LDJ_DEVICE(0xb30b),
3797           .driver_data = HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS },
3798
3799         { LDJ_DEVICE(HID_ANY_ID) },
3800
3801         { /* Keyboard LX501 (Y-RR53) */
3802           L27MHZ_DEVICE(0x0049),
3803           .driver_data = HIDPP_QUIRK_KBD_ZOOM_WHEEL },
3804         { /* Keyboard MX3000 (Y-RAM74) */
3805           L27MHZ_DEVICE(0x0057),
3806           .driver_data = HIDPP_QUIRK_KBD_SCROLL_WHEEL },
3807         { /* Keyboard MX3200 (Y-RAV80) */
3808           L27MHZ_DEVICE(0x005c),
3809           .driver_data = HIDPP_QUIRK_KBD_ZOOM_WHEEL },
3810         { /* S510 Media Remote */
3811           L27MHZ_DEVICE(0x00fe),
3812           .driver_data = HIDPP_QUIRK_KBD_SCROLL_WHEEL },
3813
3814         { L27MHZ_DEVICE(HID_ANY_ID) },
3815
3816         { /* Logitech G403 Wireless Gaming Mouse over USB */
3817           HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, 0xC082) },
3818         { /* Logitech G703 Gaming Mouse over USB */
3819           HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, 0xC087) },
3820         { /* Logitech G703 Hero Gaming Mouse over USB */
3821           HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, 0xC090) },
3822         { /* Logitech G900 Gaming Mouse over USB */
3823           HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, 0xC081) },
3824         { /* Logitech G903 Gaming Mouse over USB */
3825           HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, 0xC086) },
3826         { /* Logitech G903 Hero Gaming Mouse over USB */
3827           HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, 0xC091) },
3828         { /* Logitech G920 Wheel over USB */
3829           HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_G920_WHEEL),
3830                 .driver_data = HIDPP_QUIRK_CLASS_G920 | HIDPP_QUIRK_FORCE_OUTPUT_REPORTS},
3831         { /* Logitech G Pro Gaming Mouse over USB */
3832           HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, 0xC088) },
3833
3834         { /* MX5000 keyboard over Bluetooth */
3835           HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH, 0xb305),
3836           .driver_data = HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS },
3837         { /* Dinovo Edge keyboard over Bluetooth */
3838           HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH, 0xb309),
3839           .driver_data = HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS },
3840         { /* MX5500 keyboard over Bluetooth */
3841           HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH, 0xb30b),
3842           .driver_data = HIDPP_QUIRK_HIDPP_CONSUMER_VENDOR_KEYS },
3843         {}
3844 };
3845
3846 MODULE_DEVICE_TABLE(hid, hidpp_devices);
3847
3848 static const struct hid_usage_id hidpp_usages[] = {
3849         { HID_GD_WHEEL, EV_REL, REL_WHEEL_HI_RES },
3850         { HID_ANY_ID - 1, HID_ANY_ID - 1, HID_ANY_ID - 1}
3851 };
3852
3853 static struct hid_driver hidpp_driver = {
3854         .name = "logitech-hidpp-device",
3855         .id_table = hidpp_devices,
3856         .report_fixup = hidpp_report_fixup,
3857         .probe = hidpp_probe,
3858         .remove = hidpp_remove,
3859         .raw_event = hidpp_raw_event,
3860         .usage_table = hidpp_usages,
3861         .event = hidpp_event,
3862         .input_configured = hidpp_input_configured,
3863         .input_mapping = hidpp_input_mapping,
3864         .input_mapped = hidpp_input_mapped,
3865 };
3866
3867 module_hid_driver(hidpp_driver);