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