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