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