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