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