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