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