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