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