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