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