1 /*
2  *  HIDPP protocol for Logitech Unifying receivers
3  *
4  *  Copyright (c) 2011 Logitech (c)
5  *  Copyright (c) 2012-2013 Google (c)
6  *  Copyright (c) 2013-2014 Red Hat Inc.
7  */
8 
9 /*
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU General Public License as published by the Free
12  * Software Foundation; version 2 of the License.
13  */
14 
15 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16 
17 #include <linux/device.h>
18 #include <linux/input.h>
19 #include <linux/usb.h>
20 #include <linux/hid.h>
21 #include <linux/module.h>
22 #include <linux/slab.h>
23 #include <linux/sched.h>
24 #include <linux/kfifo.h>
25 #include <linux/input/mt.h>
26 #include <linux/workqueue.h>
27 #include <linux/atomic.h>
28 #include <linux/fixp-arith.h>
29 #include <asm/unaligned.h>
30 #include "usbhid/usbhid.h"
31 #include "hid-ids.h"
32 
33 MODULE_LICENSE("GPL");
34 MODULE_AUTHOR("Benjamin Tissoires <benjamin.tissoires@gmail.com>");
35 MODULE_AUTHOR("Nestor Lopez Casado <nlopezcasad@logitech.com>");
36 
37 static bool disable_raw_mode;
38 module_param(disable_raw_mode, bool, 0644);
39 MODULE_PARM_DESC(disable_raw_mode,
40 	"Disable Raw mode reporting for touchpads and keep firmware gestures.");
41 
42 static bool disable_tap_to_click;
43 module_param(disable_tap_to_click, bool, 0644);
44 MODULE_PARM_DESC(disable_tap_to_click,
45 	"Disable Tap-To-Click mode reporting for touchpads (only on the K400 currently).");
46 
47 #define REPORT_ID_HIDPP_SHORT			0x10
48 #define REPORT_ID_HIDPP_LONG			0x11
49 #define REPORT_ID_HIDPP_VERY_LONG		0x12
50 
51 #define HIDPP_REPORT_SHORT_LENGTH		7
52 #define HIDPP_REPORT_LONG_LENGTH		20
53 #define HIDPP_REPORT_VERY_LONG_LENGTH		64
54 
55 #define HIDPP_QUIRK_CLASS_WTP			BIT(0)
56 #define HIDPP_QUIRK_CLASS_M560			BIT(1)
57 #define HIDPP_QUIRK_CLASS_K400			BIT(2)
58 #define HIDPP_QUIRK_CLASS_G920			BIT(3)
59 #define HIDPP_QUIRK_CLASS_K750			BIT(4)
60 
61 /* bits 2..20 are reserved for classes */
62 /* #define HIDPP_QUIRK_CONNECT_EVENTS		BIT(21) disabled */
63 #define HIDPP_QUIRK_WTP_PHYSICAL_BUTTONS	BIT(22)
64 #define HIDPP_QUIRK_NO_HIDINPUT			BIT(23)
65 #define HIDPP_QUIRK_FORCE_OUTPUT_REPORTS	BIT(24)
66 #define HIDPP_QUIRK_UNIFYING			BIT(25)
67 #define HIDPP_QUIRK_HI_RES_SCROLL_1P0		BIT(26)
68 #define HIDPP_QUIRK_HI_RES_SCROLL_X2120		BIT(27)
69 #define HIDPP_QUIRK_HI_RES_SCROLL_X2121		BIT(28)
70 
71 /* Convenience constant to check for any high-res support. */
72 #define HIDPP_QUIRK_HI_RES_SCROLL	(HIDPP_QUIRK_HI_RES_SCROLL_1P0 | \
73 					 HIDPP_QUIRK_HI_RES_SCROLL_X2120 | \
74 					 HIDPP_QUIRK_HI_RES_SCROLL_X2121)
75 
76 #define HIDPP_QUIRK_DELAYED_INIT		HIDPP_QUIRK_NO_HIDINPUT
77 
78 #define HIDPP_CAPABILITY_HIDPP10_BATTERY	BIT(0)
79 #define HIDPP_CAPABILITY_HIDPP20_BATTERY	BIT(1)
80 #define HIDPP_CAPABILITY_BATTERY_MILEAGE	BIT(2)
81 #define HIDPP_CAPABILITY_BATTERY_LEVEL_STATUS	BIT(3)
82 
83 /*
84  * There are two hidpp protocols in use, the first version hidpp10 is known
85  * as register access protocol or RAP, the second version hidpp20 is known as
86  * feature access protocol or FAP
87  *
88  * Most older devices (including the Unifying usb receiver) use the RAP protocol
89  * where as most newer devices use the FAP protocol. Both protocols are
90  * compatible with the underlying transport, which could be usb, Unifiying, or
91  * bluetooth. The message lengths are defined by the hid vendor specific report
92  * descriptor for the HIDPP_SHORT report type (total message lenth 7 bytes) and
93  * the HIDPP_LONG report type (total message length 20 bytes)
94  *
95  * The RAP protocol uses both report types, whereas the FAP only uses HIDPP_LONG
96  * messages. The Unifying receiver itself responds to RAP messages (device index
97  * is 0xFF for the receiver), and all messages (short or long) with a device
98  * index between 1 and 6 are passed untouched to the corresponding paired
99  * Unifying device.
100  *
101  * The paired device can be RAP or FAP, it will receive the message untouched
102  * from the Unifiying receiver.
103  */
104 
105 struct fap {
106 	u8 feature_index;
107 	u8 funcindex_clientid;
108 	u8 params[HIDPP_REPORT_VERY_LONG_LENGTH - 4U];
109 };
110 
111 struct rap {
112 	u8 sub_id;
113 	u8 reg_address;
114 	u8 params[HIDPP_REPORT_VERY_LONG_LENGTH - 4U];
115 };
116 
117 struct hidpp_report {
118 	u8 report_id;
119 	u8 device_index;
120 	union {
121 		struct fap fap;
122 		struct rap rap;
123 		u8 rawbytes[sizeof(struct fap)];
124 	};
125 } __packed;
126 
127 struct hidpp_battery {
128 	u8 feature_index;
129 	u8 solar_feature_index;
130 	struct power_supply_desc desc;
131 	struct power_supply *ps;
132 	char name[64];
133 	int status;
134 	int capacity;
135 	int level;
136 	bool online;
137 };
138 
139 struct hidpp_device {
140 	struct hid_device *hid_dev;
141 	struct mutex send_mutex;
142 	void *send_receive_buf;
143 	char *name;		/* will never be NULL and should not be freed */
144 	wait_queue_head_t wait;
145 	bool answer_available;
146 	u8 protocol_major;
147 	u8 protocol_minor;
148 
149 	void *private_data;
150 
151 	struct work_struct work;
152 	struct kfifo delayed_work_fifo;
153 	atomic_t connected;
154 	struct input_dev *delayed_input;
155 
156 	unsigned long quirks;
157 	unsigned long capabilities;
158 
159 	struct hidpp_battery battery;
160 	struct hid_scroll_counter vertical_wheel_counter;
161 };
162 
163 /* HID++ 1.0 error codes */
164 #define HIDPP_ERROR				0x8f
165 #define HIDPP_ERROR_SUCCESS			0x00
166 #define HIDPP_ERROR_INVALID_SUBID		0x01
167 #define HIDPP_ERROR_INVALID_ADRESS		0x02
168 #define HIDPP_ERROR_INVALID_VALUE		0x03
169 #define HIDPP_ERROR_CONNECT_FAIL		0x04
170 #define HIDPP_ERROR_TOO_MANY_DEVICES		0x05
171 #define HIDPP_ERROR_ALREADY_EXISTS		0x06
172 #define HIDPP_ERROR_BUSY			0x07
173 #define HIDPP_ERROR_UNKNOWN_DEVICE		0x08
174 #define HIDPP_ERROR_RESOURCE_ERROR		0x09
175 #define HIDPP_ERROR_REQUEST_UNAVAILABLE		0x0a
176 #define HIDPP_ERROR_INVALID_PARAM_VALUE		0x0b
177 #define HIDPP_ERROR_WRONG_PIN_CODE		0x0c
178 /* HID++ 2.0 error codes */
179 #define HIDPP20_ERROR				0xff
180 
181 static void hidpp_connect_event(struct hidpp_device *hidpp_dev);
182 
183 static int __hidpp_send_report(struct hid_device *hdev,
184 				struct hidpp_report *hidpp_report)
185 {
186 	struct hidpp_device *hidpp = hid_get_drvdata(hdev);
187 	int fields_count, ret;
188 
189 	hidpp = hid_get_drvdata(hdev);
190 
191 	switch (hidpp_report->report_id) {
192 	case REPORT_ID_HIDPP_SHORT:
193 		fields_count = HIDPP_REPORT_SHORT_LENGTH;
194 		break;
195 	case REPORT_ID_HIDPP_LONG:
196 		fields_count = HIDPP_REPORT_LONG_LENGTH;
197 		break;
198 	case REPORT_ID_HIDPP_VERY_LONG:
199 		fields_count = HIDPP_REPORT_VERY_LONG_LENGTH;
200 		break;
201 	default:
202 		return -ENODEV;
203 	}
204 
205 	/*
206 	 * set the device_index as the receiver, it will be overwritten by
207 	 * hid_hw_request if needed
208 	 */
209 	hidpp_report->device_index = 0xff;
210 
211 	if (hidpp->quirks & HIDPP_QUIRK_FORCE_OUTPUT_REPORTS) {
212 		ret = hid_hw_output_report(hdev, (u8 *)hidpp_report, fields_count);
213 	} else {
214 		ret = hid_hw_raw_request(hdev, hidpp_report->report_id,
215 			(u8 *)hidpp_report, fields_count, HID_OUTPUT_REPORT,
216 			HID_REQ_SET_REPORT);
217 	}
218 
219 	return ret == fields_count ? 0 : -1;
220 }
221 
222 /**
223  * hidpp_send_message_sync() returns 0 in case of success, and something else
224  * in case of a failure.
225  * - If ' something else' is positive, that means that an error has been raised
226  *   by the protocol itself.
227  * - If ' something else' is negative, that means that we had a classic error
228  *   (-ENOMEM, -EPIPE, etc...)
229  */
230 static int hidpp_send_message_sync(struct hidpp_device *hidpp,
231 	struct hidpp_report *message,
232 	struct hidpp_report *response)
233 {
234 	int ret;
235 
236 	mutex_lock(&hidpp->send_mutex);
237 
238 	hidpp->send_receive_buf = response;
239 	hidpp->answer_available = false;
240 
241 	/*
242 	 * So that we can later validate the answer when it arrives
243 	 * in hidpp_raw_event
244 	 */
245 	*response = *message;
246 
247 	ret = __hidpp_send_report(hidpp->hid_dev, message);
248 
249 	if (ret) {
250 		dbg_hid("__hidpp_send_report returned err: %d\n", ret);
251 		memset(response, 0, sizeof(struct hidpp_report));
252 		goto exit;
253 	}
254 
255 	if (!wait_event_timeout(hidpp->wait, hidpp->answer_available,
256 				5*HZ)) {
257 		dbg_hid("%s:timeout waiting for response\n", __func__);
258 		memset(response, 0, sizeof(struct hidpp_report));
259 		ret = -ETIMEDOUT;
260 	}
261 
262 	if (response->report_id == REPORT_ID_HIDPP_SHORT &&
263 	    response->rap.sub_id == HIDPP_ERROR) {
264 		ret = response->rap.params[1];
265 		dbg_hid("%s:got hidpp error %02X\n", __func__, ret);
266 		goto exit;
267 	}
268 
269 	if ((response->report_id == REPORT_ID_HIDPP_LONG ||
270 			response->report_id == REPORT_ID_HIDPP_VERY_LONG) &&
271 			response->fap.feature_index == HIDPP20_ERROR) {
272 		ret = response->fap.params[1];
273 		dbg_hid("%s:got hidpp 2.0 error %02X\n", __func__, ret);
274 		goto exit;
275 	}
276 
277 exit:
278 	mutex_unlock(&hidpp->send_mutex);
279 	return ret;
280 
281 }
282 
283 static int hidpp_send_fap_command_sync(struct hidpp_device *hidpp,
284 	u8 feat_index, u8 funcindex_clientid, u8 *params, int param_count,
285 	struct hidpp_report *response)
286 {
287 	struct hidpp_report *message;
288 	int ret;
289 
290 	if (param_count > sizeof(message->fap.params))
291 		return -EINVAL;
292 
293 	message = kzalloc(sizeof(struct hidpp_report), GFP_KERNEL);
294 	if (!message)
295 		return -ENOMEM;
296 
297 	if (param_count > (HIDPP_REPORT_LONG_LENGTH - 4))
298 		message->report_id = REPORT_ID_HIDPP_VERY_LONG;
299 	else
300 		message->report_id = REPORT_ID_HIDPP_LONG;
301 	message->fap.feature_index = feat_index;
302 	message->fap.funcindex_clientid = funcindex_clientid;
303 	memcpy(&message->fap.params, params, param_count);
304 
305 	ret = hidpp_send_message_sync(hidpp, message, response);
306 	kfree(message);
307 	return ret;
308 }
309 
310 static int hidpp_send_rap_command_sync(struct hidpp_device *hidpp_dev,
311 	u8 report_id, u8 sub_id, u8 reg_address, u8 *params, int param_count,
312 	struct hidpp_report *response)
313 {
314 	struct hidpp_report *message;
315 	int ret, max_count;
316 
317 	switch (report_id) {
318 	case REPORT_ID_HIDPP_SHORT:
319 		max_count = HIDPP_REPORT_SHORT_LENGTH - 4;
320 		break;
321 	case REPORT_ID_HIDPP_LONG:
322 		max_count = HIDPP_REPORT_LONG_LENGTH - 4;
323 		break;
324 	case REPORT_ID_HIDPP_VERY_LONG:
325 		max_count = HIDPP_REPORT_VERY_LONG_LENGTH - 4;
326 		break;
327 	default:
328 		return -EINVAL;
329 	}
330 
331 	if (param_count > max_count)
332 		return -EINVAL;
333 
334 	message = kzalloc(sizeof(struct hidpp_report), GFP_KERNEL);
335 	if (!message)
336 		return -ENOMEM;
337 	message->report_id = report_id;
338 	message->rap.sub_id = sub_id;
339 	message->rap.reg_address = reg_address;
340 	memcpy(&message->rap.params, params, param_count);
341 
342 	ret = hidpp_send_message_sync(hidpp_dev, message, response);
343 	kfree(message);
344 	return ret;
345 }
346 
347 static void delayed_work_cb(struct work_struct *work)
348 {
349 	struct hidpp_device *hidpp = container_of(work, struct hidpp_device,
350 							work);
351 	hidpp_connect_event(hidpp);
352 }
353 
354 static inline bool hidpp_match_answer(struct hidpp_report *question,
355 		struct hidpp_report *answer)
356 {
357 	return (answer->fap.feature_index == question->fap.feature_index) &&
358 	   (answer->fap.funcindex_clientid == question->fap.funcindex_clientid);
359 }
360 
361 static inline bool hidpp_match_error(struct hidpp_report *question,
362 		struct hidpp_report *answer)
363 {
364 	return ((answer->rap.sub_id == HIDPP_ERROR) ||
365 	    (answer->fap.feature_index == HIDPP20_ERROR)) &&
366 	    (answer->fap.funcindex_clientid == question->fap.feature_index) &&
367 	    (answer->fap.params[0] == question->fap.funcindex_clientid);
368 }
369 
370 static inline bool hidpp_report_is_connect_event(struct hidpp_report *report)
371 {
372 	return (report->report_id == REPORT_ID_HIDPP_SHORT) &&
373 		(report->rap.sub_id == 0x41);
374 }
375 
376 /**
377  * hidpp_prefix_name() prefixes the current given name with "Logitech ".
378  */
379 static void hidpp_prefix_name(char **name, int name_length)
380 {
381 #define PREFIX_LENGTH 9 /* "Logitech " */
382 
383 	int new_length;
384 	char *new_name;
385 
386 	if (name_length > PREFIX_LENGTH &&
387 	    strncmp(*name, "Logitech ", PREFIX_LENGTH) == 0)
388 		/* The prefix has is already in the name */
389 		return;
390 
391 	new_length = PREFIX_LENGTH + name_length;
392 	new_name = kzalloc(new_length, GFP_KERNEL);
393 	if (!new_name)
394 		return;
395 
396 	snprintf(new_name, new_length, "Logitech %s", *name);
397 
398 	kfree(*name);
399 
400 	*name = new_name;
401 }
402 
403 /* -------------------------------------------------------------------------- */
404 /* HIDP++ 1.0 commands                                                        */
405 /* -------------------------------------------------------------------------- */
406 
407 #define HIDPP_SET_REGISTER				0x80
408 #define HIDPP_GET_REGISTER				0x81
409 #define HIDPP_SET_LONG_REGISTER				0x82
410 #define HIDPP_GET_LONG_REGISTER				0x83
411 
412 /**
413  * hidpp10_set_register_bit() - Sets a single bit in a HID++ 1.0 register.
414  * @hidpp_dev: the device to set the register on.
415  * @register_address: the address of the register to modify.
416  * @byte: the byte of the register to modify. Should be less than 3.
417  * Return: 0 if successful, otherwise a negative error code.
418  */
419 static int hidpp10_set_register_bit(struct hidpp_device *hidpp_dev,
420 	u8 register_address, u8 byte, u8 bit)
421 {
422 	struct hidpp_report response;
423 	int ret;
424 	u8 params[3] = { 0 };
425 
426 	ret = hidpp_send_rap_command_sync(hidpp_dev,
427 					  REPORT_ID_HIDPP_SHORT,
428 					  HIDPP_GET_REGISTER,
429 					  register_address,
430 					  NULL, 0, &response);
431 	if (ret)
432 		return ret;
433 
434 	memcpy(params, response.rap.params, 3);
435 
436 	params[byte] |= BIT(bit);
437 
438 	return hidpp_send_rap_command_sync(hidpp_dev,
439 					   REPORT_ID_HIDPP_SHORT,
440 					   HIDPP_SET_REGISTER,
441 					   register_address,
442 					   params, 3, &response);
443 }
444 
445 
446 #define HIDPP_REG_GENERAL				0x00
447 
448 static int hidpp10_enable_battery_reporting(struct hidpp_device *hidpp_dev)
449 {
450 	return hidpp10_set_register_bit(hidpp_dev, HIDPP_REG_GENERAL, 0, 4);
451 }
452 
453 #define HIDPP_REG_FEATURES				0x01
454 
455 /* On HID++ 1.0 devices, high-res scroll was called "scrolling acceleration". */
456 static int hidpp10_enable_scrolling_acceleration(struct hidpp_device *hidpp_dev)
457 {
458 	return hidpp10_set_register_bit(hidpp_dev, HIDPP_REG_FEATURES, 0, 6);
459 }
460 
461 #define HIDPP_REG_BATTERY_STATUS			0x07
462 
463 static int hidpp10_battery_status_map_level(u8 param)
464 {
465 	int level;
466 
467 	switch (param) {
468 	case 1 ... 2:
469 		level = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
470 		break;
471 	case 3 ... 4:
472 		level = POWER_SUPPLY_CAPACITY_LEVEL_LOW;
473 		break;
474 	case 5 ... 6:
475 		level = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
476 		break;
477 	case 7:
478 		level = POWER_SUPPLY_CAPACITY_LEVEL_HIGH;
479 		break;
480 	default:
481 		level = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
482 	}
483 
484 	return level;
485 }
486 
487 static int hidpp10_battery_status_map_status(u8 param)
488 {
489 	int status;
490 
491 	switch (param) {
492 	case 0x00:
493 		/* discharging (in use) */
494 		status = POWER_SUPPLY_STATUS_DISCHARGING;
495 		break;
496 	case 0x21: /* (standard) charging */
497 	case 0x24: /* fast charging */
498 	case 0x25: /* slow charging */
499 		status = POWER_SUPPLY_STATUS_CHARGING;
500 		break;
501 	case 0x26: /* topping charge */
502 	case 0x22: /* charge complete */
503 		status = POWER_SUPPLY_STATUS_FULL;
504 		break;
505 	case 0x20: /* unknown */
506 		status = POWER_SUPPLY_STATUS_UNKNOWN;
507 		break;
508 	/*
509 	 * 0x01...0x1F = reserved (not charging)
510 	 * 0x23 = charging error
511 	 * 0x27..0xff = reserved
512 	 */
513 	default:
514 		status = POWER_SUPPLY_STATUS_NOT_CHARGING;
515 		break;
516 	}
517 
518 	return status;
519 }
520 
521 static int hidpp10_query_battery_status(struct hidpp_device *hidpp)
522 {
523 	struct hidpp_report response;
524 	int ret, status;
525 
526 	ret = hidpp_send_rap_command_sync(hidpp,
527 					REPORT_ID_HIDPP_SHORT,
528 					HIDPP_GET_REGISTER,
529 					HIDPP_REG_BATTERY_STATUS,
530 					NULL, 0, &response);
531 	if (ret)
532 		return ret;
533 
534 	hidpp->battery.level =
535 		hidpp10_battery_status_map_level(response.rap.params[0]);
536 	status = hidpp10_battery_status_map_status(response.rap.params[1]);
537 	hidpp->battery.status = status;
538 	/* the capacity is only available when discharging or full */
539 	hidpp->battery.online = status == POWER_SUPPLY_STATUS_DISCHARGING ||
540 				status == POWER_SUPPLY_STATUS_FULL;
541 
542 	return 0;
543 }
544 
545 #define HIDPP_REG_BATTERY_MILEAGE			0x0D
546 
547 static int hidpp10_battery_mileage_map_status(u8 param)
548 {
549 	int status;
550 
551 	switch (param >> 6) {
552 	case 0x00:
553 		/* discharging (in use) */
554 		status = POWER_SUPPLY_STATUS_DISCHARGING;
555 		break;
556 	case 0x01: /* charging */
557 		status = POWER_SUPPLY_STATUS_CHARGING;
558 		break;
559 	case 0x02: /* charge complete */
560 		status = POWER_SUPPLY_STATUS_FULL;
561 		break;
562 	/*
563 	 * 0x03 = charging error
564 	 */
565 	default:
566 		status = POWER_SUPPLY_STATUS_NOT_CHARGING;
567 		break;
568 	}
569 
570 	return status;
571 }
572 
573 static int hidpp10_query_battery_mileage(struct hidpp_device *hidpp)
574 {
575 	struct hidpp_report response;
576 	int ret, status;
577 
578 	ret = hidpp_send_rap_command_sync(hidpp,
579 					REPORT_ID_HIDPP_SHORT,
580 					HIDPP_GET_REGISTER,
581 					HIDPP_REG_BATTERY_MILEAGE,
582 					NULL, 0, &response);
583 	if (ret)
584 		return ret;
585 
586 	hidpp->battery.capacity = response.rap.params[0];
587 	status = hidpp10_battery_mileage_map_status(response.rap.params[2]);
588 	hidpp->battery.status = status;
589 	/* the capacity is only available when discharging or full */
590 	hidpp->battery.online = status == POWER_SUPPLY_STATUS_DISCHARGING ||
591 				status == POWER_SUPPLY_STATUS_FULL;
592 
593 	return 0;
594 }
595 
596 static int hidpp10_battery_event(struct hidpp_device *hidpp, u8 *data, int size)
597 {
598 	struct hidpp_report *report = (struct hidpp_report *)data;
599 	int status, capacity, level;
600 	bool changed;
601 
602 	if (report->report_id != REPORT_ID_HIDPP_SHORT)
603 		return 0;
604 
605 	switch (report->rap.sub_id) {
606 	case HIDPP_REG_BATTERY_STATUS:
607 		capacity = hidpp->battery.capacity;
608 		level = hidpp10_battery_status_map_level(report->rawbytes[1]);
609 		status = hidpp10_battery_status_map_status(report->rawbytes[2]);
610 		break;
611 	case HIDPP_REG_BATTERY_MILEAGE:
612 		capacity = report->rap.params[0];
613 		level = hidpp->battery.level;
614 		status = hidpp10_battery_mileage_map_status(report->rawbytes[3]);
615 		break;
616 	default:
617 		return 0;
618 	}
619 
620 	changed = capacity != hidpp->battery.capacity ||
621 		  level != hidpp->battery.level ||
622 		  status != hidpp->battery.status;
623 
624 	/* the capacity is only available when discharging or full */
625 	hidpp->battery.online = status == POWER_SUPPLY_STATUS_DISCHARGING ||
626 				status == POWER_SUPPLY_STATUS_FULL;
627 
628 	if (changed) {
629 		hidpp->battery.level = level;
630 		hidpp->battery.status = status;
631 		if (hidpp->battery.ps)
632 			power_supply_changed(hidpp->battery.ps);
633 	}
634 
635 	return 0;
636 }
637 
638 #define HIDPP_REG_PAIRING_INFORMATION			0xB5
639 #define HIDPP_EXTENDED_PAIRING				0x30
640 #define HIDPP_DEVICE_NAME				0x40
641 
642 static char *hidpp_unifying_get_name(struct hidpp_device *hidpp_dev)
643 {
644 	struct hidpp_report response;
645 	int ret;
646 	u8 params[1] = { HIDPP_DEVICE_NAME };
647 	char *name;
648 	int len;
649 
650 	ret = hidpp_send_rap_command_sync(hidpp_dev,
651 					REPORT_ID_HIDPP_SHORT,
652 					HIDPP_GET_LONG_REGISTER,
653 					HIDPP_REG_PAIRING_INFORMATION,
654 					params, 1, &response);
655 	if (ret)
656 		return NULL;
657 
658 	len = response.rap.params[1];
659 
660 	if (2 + len > sizeof(response.rap.params))
661 		return NULL;
662 
663 	name = kzalloc(len + 1, GFP_KERNEL);
664 	if (!name)
665 		return NULL;
666 
667 	memcpy(name, &response.rap.params[2], len);
668 
669 	/* include the terminating '\0' */
670 	hidpp_prefix_name(&name, len + 1);
671 
672 	return name;
673 }
674 
675 static int hidpp_unifying_get_serial(struct hidpp_device *hidpp, u32 *serial)
676 {
677 	struct hidpp_report response;
678 	int ret;
679 	u8 params[1] = { HIDPP_EXTENDED_PAIRING };
680 
681 	ret = hidpp_send_rap_command_sync(hidpp,
682 					REPORT_ID_HIDPP_SHORT,
683 					HIDPP_GET_LONG_REGISTER,
684 					HIDPP_REG_PAIRING_INFORMATION,
685 					params, 1, &response);
686 	if (ret)
687 		return ret;
688 
689 	/*
690 	 * We don't care about LE or BE, we will output it as a string
691 	 * with %4phD, so we need to keep the order.
692 	 */
693 	*serial = *((u32 *)&response.rap.params[1]);
694 	return 0;
695 }
696 
697 static int hidpp_unifying_init(struct hidpp_device *hidpp)
698 {
699 	struct hid_device *hdev = hidpp->hid_dev;
700 	const char *name;
701 	u32 serial;
702 	int ret;
703 
704 	ret = hidpp_unifying_get_serial(hidpp, &serial);
705 	if (ret)
706 		return ret;
707 
708 	snprintf(hdev->uniq, sizeof(hdev->uniq), "%04x-%4phD",
709 		 hdev->product, &serial);
710 	dbg_hid("HID++ Unifying: Got serial: %s\n", hdev->uniq);
711 
712 	name = hidpp_unifying_get_name(hidpp);
713 	if (!name)
714 		return -EIO;
715 
716 	snprintf(hdev->name, sizeof(hdev->name), "%s", name);
717 	dbg_hid("HID++ Unifying: Got name: %s\n", name);
718 
719 	kfree(name);
720 	return 0;
721 }
722 
723 /* -------------------------------------------------------------------------- */
724 /* 0x0000: Root                                                               */
725 /* -------------------------------------------------------------------------- */
726 
727 #define HIDPP_PAGE_ROOT					0x0000
728 #define HIDPP_PAGE_ROOT_IDX				0x00
729 
730 #define CMD_ROOT_GET_FEATURE				0x01
731 #define CMD_ROOT_GET_PROTOCOL_VERSION			0x11
732 
733 static int hidpp_root_get_feature(struct hidpp_device *hidpp, u16 feature,
734 	u8 *feature_index, u8 *feature_type)
735 {
736 	struct hidpp_report response;
737 	int ret;
738 	u8 params[2] = { feature >> 8, feature & 0x00FF };
739 
740 	ret = hidpp_send_fap_command_sync(hidpp,
741 			HIDPP_PAGE_ROOT_IDX,
742 			CMD_ROOT_GET_FEATURE,
743 			params, 2, &response);
744 	if (ret)
745 		return ret;
746 
747 	if (response.fap.params[0] == 0)
748 		return -ENOENT;
749 
750 	*feature_index = response.fap.params[0];
751 	*feature_type = response.fap.params[1];
752 
753 	return ret;
754 }
755 
756 static int hidpp_root_get_protocol_version(struct hidpp_device *hidpp)
757 {
758 	struct hidpp_report response;
759 	int ret;
760 
761 	ret = hidpp_send_fap_command_sync(hidpp,
762 			HIDPP_PAGE_ROOT_IDX,
763 			CMD_ROOT_GET_PROTOCOL_VERSION,
764 			NULL, 0, &response);
765 
766 	if (ret == HIDPP_ERROR_INVALID_SUBID) {
767 		hidpp->protocol_major = 1;
768 		hidpp->protocol_minor = 0;
769 		return 0;
770 	}
771 
772 	/* the device might not be connected */
773 	if (ret == HIDPP_ERROR_RESOURCE_ERROR)
774 		return -EIO;
775 
776 	if (ret > 0) {
777 		hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
778 			__func__, ret);
779 		return -EPROTO;
780 	}
781 	if (ret)
782 		return ret;
783 
784 	hidpp->protocol_major = response.fap.params[0];
785 	hidpp->protocol_minor = response.fap.params[1];
786 
787 	return ret;
788 }
789 
790 static bool hidpp_is_connected(struct hidpp_device *hidpp)
791 {
792 	int ret;
793 
794 	ret = hidpp_root_get_protocol_version(hidpp);
795 	if (!ret)
796 		hid_dbg(hidpp->hid_dev, "HID++ %u.%u device connected.\n",
797 			hidpp->protocol_major, hidpp->protocol_minor);
798 	return ret == 0;
799 }
800 
801 /* -------------------------------------------------------------------------- */
802 /* 0x0005: GetDeviceNameType                                                  */
803 /* -------------------------------------------------------------------------- */
804 
805 #define HIDPP_PAGE_GET_DEVICE_NAME_TYPE			0x0005
806 
807 #define CMD_GET_DEVICE_NAME_TYPE_GET_COUNT		0x01
808 #define CMD_GET_DEVICE_NAME_TYPE_GET_DEVICE_NAME	0x11
809 #define CMD_GET_DEVICE_NAME_TYPE_GET_TYPE		0x21
810 
811 static int hidpp_devicenametype_get_count(struct hidpp_device *hidpp,
812 	u8 feature_index, u8 *nameLength)
813 {
814 	struct hidpp_report response;
815 	int ret;
816 
817 	ret = hidpp_send_fap_command_sync(hidpp, feature_index,
818 		CMD_GET_DEVICE_NAME_TYPE_GET_COUNT, NULL, 0, &response);
819 
820 	if (ret > 0) {
821 		hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
822 			__func__, ret);
823 		return -EPROTO;
824 	}
825 	if (ret)
826 		return ret;
827 
828 	*nameLength = response.fap.params[0];
829 
830 	return ret;
831 }
832 
833 static int hidpp_devicenametype_get_device_name(struct hidpp_device *hidpp,
834 	u8 feature_index, u8 char_index, char *device_name, int len_buf)
835 {
836 	struct hidpp_report response;
837 	int ret, i;
838 	int count;
839 
840 	ret = hidpp_send_fap_command_sync(hidpp, feature_index,
841 		CMD_GET_DEVICE_NAME_TYPE_GET_DEVICE_NAME, &char_index, 1,
842 		&response);
843 
844 	if (ret > 0) {
845 		hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
846 			__func__, ret);
847 		return -EPROTO;
848 	}
849 	if (ret)
850 		return ret;
851 
852 	switch (response.report_id) {
853 	case REPORT_ID_HIDPP_VERY_LONG:
854 		count = HIDPP_REPORT_VERY_LONG_LENGTH - 4;
855 		break;
856 	case REPORT_ID_HIDPP_LONG:
857 		count = HIDPP_REPORT_LONG_LENGTH - 4;
858 		break;
859 	case REPORT_ID_HIDPP_SHORT:
860 		count = HIDPP_REPORT_SHORT_LENGTH - 4;
861 		break;
862 	default:
863 		return -EPROTO;
864 	}
865 
866 	if (len_buf < count)
867 		count = len_buf;
868 
869 	for (i = 0; i < count; i++)
870 		device_name[i] = response.fap.params[i];
871 
872 	return count;
873 }
874 
875 static char *hidpp_get_device_name(struct hidpp_device *hidpp)
876 {
877 	u8 feature_type;
878 	u8 feature_index;
879 	u8 __name_length;
880 	char *name;
881 	unsigned index = 0;
882 	int ret;
883 
884 	ret = hidpp_root_get_feature(hidpp, HIDPP_PAGE_GET_DEVICE_NAME_TYPE,
885 		&feature_index, &feature_type);
886 	if (ret)
887 		return NULL;
888 
889 	ret = hidpp_devicenametype_get_count(hidpp, feature_index,
890 		&__name_length);
891 	if (ret)
892 		return NULL;
893 
894 	name = kzalloc(__name_length + 1, GFP_KERNEL);
895 	if (!name)
896 		return NULL;
897 
898 	while (index < __name_length) {
899 		ret = hidpp_devicenametype_get_device_name(hidpp,
900 			feature_index, index, name + index,
901 			__name_length - index);
902 		if (ret <= 0) {
903 			kfree(name);
904 			return NULL;
905 		}
906 		index += ret;
907 	}
908 
909 	/* include the terminating '\0' */
910 	hidpp_prefix_name(&name, __name_length + 1);
911 
912 	return name;
913 }
914 
915 /* -------------------------------------------------------------------------- */
916 /* 0x1000: Battery level status                                               */
917 /* -------------------------------------------------------------------------- */
918 
919 #define HIDPP_PAGE_BATTERY_LEVEL_STATUS				0x1000
920 
921 #define CMD_BATTERY_LEVEL_STATUS_GET_BATTERY_LEVEL_STATUS	0x00
922 #define CMD_BATTERY_LEVEL_STATUS_GET_BATTERY_CAPABILITY		0x10
923 
924 #define EVENT_BATTERY_LEVEL_STATUS_BROADCAST			0x00
925 
926 #define FLAG_BATTERY_LEVEL_DISABLE_OSD				BIT(0)
927 #define FLAG_BATTERY_LEVEL_MILEAGE				BIT(1)
928 #define FLAG_BATTERY_LEVEL_RECHARGEABLE				BIT(2)
929 
930 static int hidpp_map_battery_level(int capacity)
931 {
932 	if (capacity < 11)
933 		return POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
934 	else if (capacity < 31)
935 		return POWER_SUPPLY_CAPACITY_LEVEL_LOW;
936 	else if (capacity < 81)
937 		return POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
938 	return POWER_SUPPLY_CAPACITY_LEVEL_FULL;
939 }
940 
941 static int hidpp20_batterylevel_map_status_capacity(u8 data[3], int *capacity,
942 						    int *next_capacity,
943 						    int *level)
944 {
945 	int status;
946 
947 	*capacity = data[0];
948 	*next_capacity = data[1];
949 	*level = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
950 
951 	/* When discharging, we can rely on the device reported capacity.
952 	 * For all other states the device reports 0 (unknown).
953 	 */
954 	switch (data[2]) {
955 		case 0: /* discharging (in use) */
956 			status = POWER_SUPPLY_STATUS_DISCHARGING;
957 			*level = hidpp_map_battery_level(*capacity);
958 			break;
959 		case 1: /* recharging */
960 			status = POWER_SUPPLY_STATUS_CHARGING;
961 			break;
962 		case 2: /* charge in final stage */
963 			status = POWER_SUPPLY_STATUS_CHARGING;
964 			break;
965 		case 3: /* charge complete */
966 			status = POWER_SUPPLY_STATUS_FULL;
967 			*level = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
968 			*capacity = 100;
969 			break;
970 		case 4: /* recharging below optimal speed */
971 			status = POWER_SUPPLY_STATUS_CHARGING;
972 			break;
973 		/* 5 = invalid battery type
974 		   6 = thermal error
975 		   7 = other charging error */
976 		default:
977 			status = POWER_SUPPLY_STATUS_NOT_CHARGING;
978 			break;
979 	}
980 
981 	return status;
982 }
983 
984 static int hidpp20_batterylevel_get_battery_capacity(struct hidpp_device *hidpp,
985 						     u8 feature_index,
986 						     int *status,
987 						     int *capacity,
988 						     int *next_capacity,
989 						     int *level)
990 {
991 	struct hidpp_report response;
992 	int ret;
993 	u8 *params = (u8 *)response.fap.params;
994 
995 	ret = hidpp_send_fap_command_sync(hidpp, feature_index,
996 					  CMD_BATTERY_LEVEL_STATUS_GET_BATTERY_LEVEL_STATUS,
997 					  NULL, 0, &response);
998 	if (ret > 0) {
999 		hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
1000 			__func__, ret);
1001 		return -EPROTO;
1002 	}
1003 	if (ret)
1004 		return ret;
1005 
1006 	*status = hidpp20_batterylevel_map_status_capacity(params, capacity,
1007 							   next_capacity,
1008 							   level);
1009 
1010 	return 0;
1011 }
1012 
1013 static int hidpp20_batterylevel_get_battery_info(struct hidpp_device *hidpp,
1014 						  u8 feature_index)
1015 {
1016 	struct hidpp_report response;
1017 	int ret;
1018 	u8 *params = (u8 *)response.fap.params;
1019 	unsigned int level_count, flags;
1020 
1021 	ret = hidpp_send_fap_command_sync(hidpp, feature_index,
1022 					  CMD_BATTERY_LEVEL_STATUS_GET_BATTERY_CAPABILITY,
1023 					  NULL, 0, &response);
1024 	if (ret > 0) {
1025 		hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
1026 			__func__, ret);
1027 		return -EPROTO;
1028 	}
1029 	if (ret)
1030 		return ret;
1031 
1032 	level_count = params[0];
1033 	flags = params[1];
1034 
1035 	if (level_count < 10 || !(flags & FLAG_BATTERY_LEVEL_MILEAGE))
1036 		hidpp->capabilities |= HIDPP_CAPABILITY_BATTERY_LEVEL_STATUS;
1037 	else
1038 		hidpp->capabilities |= HIDPP_CAPABILITY_BATTERY_MILEAGE;
1039 
1040 	return 0;
1041 }
1042 
1043 static int hidpp20_query_battery_info(struct hidpp_device *hidpp)
1044 {
1045 	u8 feature_type;
1046 	int ret;
1047 	int status, capacity, next_capacity, level;
1048 
1049 	if (hidpp->battery.feature_index == 0xff) {
1050 		ret = hidpp_root_get_feature(hidpp,
1051 					     HIDPP_PAGE_BATTERY_LEVEL_STATUS,
1052 					     &hidpp->battery.feature_index,
1053 					     &feature_type);
1054 		if (ret)
1055 			return ret;
1056 	}
1057 
1058 	ret = hidpp20_batterylevel_get_battery_capacity(hidpp,
1059 						hidpp->battery.feature_index,
1060 						&status, &capacity,
1061 						&next_capacity, &level);
1062 	if (ret)
1063 		return ret;
1064 
1065 	ret = hidpp20_batterylevel_get_battery_info(hidpp,
1066 						hidpp->battery.feature_index);
1067 	if (ret)
1068 		return ret;
1069 
1070 	hidpp->battery.status = status;
1071 	hidpp->battery.capacity = capacity;
1072 	hidpp->battery.level = level;
1073 	/* the capacity is only available when discharging or full */
1074 	hidpp->battery.online = status == POWER_SUPPLY_STATUS_DISCHARGING ||
1075 				status == POWER_SUPPLY_STATUS_FULL;
1076 
1077 	return 0;
1078 }
1079 
1080 static int hidpp20_battery_event(struct hidpp_device *hidpp,
1081 				 u8 *data, int size)
1082 {
1083 	struct hidpp_report *report = (struct hidpp_report *)data;
1084 	int status, capacity, next_capacity, level;
1085 	bool changed;
1086 
1087 	if (report->fap.feature_index != hidpp->battery.feature_index ||
1088 	    report->fap.funcindex_clientid != EVENT_BATTERY_LEVEL_STATUS_BROADCAST)
1089 		return 0;
1090 
1091 	status = hidpp20_batterylevel_map_status_capacity(report->fap.params,
1092 							  &capacity,
1093 							  &next_capacity,
1094 							  &level);
1095 
1096 	/* the capacity is only available when discharging or full */
1097 	hidpp->battery.online = status == POWER_SUPPLY_STATUS_DISCHARGING ||
1098 				status == POWER_SUPPLY_STATUS_FULL;
1099 
1100 	changed = capacity != hidpp->battery.capacity ||
1101 		  level != hidpp->battery.level ||
1102 		  status != hidpp->battery.status;
1103 
1104 	if (changed) {
1105 		hidpp->battery.level = level;
1106 		hidpp->battery.capacity = capacity;
1107 		hidpp->battery.status = status;
1108 		if (hidpp->battery.ps)
1109 			power_supply_changed(hidpp->battery.ps);
1110 	}
1111 
1112 	return 0;
1113 }
1114 
1115 static enum power_supply_property hidpp_battery_props[] = {
1116 	POWER_SUPPLY_PROP_ONLINE,
1117 	POWER_SUPPLY_PROP_STATUS,
1118 	POWER_SUPPLY_PROP_SCOPE,
1119 	POWER_SUPPLY_PROP_MODEL_NAME,
1120 	POWER_SUPPLY_PROP_MANUFACTURER,
1121 	POWER_SUPPLY_PROP_SERIAL_NUMBER,
1122 	0, /* placeholder for POWER_SUPPLY_PROP_CAPACITY, */
1123 	0, /* placeholder for POWER_SUPPLY_PROP_CAPACITY_LEVEL, */
1124 };
1125 
1126 static int hidpp_battery_get_property(struct power_supply *psy,
1127 				      enum power_supply_property psp,
1128 				      union power_supply_propval *val)
1129 {
1130 	struct hidpp_device *hidpp = power_supply_get_drvdata(psy);
1131 	int ret = 0;
1132 
1133 	switch(psp) {
1134 		case POWER_SUPPLY_PROP_STATUS:
1135 			val->intval = hidpp->battery.status;
1136 			break;
1137 		case POWER_SUPPLY_PROP_CAPACITY:
1138 			val->intval = hidpp->battery.capacity;
1139 			break;
1140 		case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
1141 			val->intval = hidpp->battery.level;
1142 			break;
1143 		case POWER_SUPPLY_PROP_SCOPE:
1144 			val->intval = POWER_SUPPLY_SCOPE_DEVICE;
1145 			break;
1146 		case POWER_SUPPLY_PROP_ONLINE:
1147 			val->intval = hidpp->battery.online;
1148 			break;
1149 		case POWER_SUPPLY_PROP_MODEL_NAME:
1150 			if (!strncmp(hidpp->name, "Logitech ", 9))
1151 				val->strval = hidpp->name + 9;
1152 			else
1153 				val->strval = hidpp->name;
1154 			break;
1155 		case POWER_SUPPLY_PROP_MANUFACTURER:
1156 			val->strval = "Logitech";
1157 			break;
1158 		case POWER_SUPPLY_PROP_SERIAL_NUMBER:
1159 			val->strval = hidpp->hid_dev->uniq;
1160 			break;
1161 		default:
1162 			ret = -EINVAL;
1163 			break;
1164 	}
1165 
1166 	return ret;
1167 }
1168 
1169 /* -------------------------------------------------------------------------- */
1170 /* 0x2120: Hi-resolution scrolling                                            */
1171 /* -------------------------------------------------------------------------- */
1172 
1173 #define HIDPP_PAGE_HI_RESOLUTION_SCROLLING			0x2120
1174 
1175 #define CMD_HI_RESOLUTION_SCROLLING_SET_HIGHRES_SCROLLING_MODE	0x10
1176 
1177 static int hidpp_hrs_set_highres_scrolling_mode(struct hidpp_device *hidpp,
1178 	bool enabled, u8 *multiplier)
1179 {
1180 	u8 feature_index;
1181 	u8 feature_type;
1182 	int ret;
1183 	u8 params[1];
1184 	struct hidpp_report response;
1185 
1186 	ret = hidpp_root_get_feature(hidpp,
1187 				     HIDPP_PAGE_HI_RESOLUTION_SCROLLING,
1188 				     &feature_index,
1189 				     &feature_type);
1190 	if (ret)
1191 		return ret;
1192 
1193 	params[0] = enabled ? BIT(0) : 0;
1194 	ret = hidpp_send_fap_command_sync(hidpp, feature_index,
1195 					  CMD_HI_RESOLUTION_SCROLLING_SET_HIGHRES_SCROLLING_MODE,
1196 					  params, sizeof(params), &response);
1197 	if (ret)
1198 		return ret;
1199 	*multiplier = response.fap.params[1];
1200 	return 0;
1201 }
1202 
1203 /* -------------------------------------------------------------------------- */
1204 /* 0x2121: HiRes Wheel                                                        */
1205 /* -------------------------------------------------------------------------- */
1206 
1207 #define HIDPP_PAGE_HIRES_WHEEL		0x2121
1208 
1209 #define CMD_HIRES_WHEEL_GET_WHEEL_CAPABILITY	0x00
1210 #define CMD_HIRES_WHEEL_SET_WHEEL_MODE		0x20
1211 
1212 static int hidpp_hrw_get_wheel_capability(struct hidpp_device *hidpp,
1213 	u8 *multiplier)
1214 {
1215 	u8 feature_index;
1216 	u8 feature_type;
1217 	int ret;
1218 	struct hidpp_report response;
1219 
1220 	ret = hidpp_root_get_feature(hidpp, HIDPP_PAGE_HIRES_WHEEL,
1221 				     &feature_index, &feature_type);
1222 	if (ret)
1223 		goto return_default;
1224 
1225 	ret = hidpp_send_fap_command_sync(hidpp, feature_index,
1226 					  CMD_HIRES_WHEEL_GET_WHEEL_CAPABILITY,
1227 					  NULL, 0, &response);
1228 	if (ret)
1229 		goto return_default;
1230 
1231 	*multiplier = response.fap.params[0];
1232 	return 0;
1233 return_default:
1234 	hid_warn(hidpp->hid_dev,
1235 		 "Couldn't get wheel multiplier (error %d), assuming %d.\n",
1236 		 ret, *multiplier);
1237 	return ret;
1238 }
1239 
1240 static int hidpp_hrw_set_wheel_mode(struct hidpp_device *hidpp, bool invert,
1241 	bool high_resolution, bool use_hidpp)
1242 {
1243 	u8 feature_index;
1244 	u8 feature_type;
1245 	int ret;
1246 	u8 params[1];
1247 	struct hidpp_report response;
1248 
1249 	ret = hidpp_root_get_feature(hidpp, HIDPP_PAGE_HIRES_WHEEL,
1250 				     &feature_index, &feature_type);
1251 	if (ret)
1252 		return ret;
1253 
1254 	params[0] = (invert          ? BIT(2) : 0) |
1255 		    (high_resolution ? BIT(1) : 0) |
1256 		    (use_hidpp       ? BIT(0) : 0);
1257 
1258 	return hidpp_send_fap_command_sync(hidpp, feature_index,
1259 					   CMD_HIRES_WHEEL_SET_WHEEL_MODE,
1260 					   params, sizeof(params), &response);
1261 }
1262 
1263 /* -------------------------------------------------------------------------- */
1264 /* 0x4301: Solar Keyboard                                                     */
1265 /* -------------------------------------------------------------------------- */
1266 
1267 #define HIDPP_PAGE_SOLAR_KEYBOARD			0x4301
1268 
1269 #define CMD_SOLAR_SET_LIGHT_MEASURE			0x00
1270 
1271 #define EVENT_SOLAR_BATTERY_BROADCAST			0x00
1272 #define EVENT_SOLAR_BATTERY_LIGHT_MEASURE		0x10
1273 #define EVENT_SOLAR_CHECK_LIGHT_BUTTON			0x20
1274 
1275 static int hidpp_solar_request_battery_event(struct hidpp_device *hidpp)
1276 {
1277 	struct hidpp_report response;
1278 	u8 params[2] = { 1, 1 };
1279 	u8 feature_type;
1280 	int ret;
1281 
1282 	if (hidpp->battery.feature_index == 0xff) {
1283 		ret = hidpp_root_get_feature(hidpp,
1284 					     HIDPP_PAGE_SOLAR_KEYBOARD,
1285 					     &hidpp->battery.solar_feature_index,
1286 					     &feature_type);
1287 		if (ret)
1288 			return ret;
1289 	}
1290 
1291 	ret = hidpp_send_fap_command_sync(hidpp,
1292 					  hidpp->battery.solar_feature_index,
1293 					  CMD_SOLAR_SET_LIGHT_MEASURE,
1294 					  params, 2, &response);
1295 	if (ret > 0) {
1296 		hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
1297 			__func__, ret);
1298 		return -EPROTO;
1299 	}
1300 	if (ret)
1301 		return ret;
1302 
1303 	hidpp->capabilities |= HIDPP_CAPABILITY_BATTERY_MILEAGE;
1304 
1305 	return 0;
1306 }
1307 
1308 static int hidpp_solar_battery_event(struct hidpp_device *hidpp,
1309 				     u8 *data, int size)
1310 {
1311 	struct hidpp_report *report = (struct hidpp_report *)data;
1312 	int capacity, lux, status;
1313 	u8 function;
1314 
1315 	function = report->fap.funcindex_clientid;
1316 
1317 
1318 	if (report->fap.feature_index != hidpp->battery.solar_feature_index ||
1319 	    !(function == EVENT_SOLAR_BATTERY_BROADCAST ||
1320 	      function == EVENT_SOLAR_BATTERY_LIGHT_MEASURE ||
1321 	      function == EVENT_SOLAR_CHECK_LIGHT_BUTTON))
1322 		return 0;
1323 
1324 	capacity = report->fap.params[0];
1325 
1326 	switch (function) {
1327 	case EVENT_SOLAR_BATTERY_LIGHT_MEASURE:
1328 		lux = (report->fap.params[1] << 8) | report->fap.params[2];
1329 		if (lux > 200)
1330 			status = POWER_SUPPLY_STATUS_CHARGING;
1331 		else
1332 			status = POWER_SUPPLY_STATUS_DISCHARGING;
1333 		break;
1334 	case EVENT_SOLAR_CHECK_LIGHT_BUTTON:
1335 	default:
1336 		if (capacity < hidpp->battery.capacity)
1337 			status = POWER_SUPPLY_STATUS_DISCHARGING;
1338 		else
1339 			status = POWER_SUPPLY_STATUS_CHARGING;
1340 
1341 	}
1342 
1343 	if (capacity == 100)
1344 		status = POWER_SUPPLY_STATUS_FULL;
1345 
1346 	hidpp->battery.online = true;
1347 	if (capacity != hidpp->battery.capacity ||
1348 	    status != hidpp->battery.status) {
1349 		hidpp->battery.capacity = capacity;
1350 		hidpp->battery.status = status;
1351 		if (hidpp->battery.ps)
1352 			power_supply_changed(hidpp->battery.ps);
1353 	}
1354 
1355 	return 0;
1356 }
1357 
1358 /* -------------------------------------------------------------------------- */
1359 /* 0x6010: Touchpad FW items                                                  */
1360 /* -------------------------------------------------------------------------- */
1361 
1362 #define HIDPP_PAGE_TOUCHPAD_FW_ITEMS			0x6010
1363 
1364 #define CMD_TOUCHPAD_FW_ITEMS_SET			0x10
1365 
1366 struct hidpp_touchpad_fw_items {
1367 	uint8_t presence;
1368 	uint8_t desired_state;
1369 	uint8_t state;
1370 	uint8_t persistent;
1371 };
1372 
1373 /**
1374  * send a set state command to the device by reading the current items->state
1375  * field. items is then filled with the current state.
1376  */
1377 static int hidpp_touchpad_fw_items_set(struct hidpp_device *hidpp,
1378 				       u8 feature_index,
1379 				       struct hidpp_touchpad_fw_items *items)
1380 {
1381 	struct hidpp_report response;
1382 	int ret;
1383 	u8 *params = (u8 *)response.fap.params;
1384 
1385 	ret = hidpp_send_fap_command_sync(hidpp, feature_index,
1386 		CMD_TOUCHPAD_FW_ITEMS_SET, &items->state, 1, &response);
1387 
1388 	if (ret > 0) {
1389 		hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
1390 			__func__, ret);
1391 		return -EPROTO;
1392 	}
1393 	if (ret)
1394 		return ret;
1395 
1396 	items->presence = params[0];
1397 	items->desired_state = params[1];
1398 	items->state = params[2];
1399 	items->persistent = params[3];
1400 
1401 	return 0;
1402 }
1403 
1404 /* -------------------------------------------------------------------------- */
1405 /* 0x6100: TouchPadRawXY                                                      */
1406 /* -------------------------------------------------------------------------- */
1407 
1408 #define HIDPP_PAGE_TOUCHPAD_RAW_XY			0x6100
1409 
1410 #define CMD_TOUCHPAD_GET_RAW_INFO			0x01
1411 #define CMD_TOUCHPAD_SET_RAW_REPORT_STATE		0x21
1412 
1413 #define EVENT_TOUCHPAD_RAW_XY				0x00
1414 
1415 #define TOUCHPAD_RAW_XY_ORIGIN_LOWER_LEFT		0x01
1416 #define TOUCHPAD_RAW_XY_ORIGIN_UPPER_LEFT		0x03
1417 
1418 struct hidpp_touchpad_raw_info {
1419 	u16 x_size;
1420 	u16 y_size;
1421 	u8 z_range;
1422 	u8 area_range;
1423 	u8 timestamp_unit;
1424 	u8 maxcontacts;
1425 	u8 origin;
1426 	u16 res;
1427 };
1428 
1429 struct hidpp_touchpad_raw_xy_finger {
1430 	u8 contact_type;
1431 	u8 contact_status;
1432 	u16 x;
1433 	u16 y;
1434 	u8 z;
1435 	u8 area;
1436 	u8 finger_id;
1437 };
1438 
1439 struct hidpp_touchpad_raw_xy {
1440 	u16 timestamp;
1441 	struct hidpp_touchpad_raw_xy_finger fingers[2];
1442 	u8 spurious_flag;
1443 	u8 end_of_frame;
1444 	u8 finger_count;
1445 	u8 button;
1446 };
1447 
1448 static int hidpp_touchpad_get_raw_info(struct hidpp_device *hidpp,
1449 	u8 feature_index, struct hidpp_touchpad_raw_info *raw_info)
1450 {
1451 	struct hidpp_report response;
1452 	int ret;
1453 	u8 *params = (u8 *)response.fap.params;
1454 
1455 	ret = hidpp_send_fap_command_sync(hidpp, feature_index,
1456 		CMD_TOUCHPAD_GET_RAW_INFO, NULL, 0, &response);
1457 
1458 	if (ret > 0) {
1459 		hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
1460 			__func__, ret);
1461 		return -EPROTO;
1462 	}
1463 	if (ret)
1464 		return ret;
1465 
1466 	raw_info->x_size = get_unaligned_be16(&params[0]);
1467 	raw_info->y_size = get_unaligned_be16(&params[2]);
1468 	raw_info->z_range = params[4];
1469 	raw_info->area_range = params[5];
1470 	raw_info->maxcontacts = params[7];
1471 	raw_info->origin = params[8];
1472 	/* res is given in unit per inch */
1473 	raw_info->res = get_unaligned_be16(&params[13]) * 2 / 51;
1474 
1475 	return ret;
1476 }
1477 
1478 static int hidpp_touchpad_set_raw_report_state(struct hidpp_device *hidpp_dev,
1479 		u8 feature_index, bool send_raw_reports,
1480 		bool sensor_enhanced_settings)
1481 {
1482 	struct hidpp_report response;
1483 
1484 	/*
1485 	 * Params:
1486 	 *   bit 0 - enable raw
1487 	 *   bit 1 - 16bit Z, no area
1488 	 *   bit 2 - enhanced sensitivity
1489 	 *   bit 3 - width, height (4 bits each) instead of area
1490 	 *   bit 4 - send raw + gestures (degrades smoothness)
1491 	 *   remaining bits - reserved
1492 	 */
1493 	u8 params = send_raw_reports | (sensor_enhanced_settings << 2);
1494 
1495 	return hidpp_send_fap_command_sync(hidpp_dev, feature_index,
1496 		CMD_TOUCHPAD_SET_RAW_REPORT_STATE, &params, 1, &response);
1497 }
1498 
1499 static void hidpp_touchpad_touch_event(u8 *data,
1500 	struct hidpp_touchpad_raw_xy_finger *finger)
1501 {
1502 	u8 x_m = data[0] << 2;
1503 	u8 y_m = data[2] << 2;
1504 
1505 	finger->x = x_m << 6 | data[1];
1506 	finger->y = y_m << 6 | data[3];
1507 
1508 	finger->contact_type = data[0] >> 6;
1509 	finger->contact_status = data[2] >> 6;
1510 
1511 	finger->z = data[4];
1512 	finger->area = data[5];
1513 	finger->finger_id = data[6] >> 4;
1514 }
1515 
1516 static void hidpp_touchpad_raw_xy_event(struct hidpp_device *hidpp_dev,
1517 		u8 *data, struct hidpp_touchpad_raw_xy *raw_xy)
1518 {
1519 	memset(raw_xy, 0, sizeof(struct hidpp_touchpad_raw_xy));
1520 	raw_xy->end_of_frame = data[8] & 0x01;
1521 	raw_xy->spurious_flag = (data[8] >> 1) & 0x01;
1522 	raw_xy->finger_count = data[15] & 0x0f;
1523 	raw_xy->button = (data[8] >> 2) & 0x01;
1524 
1525 	if (raw_xy->finger_count) {
1526 		hidpp_touchpad_touch_event(&data[2], &raw_xy->fingers[0]);
1527 		hidpp_touchpad_touch_event(&data[9], &raw_xy->fingers[1]);
1528 	}
1529 }
1530 
1531 /* -------------------------------------------------------------------------- */
1532 /* 0x8123: Force feedback support                                             */
1533 /* -------------------------------------------------------------------------- */
1534 
1535 #define HIDPP_FF_GET_INFO		0x01
1536 #define HIDPP_FF_RESET_ALL		0x11
1537 #define HIDPP_FF_DOWNLOAD_EFFECT	0x21
1538 #define HIDPP_FF_SET_EFFECT_STATE	0x31
1539 #define HIDPP_FF_DESTROY_EFFECT		0x41
1540 #define HIDPP_FF_GET_APERTURE		0x51
1541 #define HIDPP_FF_SET_APERTURE		0x61
1542 #define HIDPP_FF_GET_GLOBAL_GAINS	0x71
1543 #define HIDPP_FF_SET_GLOBAL_GAINS	0x81
1544 
1545 #define HIDPP_FF_EFFECT_STATE_GET	0x00
1546 #define HIDPP_FF_EFFECT_STATE_STOP	0x01
1547 #define HIDPP_FF_EFFECT_STATE_PLAY	0x02
1548 #define HIDPP_FF_EFFECT_STATE_PAUSE	0x03
1549 
1550 #define HIDPP_FF_EFFECT_CONSTANT	0x00
1551 #define HIDPP_FF_EFFECT_PERIODIC_SINE		0x01
1552 #define HIDPP_FF_EFFECT_PERIODIC_SQUARE		0x02
1553 #define HIDPP_FF_EFFECT_PERIODIC_TRIANGLE	0x03
1554 #define HIDPP_FF_EFFECT_PERIODIC_SAWTOOTHUP	0x04
1555 #define HIDPP_FF_EFFECT_PERIODIC_SAWTOOTHDOWN	0x05
1556 #define HIDPP_FF_EFFECT_SPRING		0x06
1557 #define HIDPP_FF_EFFECT_DAMPER		0x07
1558 #define HIDPP_FF_EFFECT_FRICTION	0x08
1559 #define HIDPP_FF_EFFECT_INERTIA		0x09
1560 #define HIDPP_FF_EFFECT_RAMP		0x0A
1561 
1562 #define HIDPP_FF_EFFECT_AUTOSTART	0x80
1563 
1564 #define HIDPP_FF_EFFECTID_NONE		-1
1565 #define HIDPP_FF_EFFECTID_AUTOCENTER	-2
1566 
1567 #define HIDPP_FF_MAX_PARAMS	20
1568 #define HIDPP_FF_RESERVED_SLOTS	1
1569 
1570 struct hidpp_ff_private_data {
1571 	struct hidpp_device *hidpp;
1572 	u8 feature_index;
1573 	u8 version;
1574 	u16 gain;
1575 	s16 range;
1576 	u8 slot_autocenter;
1577 	u8 num_effects;
1578 	int *effect_ids;
1579 	struct workqueue_struct *wq;
1580 	atomic_t workqueue_size;
1581 };
1582 
1583 struct hidpp_ff_work_data {
1584 	struct work_struct work;
1585 	struct hidpp_ff_private_data *data;
1586 	int effect_id;
1587 	u8 command;
1588 	u8 params[HIDPP_FF_MAX_PARAMS];
1589 	u8 size;
1590 };
1591 
1592 static const signed short hiddpp_ff_effects[] = {
1593 	FF_CONSTANT,
1594 	FF_PERIODIC,
1595 	FF_SINE,
1596 	FF_SQUARE,
1597 	FF_SAW_UP,
1598 	FF_SAW_DOWN,
1599 	FF_TRIANGLE,
1600 	FF_SPRING,
1601 	FF_DAMPER,
1602 	FF_AUTOCENTER,
1603 	FF_GAIN,
1604 	-1
1605 };
1606 
1607 static const signed short hiddpp_ff_effects_v2[] = {
1608 	FF_RAMP,
1609 	FF_FRICTION,
1610 	FF_INERTIA,
1611 	-1
1612 };
1613 
1614 static const u8 HIDPP_FF_CONDITION_CMDS[] = {
1615 	HIDPP_FF_EFFECT_SPRING,
1616 	HIDPP_FF_EFFECT_FRICTION,
1617 	HIDPP_FF_EFFECT_DAMPER,
1618 	HIDPP_FF_EFFECT_INERTIA
1619 };
1620 
1621 static const char *HIDPP_FF_CONDITION_NAMES[] = {
1622 	"spring",
1623 	"friction",
1624 	"damper",
1625 	"inertia"
1626 };
1627 
1628 
1629 static u8 hidpp_ff_find_effect(struct hidpp_ff_private_data *data, int effect_id)
1630 {
1631 	int i;
1632 
1633 	for (i = 0; i < data->num_effects; i++)
1634 		if (data->effect_ids[i] == effect_id)
1635 			return i+1;
1636 
1637 	return 0;
1638 }
1639 
1640 static void hidpp_ff_work_handler(struct work_struct *w)
1641 {
1642 	struct hidpp_ff_work_data *wd = container_of(w, struct hidpp_ff_work_data, work);
1643 	struct hidpp_ff_private_data *data = wd->data;
1644 	struct hidpp_report response;
1645 	u8 slot;
1646 	int ret;
1647 
1648 	/* add slot number if needed */
1649 	switch (wd->effect_id) {
1650 	case HIDPP_FF_EFFECTID_AUTOCENTER:
1651 		wd->params[0] = data->slot_autocenter;
1652 		break;
1653 	case HIDPP_FF_EFFECTID_NONE:
1654 		/* leave slot as zero */
1655 		break;
1656 	default:
1657 		/* find current slot for effect */
1658 		wd->params[0] = hidpp_ff_find_effect(data, wd->effect_id);
1659 		break;
1660 	}
1661 
1662 	/* send command and wait for reply */
1663 	ret = hidpp_send_fap_command_sync(data->hidpp, data->feature_index,
1664 		wd->command, wd->params, wd->size, &response);
1665 
1666 	if (ret) {
1667 		hid_err(data->hidpp->hid_dev, "Failed to send command to device!\n");
1668 		goto out;
1669 	}
1670 
1671 	/* parse return data */
1672 	switch (wd->command) {
1673 	case HIDPP_FF_DOWNLOAD_EFFECT:
1674 		slot = response.fap.params[0];
1675 		if (slot > 0 && slot <= data->num_effects) {
1676 			if (wd->effect_id >= 0)
1677 				/* regular effect uploaded */
1678 				data->effect_ids[slot-1] = wd->effect_id;
1679 			else if (wd->effect_id >= HIDPP_FF_EFFECTID_AUTOCENTER)
1680 				/* autocenter spring uploaded */
1681 				data->slot_autocenter = slot;
1682 		}
1683 		break;
1684 	case HIDPP_FF_DESTROY_EFFECT:
1685 		if (wd->effect_id >= 0)
1686 			/* regular effect destroyed */
1687 			data->effect_ids[wd->params[0]-1] = -1;
1688 		else if (wd->effect_id >= HIDPP_FF_EFFECTID_AUTOCENTER)
1689 			/* autocenter spring destoyed */
1690 			data->slot_autocenter = 0;
1691 		break;
1692 	case HIDPP_FF_SET_GLOBAL_GAINS:
1693 		data->gain = (wd->params[0] << 8) + wd->params[1];
1694 		break;
1695 	case HIDPP_FF_SET_APERTURE:
1696 		data->range = (wd->params[0] << 8) + wd->params[1];
1697 		break;
1698 	default:
1699 		/* no action needed */
1700 		break;
1701 	}
1702 
1703 out:
1704 	atomic_dec(&data->workqueue_size);
1705 	kfree(wd);
1706 }
1707 
1708 static int hidpp_ff_queue_work(struct hidpp_ff_private_data *data, int effect_id, u8 command, u8 *params, u8 size)
1709 {
1710 	struct hidpp_ff_work_data *wd = kzalloc(sizeof(*wd), GFP_KERNEL);
1711 	int s;
1712 
1713 	if (!wd)
1714 		return -ENOMEM;
1715 
1716 	INIT_WORK(&wd->work, hidpp_ff_work_handler);
1717 
1718 	wd->data = data;
1719 	wd->effect_id = effect_id;
1720 	wd->command = command;
1721 	wd->size = size;
1722 	memcpy(wd->params, params, size);
1723 
1724 	atomic_inc(&data->workqueue_size);
1725 	queue_work(data->wq, &wd->work);
1726 
1727 	/* warn about excessive queue size */
1728 	s = atomic_read(&data->workqueue_size);
1729 	if (s >= 20 && s % 20 == 0)
1730 		hid_warn(data->hidpp->hid_dev, "Force feedback command queue contains %d commands, causing substantial delays!", s);
1731 
1732 	return 0;
1733 }
1734 
1735 static int hidpp_ff_upload_effect(struct input_dev *dev, struct ff_effect *effect, struct ff_effect *old)
1736 {
1737 	struct hidpp_ff_private_data *data = dev->ff->private;
1738 	u8 params[20];
1739 	u8 size;
1740 	int force;
1741 
1742 	/* set common parameters */
1743 	params[2] = effect->replay.length >> 8;
1744 	params[3] = effect->replay.length & 255;
1745 	params[4] = effect->replay.delay >> 8;
1746 	params[5] = effect->replay.delay & 255;
1747 
1748 	switch (effect->type) {
1749 	case FF_CONSTANT:
1750 		force = (effect->u.constant.level * fixp_sin16((effect->direction * 360) >> 16)) >> 15;
1751 		params[1] = HIDPP_FF_EFFECT_CONSTANT;
1752 		params[6] = force >> 8;
1753 		params[7] = force & 255;
1754 		params[8] = effect->u.constant.envelope.attack_level >> 7;
1755 		params[9] = effect->u.constant.envelope.attack_length >> 8;
1756 		params[10] = effect->u.constant.envelope.attack_length & 255;
1757 		params[11] = effect->u.constant.envelope.fade_level >> 7;
1758 		params[12] = effect->u.constant.envelope.fade_length >> 8;
1759 		params[13] = effect->u.constant.envelope.fade_length & 255;
1760 		size = 14;
1761 		dbg_hid("Uploading constant force level=%d in dir %d = %d\n",
1762 				effect->u.constant.level,
1763 				effect->direction, force);
1764 		dbg_hid("          envelope attack=(%d, %d ms) fade=(%d, %d ms)\n",
1765 				effect->u.constant.envelope.attack_level,
1766 				effect->u.constant.envelope.attack_length,
1767 				effect->u.constant.envelope.fade_level,
1768 				effect->u.constant.envelope.fade_length);
1769 		break;
1770 	case FF_PERIODIC:
1771 	{
1772 		switch (effect->u.periodic.waveform) {
1773 		case FF_SINE:
1774 			params[1] = HIDPP_FF_EFFECT_PERIODIC_SINE;
1775 			break;
1776 		case FF_SQUARE:
1777 			params[1] = HIDPP_FF_EFFECT_PERIODIC_SQUARE;
1778 			break;
1779 		case FF_SAW_UP:
1780 			params[1] = HIDPP_FF_EFFECT_PERIODIC_SAWTOOTHUP;
1781 			break;
1782 		case FF_SAW_DOWN:
1783 			params[1] = HIDPP_FF_EFFECT_PERIODIC_SAWTOOTHDOWN;
1784 			break;
1785 		case FF_TRIANGLE:
1786 			params[1] = HIDPP_FF_EFFECT_PERIODIC_TRIANGLE;
1787 			break;
1788 		default:
1789 			hid_err(data->hidpp->hid_dev, "Unexpected periodic waveform type %i!\n", effect->u.periodic.waveform);
1790 			return -EINVAL;
1791 		}
1792 		force = (effect->u.periodic.magnitude * fixp_sin16((effect->direction * 360) >> 16)) >> 15;
1793 		params[6] = effect->u.periodic.magnitude >> 8;
1794 		params[7] = effect->u.periodic.magnitude & 255;
1795 		params[8] = effect->u.periodic.offset >> 8;
1796 		params[9] = effect->u.periodic.offset & 255;
1797 		params[10] = effect->u.periodic.period >> 8;
1798 		params[11] = effect->u.periodic.period & 255;
1799 		params[12] = effect->u.periodic.phase >> 8;
1800 		params[13] = effect->u.periodic.phase & 255;
1801 		params[14] = effect->u.periodic.envelope.attack_level >> 7;
1802 		params[15] = effect->u.periodic.envelope.attack_length >> 8;
1803 		params[16] = effect->u.periodic.envelope.attack_length & 255;
1804 		params[17] = effect->u.periodic.envelope.fade_level >> 7;
1805 		params[18] = effect->u.periodic.envelope.fade_length >> 8;
1806 		params[19] = effect->u.periodic.envelope.fade_length & 255;
1807 		size = 20;
1808 		dbg_hid("Uploading periodic force mag=%d/dir=%d, offset=%d, period=%d ms, phase=%d\n",
1809 				effect->u.periodic.magnitude, effect->direction,
1810 				effect->u.periodic.offset,
1811 				effect->u.periodic.period,
1812 				effect->u.periodic.phase);
1813 		dbg_hid("          envelope attack=(%d, %d ms) fade=(%d, %d ms)\n",
1814 				effect->u.periodic.envelope.attack_level,
1815 				effect->u.periodic.envelope.attack_length,
1816 				effect->u.periodic.envelope.fade_level,
1817 				effect->u.periodic.envelope.fade_length);
1818 		break;
1819 	}
1820 	case FF_RAMP:
1821 		params[1] = HIDPP_FF_EFFECT_RAMP;
1822 		force = (effect->u.ramp.start_level * fixp_sin16((effect->direction * 360) >> 16)) >> 15;
1823 		params[6] = force >> 8;
1824 		params[7] = force & 255;
1825 		force = (effect->u.ramp.end_level * fixp_sin16((effect->direction * 360) >> 16)) >> 15;
1826 		params[8] = force >> 8;
1827 		params[9] = force & 255;
1828 		params[10] = effect->u.ramp.envelope.attack_level >> 7;
1829 		params[11] = effect->u.ramp.envelope.attack_length >> 8;
1830 		params[12] = effect->u.ramp.envelope.attack_length & 255;
1831 		params[13] = effect->u.ramp.envelope.fade_level >> 7;
1832 		params[14] = effect->u.ramp.envelope.fade_length >> 8;
1833 		params[15] = effect->u.ramp.envelope.fade_length & 255;
1834 		size = 16;
1835 		dbg_hid("Uploading ramp force level=%d -> %d in dir %d = %d\n",
1836 				effect->u.ramp.start_level,
1837 				effect->u.ramp.end_level,
1838 				effect->direction, force);
1839 		dbg_hid("          envelope attack=(%d, %d ms) fade=(%d, %d ms)\n",
1840 				effect->u.ramp.envelope.attack_level,
1841 				effect->u.ramp.envelope.attack_length,
1842 				effect->u.ramp.envelope.fade_level,
1843 				effect->u.ramp.envelope.fade_length);
1844 		break;
1845 	case FF_FRICTION:
1846 	case FF_INERTIA:
1847 	case FF_SPRING:
1848 	case FF_DAMPER:
1849 		params[1] = HIDPP_FF_CONDITION_CMDS[effect->type - FF_SPRING];
1850 		params[6] = effect->u.condition[0].left_saturation >> 9;
1851 		params[7] = (effect->u.condition[0].left_saturation >> 1) & 255;
1852 		params[8] = effect->u.condition[0].left_coeff >> 8;
1853 		params[9] = effect->u.condition[0].left_coeff & 255;
1854 		params[10] = effect->u.condition[0].deadband >> 9;
1855 		params[11] = (effect->u.condition[0].deadband >> 1) & 255;
1856 		params[12] = effect->u.condition[0].center >> 8;
1857 		params[13] = effect->u.condition[0].center & 255;
1858 		params[14] = effect->u.condition[0].right_coeff >> 8;
1859 		params[15] = effect->u.condition[0].right_coeff & 255;
1860 		params[16] = effect->u.condition[0].right_saturation >> 9;
1861 		params[17] = (effect->u.condition[0].right_saturation >> 1) & 255;
1862 		size = 18;
1863 		dbg_hid("Uploading %s force left coeff=%d, left sat=%d, right coeff=%d, right sat=%d\n",
1864 				HIDPP_FF_CONDITION_NAMES[effect->type - FF_SPRING],
1865 				effect->u.condition[0].left_coeff,
1866 				effect->u.condition[0].left_saturation,
1867 				effect->u.condition[0].right_coeff,
1868 				effect->u.condition[0].right_saturation);
1869 		dbg_hid("          deadband=%d, center=%d\n",
1870 				effect->u.condition[0].deadband,
1871 				effect->u.condition[0].center);
1872 		break;
1873 	default:
1874 		hid_err(data->hidpp->hid_dev, "Unexpected force type %i!\n", effect->type);
1875 		return -EINVAL;
1876 	}
1877 
1878 	return hidpp_ff_queue_work(data, effect->id, HIDPP_FF_DOWNLOAD_EFFECT, params, size);
1879 }
1880 
1881 static int hidpp_ff_playback(struct input_dev *dev, int effect_id, int value)
1882 {
1883 	struct hidpp_ff_private_data *data = dev->ff->private;
1884 	u8 params[2];
1885 
1886 	params[1] = value ? HIDPP_FF_EFFECT_STATE_PLAY : HIDPP_FF_EFFECT_STATE_STOP;
1887 
1888 	dbg_hid("St%sing playback of effect %d.\n", value?"art":"opp", effect_id);
1889 
1890 	return hidpp_ff_queue_work(data, effect_id, HIDPP_FF_SET_EFFECT_STATE, params, ARRAY_SIZE(params));
1891 }
1892 
1893 static int hidpp_ff_erase_effect(struct input_dev *dev, int effect_id)
1894 {
1895 	struct hidpp_ff_private_data *data = dev->ff->private;
1896 	u8 slot = 0;
1897 
1898 	dbg_hid("Erasing effect %d.\n", effect_id);
1899 
1900 	return hidpp_ff_queue_work(data, effect_id, HIDPP_FF_DESTROY_EFFECT, &slot, 1);
1901 }
1902 
1903 static void hidpp_ff_set_autocenter(struct input_dev *dev, u16 magnitude)
1904 {
1905 	struct hidpp_ff_private_data *data = dev->ff->private;
1906 	u8 params[18];
1907 
1908 	dbg_hid("Setting autocenter to %d.\n", magnitude);
1909 
1910 	/* start a standard spring effect */
1911 	params[1] = HIDPP_FF_EFFECT_SPRING | HIDPP_FF_EFFECT_AUTOSTART;
1912 	/* zero delay and duration */
1913 	params[2] = params[3] = params[4] = params[5] = 0;
1914 	/* set coeff to 25% of saturation */
1915 	params[8] = params[14] = magnitude >> 11;
1916 	params[9] = params[15] = (magnitude >> 3) & 255;
1917 	params[6] = params[16] = magnitude >> 9;
1918 	params[7] = params[17] = (magnitude >> 1) & 255;
1919 	/* zero deadband and center */
1920 	params[10] = params[11] = params[12] = params[13] = 0;
1921 
1922 	hidpp_ff_queue_work(data, HIDPP_FF_EFFECTID_AUTOCENTER, HIDPP_FF_DOWNLOAD_EFFECT, params, ARRAY_SIZE(params));
1923 }
1924 
1925 static void hidpp_ff_set_gain(struct input_dev *dev, u16 gain)
1926 {
1927 	struct hidpp_ff_private_data *data = dev->ff->private;
1928 	u8 params[4];
1929 
1930 	dbg_hid("Setting gain to %d.\n", gain);
1931 
1932 	params[0] = gain >> 8;
1933 	params[1] = gain & 255;
1934 	params[2] = 0; /* no boost */
1935 	params[3] = 0;
1936 
1937 	hidpp_ff_queue_work(data, HIDPP_FF_EFFECTID_NONE, HIDPP_FF_SET_GLOBAL_GAINS, params, ARRAY_SIZE(params));
1938 }
1939 
1940 static ssize_t hidpp_ff_range_show(struct device *dev, struct device_attribute *attr, char *buf)
1941 {
1942 	struct hid_device *hid = to_hid_device(dev);
1943 	struct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list);
1944 	struct input_dev *idev = hidinput->input;
1945 	struct hidpp_ff_private_data *data = idev->ff->private;
1946 
1947 	return scnprintf(buf, PAGE_SIZE, "%u\n", data->range);
1948 }
1949 
1950 static ssize_t hidpp_ff_range_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
1951 {
1952 	struct hid_device *hid = to_hid_device(dev);
1953 	struct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list);
1954 	struct input_dev *idev = hidinput->input;
1955 	struct hidpp_ff_private_data *data = idev->ff->private;
1956 	u8 params[2];
1957 	int range = simple_strtoul(buf, NULL, 10);
1958 
1959 	range = clamp(range, 180, 900);
1960 
1961 	params[0] = range >> 8;
1962 	params[1] = range & 0x00FF;
1963 
1964 	hidpp_ff_queue_work(data, -1, HIDPP_FF_SET_APERTURE, params, ARRAY_SIZE(params));
1965 
1966 	return count;
1967 }
1968 
1969 static DEVICE_ATTR(range, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH, hidpp_ff_range_show, hidpp_ff_range_store);
1970 
1971 static void hidpp_ff_destroy(struct ff_device *ff)
1972 {
1973 	struct hidpp_ff_private_data *data = ff->private;
1974 
1975 	kfree(data->effect_ids);
1976 }
1977 
1978 static int hidpp_ff_init(struct hidpp_device *hidpp, u8 feature_index)
1979 {
1980 	struct hid_device *hid = hidpp->hid_dev;
1981 	struct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list);
1982 	struct input_dev *dev = hidinput->input;
1983 	const struct usb_device_descriptor *udesc = &(hid_to_usb_dev(hid)->descriptor);
1984 	const u16 bcdDevice = le16_to_cpu(udesc->bcdDevice);
1985 	struct ff_device *ff;
1986 	struct hidpp_report response;
1987 	struct hidpp_ff_private_data *data;
1988 	int error, j, num_slots;
1989 	u8 version;
1990 
1991 	if (!dev) {
1992 		hid_err(hid, "Struct input_dev not set!\n");
1993 		return -EINVAL;
1994 	}
1995 
1996 	/* Get firmware release */
1997 	version = bcdDevice & 255;
1998 
1999 	/* Set supported force feedback capabilities */
2000 	for (j = 0; hiddpp_ff_effects[j] >= 0; j++)
2001 		set_bit(hiddpp_ff_effects[j], dev->ffbit);
2002 	if (version > 1)
2003 		for (j = 0; hiddpp_ff_effects_v2[j] >= 0; j++)
2004 			set_bit(hiddpp_ff_effects_v2[j], dev->ffbit);
2005 
2006 	/* Read number of slots available in device */
2007 	error = hidpp_send_fap_command_sync(hidpp, feature_index,
2008 		HIDPP_FF_GET_INFO, NULL, 0, &response);
2009 	if (error) {
2010 		if (error < 0)
2011 			return error;
2012 		hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n",
2013 			__func__, error);
2014 		return -EPROTO;
2015 	}
2016 
2017 	num_slots = response.fap.params[0] - HIDPP_FF_RESERVED_SLOTS;
2018 
2019 	error = input_ff_create(dev, num_slots);
2020 
2021 	if (error) {
2022 		hid_err(dev, "Failed to create FF device!\n");
2023 		return error;
2024 	}
2025 
2026 	data = kzalloc(sizeof(*data), GFP_KERNEL);
2027 	if (!data)
2028 		return -ENOMEM;
2029 	data->effect_ids = kcalloc(num_slots, sizeof(int), GFP_KERNEL);
2030 	if (!data->effect_ids) {
2031 		kfree(data);
2032 		return -ENOMEM;
2033 	}
2034 	data->hidpp = hidpp;
2035 	data->feature_index = feature_index;
2036 	data->version = version;
2037 	data->slot_autocenter = 0;
2038 	data->num_effects = num_slots;
2039 	for (j = 0; j < num_slots; j++)
2040 		data->effect_ids[j] = -1;
2041 
2042 	ff = dev->ff;
2043 	ff->private = data;
2044 
2045 	ff->upload = hidpp_ff_upload_effect;
2046 	ff->erase = hidpp_ff_erase_effect;
2047 	ff->playback = hidpp_ff_playback;
2048 	ff->set_gain = hidpp_ff_set_gain;
2049 	ff->set_autocenter = hidpp_ff_set_autocenter;
2050 	ff->destroy = hidpp_ff_destroy;
2051 
2052 
2053 	/* reset all forces */
2054 	error = hidpp_send_fap_command_sync(hidpp, feature_index,
2055 		HIDPP_FF_RESET_ALL, NULL, 0, &response);
2056 
2057 	/* Read current Range */
2058 	error = hidpp_send_fap_command_sync(hidpp, feature_index,
2059 		HIDPP_FF_GET_APERTURE, NULL, 0, &response);
2060 	if (error)
2061 		hid_warn(hidpp->hid_dev, "Failed to read range from device!\n");
2062 	data->range = error ? 900 : get_unaligned_be16(&response.fap.params[0]);
2063 
2064 	/* Create sysfs interface */
2065 	error = device_create_file(&(hidpp->hid_dev->dev), &dev_attr_range);
2066 	if (error)
2067 		hid_warn(hidpp->hid_dev, "Unable to create sysfs interface for \"range\", errno %d!\n", error);
2068 
2069 	/* Read the current gain values */
2070 	error = hidpp_send_fap_command_sync(hidpp, feature_index,
2071 		HIDPP_FF_GET_GLOBAL_GAINS, NULL, 0, &response);
2072 	if (error)
2073 		hid_warn(hidpp->hid_dev, "Failed to read gain values from device!\n");
2074 	data->gain = error ? 0xffff : get_unaligned_be16(&response.fap.params[0]);
2075 	/* ignore boost value at response.fap.params[2] */
2076 
2077 	/* init the hardware command queue */
2078 	data->wq = create_singlethread_workqueue("hidpp-ff-sendqueue");
2079 	atomic_set(&data->workqueue_size, 0);
2080 
2081 	/* initialize with zero autocenter to get wheel in usable state */
2082 	hidpp_ff_set_autocenter(dev, 0);
2083 
2084 	hid_info(hid, "Force feedback support loaded (firmware release %d).\n",
2085 		 version);
2086 
2087 	return 0;
2088 }
2089 
2090 static int hidpp_ff_deinit(struct hid_device *hid)
2091 {
2092 	struct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list);
2093 	struct input_dev *dev = hidinput->input;
2094 	struct hidpp_ff_private_data *data;
2095 
2096 	if (!dev) {
2097 		hid_err(hid, "Struct input_dev not found!\n");
2098 		return -EINVAL;
2099 	}
2100 
2101 	hid_info(hid, "Unloading HID++ force feedback.\n");
2102 	data = dev->ff->private;
2103 	if (!data) {
2104 		hid_err(hid, "Private data not found!\n");
2105 		return -EINVAL;
2106 	}
2107 
2108 	destroy_workqueue(data->wq);
2109 	device_remove_file(&hid->dev, &dev_attr_range);
2110 
2111 	return 0;
2112 }
2113 
2114 
2115 /* ************************************************************************** */
2116 /*                                                                            */
2117 /* Device Support                                                             */
2118 /*                                                                            */
2119 /* ************************************************************************** */
2120 
2121 /* -------------------------------------------------------------------------- */
2122 /* Touchpad HID++ devices                                                     */
2123 /* -------------------------------------------------------------------------- */
2124 
2125 #define WTP_MANUAL_RESOLUTION				39
2126 
2127 struct wtp_data {
2128 	struct input_dev *input;
2129 	u16 x_size, y_size;
2130 	u8 finger_count;
2131 	u8 mt_feature_index;
2132 	u8 button_feature_index;
2133 	u8 maxcontacts;
2134 	bool flip_y;
2135 	unsigned int resolution;
2136 };
2137 
2138 static int wtp_input_mapping(struct hid_device *hdev, struct hid_input *hi,
2139 		struct hid_field *field, struct hid_usage *usage,
2140 		unsigned long **bit, int *max)
2141 {
2142 	return -1;
2143 }
2144 
2145 static void wtp_populate_input(struct hidpp_device *hidpp,
2146 		struct input_dev *input_dev, bool origin_is_hid_core)
2147 {
2148 	struct wtp_data *wd = hidpp->private_data;
2149 
2150 	__set_bit(EV_ABS, input_dev->evbit);
2151 	__set_bit(EV_KEY, input_dev->evbit);
2152 	__clear_bit(EV_REL, input_dev->evbit);
2153 	__clear_bit(EV_LED, input_dev->evbit);
2154 
2155 	input_set_abs_params(input_dev, ABS_MT_POSITION_X, 0, wd->x_size, 0, 0);
2156 	input_abs_set_res(input_dev, ABS_MT_POSITION_X, wd->resolution);
2157 	input_set_abs_params(input_dev, ABS_MT_POSITION_Y, 0, wd->y_size, 0, 0);
2158 	input_abs_set_res(input_dev, ABS_MT_POSITION_Y, wd->resolution);
2159 
2160 	/* Max pressure is not given by the devices, pick one */
2161 	input_set_abs_params(input_dev, ABS_MT_PRESSURE, 0, 50, 0, 0);
2162 
2163 	input_set_capability(input_dev, EV_KEY, BTN_LEFT);
2164 
2165 	if (hidpp->quirks & HIDPP_QUIRK_WTP_PHYSICAL_BUTTONS)
2166 		input_set_capability(input_dev, EV_KEY, BTN_RIGHT);
2167 	else
2168 		__set_bit(INPUT_PROP_BUTTONPAD, input_dev->propbit);
2169 
2170 	input_mt_init_slots(input_dev, wd->maxcontacts, INPUT_MT_POINTER |
2171 		INPUT_MT_DROP_UNUSED);
2172 
2173 	wd->input = input_dev;
2174 }
2175 
2176 static void wtp_touch_event(struct wtp_data *wd,
2177 	struct hidpp_touchpad_raw_xy_finger *touch_report)
2178 {
2179 	int slot;
2180 
2181 	if (!touch_report->finger_id || touch_report->contact_type)
2182 		/* no actual data */
2183 		return;
2184 
2185 	slot = input_mt_get_slot_by_key(wd->input, touch_report->finger_id);
2186 
2187 	input_mt_slot(wd->input, slot);
2188 	input_mt_report_slot_state(wd->input, MT_TOOL_FINGER,
2189 					touch_report->contact_status);
2190 	if (touch_report->contact_status) {
2191 		input_event(wd->input, EV_ABS, ABS_MT_POSITION_X,
2192 				touch_report->x);
2193 		input_event(wd->input, EV_ABS, ABS_MT_POSITION_Y,
2194 				wd->flip_y ? wd->y_size - touch_report->y :
2195 					     touch_report->y);
2196 		input_event(wd->input, EV_ABS, ABS_MT_PRESSURE,
2197 				touch_report->area);
2198 	}
2199 }
2200 
2201 static void wtp_send_raw_xy_event(struct hidpp_device *hidpp,
2202 		struct hidpp_touchpad_raw_xy *raw)
2203 {
2204 	struct wtp_data *wd = hidpp->private_data;
2205 	int i;
2206 
2207 	for (i = 0; i < 2; i++)
2208 		wtp_touch_event(wd, &(raw->fingers[i]));
2209 
2210 	if (raw->end_of_frame &&
2211 	    !(hidpp->quirks & HIDPP_QUIRK_WTP_PHYSICAL_BUTTONS))
2212 		input_event(wd->input, EV_KEY, BTN_LEFT, raw->button);
2213 
2214 	if (raw->end_of_frame || raw->finger_count <= 2) {
2215 		input_mt_sync_frame(wd->input);
2216 		input_sync(wd->input);
2217 	}
2218 }
2219 
2220 static int wtp_mouse_raw_xy_event(struct hidpp_device *hidpp, u8 *data)
2221 {
2222 	struct wtp_data *wd = hidpp->private_data;
2223 	u8 c1_area = ((data[7] & 0xf) * (data[7] & 0xf) +
2224 		      (data[7] >> 4) * (data[7] >> 4)) / 2;
2225 	u8 c2_area = ((data[13] & 0xf) * (data[13] & 0xf) +
2226 		      (data[13] >> 4) * (data[13] >> 4)) / 2;
2227 	struct hidpp_touchpad_raw_xy raw = {
2228 		.timestamp = data[1],
2229 		.fingers = {
2230 			{
2231 				.contact_type = 0,
2232 				.contact_status = !!data[7],
2233 				.x = get_unaligned_le16(&data[3]),
2234 				.y = get_unaligned_le16(&data[5]),
2235 				.z = c1_area,
2236 				.area = c1_area,
2237 				.finger_id = data[2],
2238 			}, {
2239 				.contact_type = 0,
2240 				.contact_status = !!data[13],
2241 				.x = get_unaligned_le16(&data[9]),
2242 				.y = get_unaligned_le16(&data[11]),
2243 				.z = c2_area,
2244 				.area = c2_area,
2245 				.finger_id = data[8],
2246 			}
2247 		},
2248 		.finger_count = wd->maxcontacts,
2249 		.spurious_flag = 0,
2250 		.end_of_frame = (data[0] >> 7) == 0,
2251 		.button = data[0] & 0x01,
2252 	};
2253 
2254 	wtp_send_raw_xy_event(hidpp, &raw);
2255 
2256 	return 1;
2257 }
2258 
2259 static int wtp_raw_event(struct hid_device *hdev, u8 *data, int size)
2260 {
2261 	struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2262 	struct wtp_data *wd = hidpp->private_data;
2263 	struct hidpp_report *report = (struct hidpp_report *)data;
2264 	struct hidpp_touchpad_raw_xy raw;
2265 
2266 	if (!wd || !wd->input)
2267 		return 1;
2268 
2269 	switch (data[0]) {
2270 	case 0x02:
2271 		if (size < 2) {
2272 			hid_err(hdev, "Received HID report of bad size (%d)",
2273 				size);
2274 			return 1;
2275 		}
2276 		if (hidpp->quirks & HIDPP_QUIRK_WTP_PHYSICAL_BUTTONS) {
2277 			input_event(wd->input, EV_KEY, BTN_LEFT,
2278 					!!(data[1] & 0x01));
2279 			input_event(wd->input, EV_KEY, BTN_RIGHT,
2280 					!!(data[1] & 0x02));
2281 			input_sync(wd->input);
2282 			return 0;
2283 		} else {
2284 			if (size < 21)
2285 				return 1;
2286 			return wtp_mouse_raw_xy_event(hidpp, &data[7]);
2287 		}
2288 	case REPORT_ID_HIDPP_LONG:
2289 		/* size is already checked in hidpp_raw_event. */
2290 		if ((report->fap.feature_index != wd->mt_feature_index) ||
2291 		    (report->fap.funcindex_clientid != EVENT_TOUCHPAD_RAW_XY))
2292 			return 1;
2293 		hidpp_touchpad_raw_xy_event(hidpp, data + 4, &raw);
2294 
2295 		wtp_send_raw_xy_event(hidpp, &raw);
2296 		return 0;
2297 	}
2298 
2299 	return 0;
2300 }
2301 
2302 static int wtp_get_config(struct hidpp_device *hidpp)
2303 {
2304 	struct wtp_data *wd = hidpp->private_data;
2305 	struct hidpp_touchpad_raw_info raw_info = {0};
2306 	u8 feature_type;
2307 	int ret;
2308 
2309 	ret = hidpp_root_get_feature(hidpp, HIDPP_PAGE_TOUCHPAD_RAW_XY,
2310 		&wd->mt_feature_index, &feature_type);
2311 	if (ret)
2312 		/* means that the device is not powered up */
2313 		return ret;
2314 
2315 	ret = hidpp_touchpad_get_raw_info(hidpp, wd->mt_feature_index,
2316 		&raw_info);
2317 	if (ret)
2318 		return ret;
2319 
2320 	wd->x_size = raw_info.x_size;
2321 	wd->y_size = raw_info.y_size;
2322 	wd->maxcontacts = raw_info.maxcontacts;
2323 	wd->flip_y = raw_info.origin == TOUCHPAD_RAW_XY_ORIGIN_LOWER_LEFT;
2324 	wd->resolution = raw_info.res;
2325 	if (!wd->resolution)
2326 		wd->resolution = WTP_MANUAL_RESOLUTION;
2327 
2328 	return 0;
2329 }
2330 
2331 static int wtp_allocate(struct hid_device *hdev, const struct hid_device_id *id)
2332 {
2333 	struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2334 	struct wtp_data *wd;
2335 
2336 	wd = devm_kzalloc(&hdev->dev, sizeof(struct wtp_data),
2337 			GFP_KERNEL);
2338 	if (!wd)
2339 		return -ENOMEM;
2340 
2341 	hidpp->private_data = wd;
2342 
2343 	return 0;
2344 };
2345 
2346 static int wtp_connect(struct hid_device *hdev, bool connected)
2347 {
2348 	struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2349 	struct wtp_data *wd = hidpp->private_data;
2350 	int ret;
2351 
2352 	if (!wd->x_size) {
2353 		ret = wtp_get_config(hidpp);
2354 		if (ret) {
2355 			hid_err(hdev, "Can not get wtp config: %d\n", ret);
2356 			return ret;
2357 		}
2358 	}
2359 
2360 	return hidpp_touchpad_set_raw_report_state(hidpp, wd->mt_feature_index,
2361 			true, true);
2362 }
2363 
2364 /* ------------------------------------------------------------------------- */
2365 /* Logitech M560 devices                                                     */
2366 /* ------------------------------------------------------------------------- */
2367 
2368 /*
2369  * Logitech M560 protocol overview
2370  *
2371  * The Logitech M560 mouse, is designed for windows 8. When the middle and/or
2372  * the sides buttons are pressed, it sends some keyboard keys events
2373  * instead of buttons ones.
2374  * To complicate things further, the middle button keys sequence
2375  * is different from the odd press and the even press.
2376  *
2377  * forward button -> Super_R
2378  * backward button -> Super_L+'d' (press only)
2379  * middle button -> 1st time: Alt_L+SuperL+XF86TouchpadOff (press only)
2380  *                  2nd time: left-click (press only)
2381  * NB: press-only means that when the button is pressed, the
2382  * KeyPress/ButtonPress and KeyRelease/ButtonRelease events are generated
2383  * together sequentially; instead when the button is released, no event is
2384  * generated !
2385  *
2386  * With the command
2387  *	10<xx>0a 3500af03 (where <xx> is the mouse id),
2388  * the mouse reacts differently:
2389  * - it never sends a keyboard key event
2390  * - for the three mouse button it sends:
2391  *	middle button               press   11<xx>0a 3500af00...
2392  *	side 1 button (forward)     press   11<xx>0a 3500b000...
2393  *	side 2 button (backward)    press   11<xx>0a 3500ae00...
2394  *	middle/side1/side2 button   release 11<xx>0a 35000000...
2395  */
2396 
2397 static const u8 m560_config_parameter[] = {0x00, 0xaf, 0x03};
2398 
2399 struct m560_private_data {
2400 	struct input_dev *input;
2401 };
2402 
2403 /* how buttons are mapped in the report */
2404 #define M560_MOUSE_BTN_LEFT		0x01
2405 #define M560_MOUSE_BTN_RIGHT		0x02
2406 #define M560_MOUSE_BTN_WHEEL_LEFT	0x08
2407 #define M560_MOUSE_BTN_WHEEL_RIGHT	0x10
2408 
2409 #define M560_SUB_ID			0x0a
2410 #define M560_BUTTON_MODE_REGISTER	0x35
2411 
2412 static int m560_send_config_command(struct hid_device *hdev, bool connected)
2413 {
2414 	struct hidpp_report response;
2415 	struct hidpp_device *hidpp_dev;
2416 
2417 	hidpp_dev = hid_get_drvdata(hdev);
2418 
2419 	return hidpp_send_rap_command_sync(
2420 		hidpp_dev,
2421 		REPORT_ID_HIDPP_SHORT,
2422 		M560_SUB_ID,
2423 		M560_BUTTON_MODE_REGISTER,
2424 		(u8 *)m560_config_parameter,
2425 		sizeof(m560_config_parameter),
2426 		&response
2427 	);
2428 }
2429 
2430 static int m560_allocate(struct hid_device *hdev)
2431 {
2432 	struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2433 	struct m560_private_data *d;
2434 
2435 	d = devm_kzalloc(&hdev->dev, sizeof(struct m560_private_data),
2436 			GFP_KERNEL);
2437 	if (!d)
2438 		return -ENOMEM;
2439 
2440 	hidpp->private_data = d;
2441 
2442 	return 0;
2443 };
2444 
2445 static int m560_raw_event(struct hid_device *hdev, u8 *data, int size)
2446 {
2447 	struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2448 	struct m560_private_data *mydata = hidpp->private_data;
2449 
2450 	/* sanity check */
2451 	if (!mydata || !mydata->input) {
2452 		hid_err(hdev, "error in parameter\n");
2453 		return -EINVAL;
2454 	}
2455 
2456 	if (size < 7) {
2457 		hid_err(hdev, "error in report\n");
2458 		return 0;
2459 	}
2460 
2461 	if (data[0] == REPORT_ID_HIDPP_LONG &&
2462 	    data[2] == M560_SUB_ID && data[6] == 0x00) {
2463 		/*
2464 		 * m560 mouse report for middle, forward and backward button
2465 		 *
2466 		 * data[0] = 0x11
2467 		 * data[1] = device-id
2468 		 * data[2] = 0x0a
2469 		 * data[5] = 0xaf -> middle
2470 		 *	     0xb0 -> forward
2471 		 *	     0xae -> backward
2472 		 *	     0x00 -> release all
2473 		 * data[6] = 0x00
2474 		 */
2475 
2476 		switch (data[5]) {
2477 		case 0xaf:
2478 			input_report_key(mydata->input, BTN_MIDDLE, 1);
2479 			break;
2480 		case 0xb0:
2481 			input_report_key(mydata->input, BTN_FORWARD, 1);
2482 			break;
2483 		case 0xae:
2484 			input_report_key(mydata->input, BTN_BACK, 1);
2485 			break;
2486 		case 0x00:
2487 			input_report_key(mydata->input, BTN_BACK, 0);
2488 			input_report_key(mydata->input, BTN_FORWARD, 0);
2489 			input_report_key(mydata->input, BTN_MIDDLE, 0);
2490 			break;
2491 		default:
2492 			hid_err(hdev, "error in report\n");
2493 			return 0;
2494 		}
2495 		input_sync(mydata->input);
2496 
2497 	} else if (data[0] == 0x02) {
2498 		/*
2499 		 * Logitech M560 mouse report
2500 		 *
2501 		 * data[0] = type (0x02)
2502 		 * data[1..2] = buttons
2503 		 * data[3..5] = xy
2504 		 * data[6] = wheel
2505 		 */
2506 
2507 		int v;
2508 
2509 		input_report_key(mydata->input, BTN_LEFT,
2510 			!!(data[1] & M560_MOUSE_BTN_LEFT));
2511 		input_report_key(mydata->input, BTN_RIGHT,
2512 			!!(data[1] & M560_MOUSE_BTN_RIGHT));
2513 
2514 		if (data[1] & M560_MOUSE_BTN_WHEEL_LEFT)
2515 			input_report_rel(mydata->input, REL_HWHEEL, -1);
2516 		else if (data[1] & M560_MOUSE_BTN_WHEEL_RIGHT)
2517 			input_report_rel(mydata->input, REL_HWHEEL, 1);
2518 
2519 		v = hid_snto32(hid_field_extract(hdev, data+3, 0, 12), 12);
2520 		input_report_rel(mydata->input, REL_X, v);
2521 
2522 		v = hid_snto32(hid_field_extract(hdev, data+3, 12, 12), 12);
2523 		input_report_rel(mydata->input, REL_Y, v);
2524 
2525 		v = hid_snto32(data[6], 8);
2526 		hid_scroll_counter_handle_scroll(
2527 				&hidpp->vertical_wheel_counter, v);
2528 
2529 		input_sync(mydata->input);
2530 	}
2531 
2532 	return 1;
2533 }
2534 
2535 static void m560_populate_input(struct hidpp_device *hidpp,
2536 		struct input_dev *input_dev, bool origin_is_hid_core)
2537 {
2538 	struct m560_private_data *mydata = hidpp->private_data;
2539 
2540 	mydata->input = input_dev;
2541 
2542 	__set_bit(EV_KEY, mydata->input->evbit);
2543 	__set_bit(BTN_MIDDLE, mydata->input->keybit);
2544 	__set_bit(BTN_RIGHT, mydata->input->keybit);
2545 	__set_bit(BTN_LEFT, mydata->input->keybit);
2546 	__set_bit(BTN_BACK, mydata->input->keybit);
2547 	__set_bit(BTN_FORWARD, mydata->input->keybit);
2548 
2549 	__set_bit(EV_REL, mydata->input->evbit);
2550 	__set_bit(REL_X, mydata->input->relbit);
2551 	__set_bit(REL_Y, mydata->input->relbit);
2552 	__set_bit(REL_WHEEL, mydata->input->relbit);
2553 	__set_bit(REL_HWHEEL, mydata->input->relbit);
2554 }
2555 
2556 static int m560_input_mapping(struct hid_device *hdev, struct hid_input *hi,
2557 		struct hid_field *field, struct hid_usage *usage,
2558 		unsigned long **bit, int *max)
2559 {
2560 	return -1;
2561 }
2562 
2563 /* ------------------------------------------------------------------------- */
2564 /* Logitech K400 devices                                                     */
2565 /* ------------------------------------------------------------------------- */
2566 
2567 /*
2568  * The Logitech K400 keyboard has an embedded touchpad which is seen
2569  * as a mouse from the OS point of view. There is a hardware shortcut to disable
2570  * tap-to-click but the setting is not remembered accross reset, annoying some
2571  * users.
2572  *
2573  * We can toggle this feature from the host by using the feature 0x6010:
2574  * Touchpad FW items
2575  */
2576 
2577 struct k400_private_data {
2578 	u8 feature_index;
2579 };
2580 
2581 static int k400_disable_tap_to_click(struct hidpp_device *hidpp)
2582 {
2583 	struct k400_private_data *k400 = hidpp->private_data;
2584 	struct hidpp_touchpad_fw_items items = {};
2585 	int ret;
2586 	u8 feature_type;
2587 
2588 	if (!k400->feature_index) {
2589 		ret = hidpp_root_get_feature(hidpp,
2590 			HIDPP_PAGE_TOUCHPAD_FW_ITEMS,
2591 			&k400->feature_index, &feature_type);
2592 		if (ret)
2593 			/* means that the device is not powered up */
2594 			return ret;
2595 	}
2596 
2597 	ret = hidpp_touchpad_fw_items_set(hidpp, k400->feature_index, &items);
2598 	if (ret)
2599 		return ret;
2600 
2601 	return 0;
2602 }
2603 
2604 static int k400_allocate(struct hid_device *hdev)
2605 {
2606 	struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2607 	struct k400_private_data *k400;
2608 
2609 	k400 = devm_kzalloc(&hdev->dev, sizeof(struct k400_private_data),
2610 			    GFP_KERNEL);
2611 	if (!k400)
2612 		return -ENOMEM;
2613 
2614 	hidpp->private_data = k400;
2615 
2616 	return 0;
2617 };
2618 
2619 static int k400_connect(struct hid_device *hdev, bool connected)
2620 {
2621 	struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2622 
2623 	if (!disable_tap_to_click)
2624 		return 0;
2625 
2626 	return k400_disable_tap_to_click(hidpp);
2627 }
2628 
2629 /* ------------------------------------------------------------------------- */
2630 /* Logitech G920 Driving Force Racing Wheel for Xbox One                     */
2631 /* ------------------------------------------------------------------------- */
2632 
2633 #define HIDPP_PAGE_G920_FORCE_FEEDBACK			0x8123
2634 
2635 static int g920_get_config(struct hidpp_device *hidpp)
2636 {
2637 	u8 feature_type;
2638 	u8 feature_index;
2639 	int ret;
2640 
2641 	/* Find feature and store for later use */
2642 	ret = hidpp_root_get_feature(hidpp, HIDPP_PAGE_G920_FORCE_FEEDBACK,
2643 		&feature_index, &feature_type);
2644 	if (ret)
2645 		return ret;
2646 
2647 	ret = hidpp_ff_init(hidpp, feature_index);
2648 	if (ret)
2649 		hid_warn(hidpp->hid_dev, "Unable to initialize force feedback support, errno %d\n",
2650 				ret);
2651 
2652 	return 0;
2653 }
2654 
2655 /* -------------------------------------------------------------------------- */
2656 /* High-resolution scroll wheels                                              */
2657 /* -------------------------------------------------------------------------- */
2658 
2659 /**
2660  * struct hi_res_scroll_info - Stores info on a device's high-res scroll wheel.
2661  * @product_id: the HID product ID of the device being described.
2662  * @microns_per_hi_res_unit: the distance moved by the user's finger for each
2663  *                         high-resolution unit reported by the device, in
2664  *                         256ths of a millimetre.
2665  */
2666 struct hi_res_scroll_info {
2667 	__u32 product_id;
2668 	int microns_per_hi_res_unit;
2669 };
2670 
2671 static struct hi_res_scroll_info hi_res_scroll_devices[] = {
2672 	{ /* Anywhere MX */
2673 	  .product_id = 0x1017, .microns_per_hi_res_unit = 445 },
2674 	{ /* Performance MX */
2675 	  .product_id = 0x101a, .microns_per_hi_res_unit = 406 },
2676 	{ /* M560 */
2677 	  .product_id = 0x402d, .microns_per_hi_res_unit = 435 },
2678 	{ /* MX Master 2S */
2679 	  .product_id = 0x4069, .microns_per_hi_res_unit = 406 },
2680 };
2681 
2682 static int hi_res_scroll_look_up_microns(__u32 product_id)
2683 {
2684 	int i;
2685 	int num_devices = sizeof(hi_res_scroll_devices)
2686 			  / sizeof(hi_res_scroll_devices[0]);
2687 	for (i = 0; i < num_devices; i++) {
2688 		if (hi_res_scroll_devices[i].product_id == product_id)
2689 			return hi_res_scroll_devices[i].microns_per_hi_res_unit;
2690 	}
2691 	/* We don't have a value for this device, so use a sensible default. */
2692 	return 406;
2693 }
2694 
2695 static int hi_res_scroll_enable(struct hidpp_device *hidpp)
2696 {
2697 	int ret;
2698 	u8 multiplier = 8;
2699 
2700 	if (hidpp->quirks & HIDPP_QUIRK_HI_RES_SCROLL_X2121) {
2701 		ret = hidpp_hrw_set_wheel_mode(hidpp, false, true, false);
2702 		hidpp_hrw_get_wheel_capability(hidpp, &multiplier);
2703 	} else if (hidpp->quirks & HIDPP_QUIRK_HI_RES_SCROLL_X2120) {
2704 		ret = hidpp_hrs_set_highres_scrolling_mode(hidpp, true,
2705 							   &multiplier);
2706 	} else /* if (hidpp->quirks & HIDPP_QUIRK_HI_RES_SCROLL_1P0) */
2707 		ret = hidpp10_enable_scrolling_acceleration(hidpp);
2708 
2709 	if (ret)
2710 		return ret;
2711 
2712 	hidpp->vertical_wheel_counter.resolution_multiplier = multiplier;
2713 	hidpp->vertical_wheel_counter.microns_per_hi_res_unit =
2714 		hi_res_scroll_look_up_microns(hidpp->hid_dev->product);
2715 	hid_info(hidpp->hid_dev, "multiplier = %d, microns = %d\n",
2716 		 multiplier,
2717 		 hidpp->vertical_wheel_counter.microns_per_hi_res_unit);
2718 	return 0;
2719 }
2720 
2721 /* -------------------------------------------------------------------------- */
2722 /* Generic HID++ devices                                                      */
2723 /* -------------------------------------------------------------------------- */
2724 
2725 static int hidpp_input_mapping(struct hid_device *hdev, struct hid_input *hi,
2726 		struct hid_field *field, struct hid_usage *usage,
2727 		unsigned long **bit, int *max)
2728 {
2729 	struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2730 
2731 	if (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP)
2732 		return wtp_input_mapping(hdev, hi, field, usage, bit, max);
2733 	else if (hidpp->quirks & HIDPP_QUIRK_CLASS_M560 &&
2734 			field->application != HID_GD_MOUSE)
2735 		return m560_input_mapping(hdev, hi, field, usage, bit, max);
2736 
2737 	return 0;
2738 }
2739 
2740 static int hidpp_input_mapped(struct hid_device *hdev, struct hid_input *hi,
2741 		struct hid_field *field, struct hid_usage *usage,
2742 		unsigned long **bit, int *max)
2743 {
2744 	struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2745 
2746 	/* Ensure that Logitech G920 is not given a default fuzz/flat value */
2747 	if (hidpp->quirks & HIDPP_QUIRK_CLASS_G920) {
2748 		if (usage->type == EV_ABS && (usage->code == ABS_X ||
2749 				usage->code == ABS_Y || usage->code == ABS_Z ||
2750 				usage->code == ABS_RZ)) {
2751 			field->application = HID_GD_MULTIAXIS;
2752 		}
2753 	}
2754 
2755 	return 0;
2756 }
2757 
2758 
2759 static void hidpp_populate_input(struct hidpp_device *hidpp,
2760 		struct input_dev *input, bool origin_is_hid_core)
2761 {
2762 	if (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP)
2763 		wtp_populate_input(hidpp, input, origin_is_hid_core);
2764 	else if (hidpp->quirks & HIDPP_QUIRK_CLASS_M560)
2765 		m560_populate_input(hidpp, input, origin_is_hid_core);
2766 
2767 	if (hidpp->quirks & HIDPP_QUIRK_HI_RES_SCROLL) {
2768 		input_set_capability(input, EV_REL, REL_WHEEL_HI_RES);
2769 		hidpp->vertical_wheel_counter.dev = input;
2770 	}
2771 }
2772 
2773 static int hidpp_input_configured(struct hid_device *hdev,
2774 				struct hid_input *hidinput)
2775 {
2776 	struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2777 	struct input_dev *input = hidinput->input;
2778 
2779 	hidpp_populate_input(hidpp, input, true);
2780 
2781 	return 0;
2782 }
2783 
2784 static int hidpp_raw_hidpp_event(struct hidpp_device *hidpp, u8 *data,
2785 		int size)
2786 {
2787 	struct hidpp_report *question = hidpp->send_receive_buf;
2788 	struct hidpp_report *answer = hidpp->send_receive_buf;
2789 	struct hidpp_report *report = (struct hidpp_report *)data;
2790 	int ret;
2791 
2792 	/*
2793 	 * If the mutex is locked then we have a pending answer from a
2794 	 * previously sent command.
2795 	 */
2796 	if (unlikely(mutex_is_locked(&hidpp->send_mutex))) {
2797 		/*
2798 		 * Check for a correct hidpp20 answer or the corresponding
2799 		 * error
2800 		 */
2801 		if (hidpp_match_answer(question, report) ||
2802 				hidpp_match_error(question, report)) {
2803 			*answer = *report;
2804 			hidpp->answer_available = true;
2805 			wake_up(&hidpp->wait);
2806 			/*
2807 			 * This was an answer to a command that this driver sent
2808 			 * We return 1 to hid-core to avoid forwarding the
2809 			 * command upstream as it has been treated by the driver
2810 			 */
2811 
2812 			return 1;
2813 		}
2814 	}
2815 
2816 	if (unlikely(hidpp_report_is_connect_event(report))) {
2817 		atomic_set(&hidpp->connected,
2818 				!(report->rap.params[0] & (1 << 6)));
2819 		if (schedule_work(&hidpp->work) == 0)
2820 			dbg_hid("%s: connect event already queued\n", __func__);
2821 		return 1;
2822 	}
2823 
2824 	if (hidpp->capabilities & HIDPP_CAPABILITY_HIDPP20_BATTERY) {
2825 		ret = hidpp20_battery_event(hidpp, data, size);
2826 		if (ret != 0)
2827 			return ret;
2828 		ret = hidpp_solar_battery_event(hidpp, data, size);
2829 		if (ret != 0)
2830 			return ret;
2831 	}
2832 
2833 	if (hidpp->capabilities & HIDPP_CAPABILITY_HIDPP10_BATTERY) {
2834 		ret = hidpp10_battery_event(hidpp, data, size);
2835 		if (ret != 0)
2836 			return ret;
2837 	}
2838 
2839 	return 0;
2840 }
2841 
2842 static int hidpp_raw_event(struct hid_device *hdev, struct hid_report *report,
2843 		u8 *data, int size)
2844 {
2845 	struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2846 	int ret = 0;
2847 
2848 	/* Generic HID++ processing. */
2849 	switch (data[0]) {
2850 	case REPORT_ID_HIDPP_VERY_LONG:
2851 		if (size != HIDPP_REPORT_VERY_LONG_LENGTH) {
2852 			hid_err(hdev, "received hid++ report of bad size (%d)",
2853 				size);
2854 			return 1;
2855 		}
2856 		ret = hidpp_raw_hidpp_event(hidpp, data, size);
2857 		break;
2858 	case REPORT_ID_HIDPP_LONG:
2859 		if (size != HIDPP_REPORT_LONG_LENGTH) {
2860 			hid_err(hdev, "received hid++ report of bad size (%d)",
2861 				size);
2862 			return 1;
2863 		}
2864 		ret = hidpp_raw_hidpp_event(hidpp, data, size);
2865 		break;
2866 	case REPORT_ID_HIDPP_SHORT:
2867 		if (size != HIDPP_REPORT_SHORT_LENGTH) {
2868 			hid_err(hdev, "received hid++ report of bad size (%d)",
2869 				size);
2870 			return 1;
2871 		}
2872 		ret = hidpp_raw_hidpp_event(hidpp, data, size);
2873 		break;
2874 	}
2875 
2876 	/* If no report is available for further processing, skip calling
2877 	 * raw_event of subclasses. */
2878 	if (ret != 0)
2879 		return ret;
2880 
2881 	if (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP)
2882 		return wtp_raw_event(hdev, data, size);
2883 	else if (hidpp->quirks & HIDPP_QUIRK_CLASS_M560)
2884 		return m560_raw_event(hdev, data, size);
2885 
2886 	return 0;
2887 }
2888 
2889 static int hidpp_event(struct hid_device *hdev, struct hid_field *field,
2890 	struct hid_usage *usage, __s32 value)
2891 {
2892 	/* This function will only be called for scroll events, due to the
2893 	 * restriction imposed in hidpp_usages.
2894 	 */
2895 	struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2896 	struct hid_scroll_counter *counter = &hidpp->vertical_wheel_counter;
2897 	/* A scroll event may occur before the multiplier has been retrieved or
2898 	 * the input device set, or high-res scroll enabling may fail. In such
2899 	 * cases we must return early (falling back to default behaviour) to
2900 	 * avoid a crash in hid_scroll_counter_handle_scroll.
2901 	 */
2902 	if (!(hidpp->quirks & HIDPP_QUIRK_HI_RES_SCROLL) || value == 0
2903 	    || counter->dev == NULL || counter->resolution_multiplier == 0)
2904 		return 0;
2905 
2906 	hid_scroll_counter_handle_scroll(counter, value);
2907 	return 1;
2908 }
2909 
2910 static int hidpp_initialize_battery(struct hidpp_device *hidpp)
2911 {
2912 	static atomic_t battery_no = ATOMIC_INIT(0);
2913 	struct power_supply_config cfg = { .drv_data = hidpp };
2914 	struct power_supply_desc *desc = &hidpp->battery.desc;
2915 	enum power_supply_property *battery_props;
2916 	struct hidpp_battery *battery;
2917 	unsigned int num_battery_props;
2918 	unsigned long n;
2919 	int ret;
2920 
2921 	if (hidpp->battery.ps)
2922 		return 0;
2923 
2924 	hidpp->battery.feature_index = 0xff;
2925 	hidpp->battery.solar_feature_index = 0xff;
2926 
2927 	if (hidpp->protocol_major >= 2) {
2928 		if (hidpp->quirks & HIDPP_QUIRK_CLASS_K750)
2929 			ret = hidpp_solar_request_battery_event(hidpp);
2930 		else
2931 			ret = hidpp20_query_battery_info(hidpp);
2932 
2933 		if (ret)
2934 			return ret;
2935 		hidpp->capabilities |= HIDPP_CAPABILITY_HIDPP20_BATTERY;
2936 	} else {
2937 		ret = hidpp10_query_battery_status(hidpp);
2938 		if (ret) {
2939 			ret = hidpp10_query_battery_mileage(hidpp);
2940 			if (ret)
2941 				return -ENOENT;
2942 			hidpp->capabilities |= HIDPP_CAPABILITY_BATTERY_MILEAGE;
2943 		} else {
2944 			hidpp->capabilities |= HIDPP_CAPABILITY_BATTERY_LEVEL_STATUS;
2945 		}
2946 		hidpp->capabilities |= HIDPP_CAPABILITY_HIDPP10_BATTERY;
2947 	}
2948 
2949 	battery_props = devm_kmemdup(&hidpp->hid_dev->dev,
2950 				     hidpp_battery_props,
2951 				     sizeof(hidpp_battery_props),
2952 				     GFP_KERNEL);
2953 	if (!battery_props)
2954 		return -ENOMEM;
2955 
2956 	num_battery_props = ARRAY_SIZE(hidpp_battery_props) - 2;
2957 
2958 	if (hidpp->capabilities & HIDPP_CAPABILITY_BATTERY_MILEAGE)
2959 		battery_props[num_battery_props++] =
2960 				POWER_SUPPLY_PROP_CAPACITY;
2961 
2962 	if (hidpp->capabilities & HIDPP_CAPABILITY_BATTERY_LEVEL_STATUS)
2963 		battery_props[num_battery_props++] =
2964 				POWER_SUPPLY_PROP_CAPACITY_LEVEL;
2965 
2966 	battery = &hidpp->battery;
2967 
2968 	n = atomic_inc_return(&battery_no) - 1;
2969 	desc->properties = battery_props;
2970 	desc->num_properties = num_battery_props;
2971 	desc->get_property = hidpp_battery_get_property;
2972 	sprintf(battery->name, "hidpp_battery_%ld", n);
2973 	desc->name = battery->name;
2974 	desc->type = POWER_SUPPLY_TYPE_BATTERY;
2975 	desc->use_for_apm = 0;
2976 
2977 	battery->ps = devm_power_supply_register(&hidpp->hid_dev->dev,
2978 						 &battery->desc,
2979 						 &cfg);
2980 	if (IS_ERR(battery->ps))
2981 		return PTR_ERR(battery->ps);
2982 
2983 	power_supply_powers(battery->ps, &hidpp->hid_dev->dev);
2984 
2985 	return ret;
2986 }
2987 
2988 static void hidpp_overwrite_name(struct hid_device *hdev)
2989 {
2990 	struct hidpp_device *hidpp = hid_get_drvdata(hdev);
2991 	char *name;
2992 
2993 	if (hidpp->protocol_major < 2)
2994 		return;
2995 
2996 	name = hidpp_get_device_name(hidpp);
2997 
2998 	if (!name) {
2999 		hid_err(hdev, "unable to retrieve the name of the device");
3000 	} else {
3001 		dbg_hid("HID++: Got name: %s\n", name);
3002 		snprintf(hdev->name, sizeof(hdev->name), "%s", name);
3003 	}
3004 
3005 	kfree(name);
3006 }
3007 
3008 static int hidpp_input_open(struct input_dev *dev)
3009 {
3010 	struct hid_device *hid = input_get_drvdata(dev);
3011 
3012 	return hid_hw_open(hid);
3013 }
3014 
3015 static void hidpp_input_close(struct input_dev *dev)
3016 {
3017 	struct hid_device *hid = input_get_drvdata(dev);
3018 
3019 	hid_hw_close(hid);
3020 }
3021 
3022 static struct input_dev *hidpp_allocate_input(struct hid_device *hdev)
3023 {
3024 	struct input_dev *input_dev = devm_input_allocate_device(&hdev->dev);
3025 	struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3026 
3027 	if (!input_dev)
3028 		return NULL;
3029 
3030 	input_set_drvdata(input_dev, hdev);
3031 	input_dev->open = hidpp_input_open;
3032 	input_dev->close = hidpp_input_close;
3033 
3034 	input_dev->name = hidpp->name;
3035 	input_dev->phys = hdev->phys;
3036 	input_dev->uniq = hdev->uniq;
3037 	input_dev->id.bustype = hdev->bus;
3038 	input_dev->id.vendor  = hdev->vendor;
3039 	input_dev->id.product = hdev->product;
3040 	input_dev->id.version = hdev->version;
3041 	input_dev->dev.parent = &hdev->dev;
3042 
3043 	return input_dev;
3044 }
3045 
3046 static void hidpp_connect_event(struct hidpp_device *hidpp)
3047 {
3048 	struct hid_device *hdev = hidpp->hid_dev;
3049 	int ret = 0;
3050 	bool connected = atomic_read(&hidpp->connected);
3051 	struct input_dev *input;
3052 	char *name, *devm_name;
3053 
3054 	if (!connected) {
3055 		if (hidpp->battery.ps) {
3056 			hidpp->battery.online = false;
3057 			hidpp->battery.status = POWER_SUPPLY_STATUS_UNKNOWN;
3058 			hidpp->battery.level = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
3059 			power_supply_changed(hidpp->battery.ps);
3060 		}
3061 		return;
3062 	}
3063 
3064 	if (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP) {
3065 		ret = wtp_connect(hdev, connected);
3066 		if (ret)
3067 			return;
3068 	} else if (hidpp->quirks & HIDPP_QUIRK_CLASS_M560) {
3069 		ret = m560_send_config_command(hdev, connected);
3070 		if (ret)
3071 			return;
3072 	} else if (hidpp->quirks & HIDPP_QUIRK_CLASS_K400) {
3073 		ret = k400_connect(hdev, connected);
3074 		if (ret)
3075 			return;
3076 	}
3077 
3078 	/* the device is already connected, we can ask for its name and
3079 	 * protocol */
3080 	if (!hidpp->protocol_major) {
3081 		ret = !hidpp_is_connected(hidpp);
3082 		if (ret) {
3083 			hid_err(hdev, "Can not get the protocol version.\n");
3084 			return;
3085 		}
3086 		hid_info(hdev, "HID++ %u.%u device connected.\n",
3087 			 hidpp->protocol_major, hidpp->protocol_minor);
3088 	}
3089 
3090 	if (hidpp->name == hdev->name && hidpp->protocol_major >= 2) {
3091 		name = hidpp_get_device_name(hidpp);
3092 		if (!name) {
3093 			hid_err(hdev,
3094 				"unable to retrieve the name of the device");
3095 			return;
3096 		}
3097 
3098 		devm_name = devm_kasprintf(&hdev->dev, GFP_KERNEL, "%s", name);
3099 		kfree(name);
3100 		if (!devm_name)
3101 			return;
3102 
3103 		hidpp->name = devm_name;
3104 	}
3105 
3106 	hidpp_initialize_battery(hidpp);
3107 
3108 	/* forward current battery state */
3109 	if (hidpp->capabilities & HIDPP_CAPABILITY_HIDPP10_BATTERY) {
3110 		hidpp10_enable_battery_reporting(hidpp);
3111 		if (hidpp->capabilities & HIDPP_CAPABILITY_BATTERY_MILEAGE)
3112 			hidpp10_query_battery_mileage(hidpp);
3113 		else
3114 			hidpp10_query_battery_status(hidpp);
3115 	} else if (hidpp->capabilities & HIDPP_CAPABILITY_HIDPP20_BATTERY) {
3116 		hidpp20_query_battery_info(hidpp);
3117 	}
3118 	if (hidpp->battery.ps)
3119 		power_supply_changed(hidpp->battery.ps);
3120 
3121 	if (hidpp->quirks & HIDPP_QUIRK_HI_RES_SCROLL)
3122 		hi_res_scroll_enable(hidpp);
3123 
3124 	if (!(hidpp->quirks & HIDPP_QUIRK_NO_HIDINPUT) || hidpp->delayed_input)
3125 		/* if the input nodes are already created, we can stop now */
3126 		return;
3127 
3128 	input = hidpp_allocate_input(hdev);
3129 	if (!input) {
3130 		hid_err(hdev, "cannot allocate new input device: %d\n", ret);
3131 		return;
3132 	}
3133 
3134 	hidpp_populate_input(hidpp, input, false);
3135 
3136 	ret = input_register_device(input);
3137 	if (ret)
3138 		input_free_device(input);
3139 
3140 	hidpp->delayed_input = input;
3141 }
3142 
3143 static DEVICE_ATTR(builtin_power_supply, 0000, NULL, NULL);
3144 
3145 static struct attribute *sysfs_attrs[] = {
3146 	&dev_attr_builtin_power_supply.attr,
3147 	NULL
3148 };
3149 
3150 static const struct attribute_group ps_attribute_group = {
3151 	.attrs = sysfs_attrs
3152 };
3153 
3154 static int hidpp_probe(struct hid_device *hdev, const struct hid_device_id *id)
3155 {
3156 	struct hidpp_device *hidpp;
3157 	int ret;
3158 	bool connected;
3159 	unsigned int connect_mask = HID_CONNECT_DEFAULT;
3160 
3161 	hidpp = devm_kzalloc(&hdev->dev, sizeof(struct hidpp_device),
3162 			GFP_KERNEL);
3163 	if (!hidpp)
3164 		return -ENOMEM;
3165 
3166 	hidpp->hid_dev = hdev;
3167 	hidpp->name = hdev->name;
3168 	hid_set_drvdata(hdev, hidpp);
3169 
3170 	hidpp->quirks = id->driver_data;
3171 
3172 	if (id->group == HID_GROUP_LOGITECH_DJ_DEVICE)
3173 		hidpp->quirks |= HIDPP_QUIRK_UNIFYING;
3174 
3175 	if (disable_raw_mode) {
3176 		hidpp->quirks &= ~HIDPP_QUIRK_CLASS_WTP;
3177 		hidpp->quirks &= ~HIDPP_QUIRK_NO_HIDINPUT;
3178 	}
3179 
3180 	if (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP) {
3181 		ret = wtp_allocate(hdev, id);
3182 		if (ret)
3183 			goto allocate_fail;
3184 	} else if (hidpp->quirks & HIDPP_QUIRK_CLASS_M560) {
3185 		ret = m560_allocate(hdev);
3186 		if (ret)
3187 			goto allocate_fail;
3188 	} else if (hidpp->quirks & HIDPP_QUIRK_CLASS_K400) {
3189 		ret = k400_allocate(hdev);
3190 		if (ret)
3191 			goto allocate_fail;
3192 	}
3193 
3194 	INIT_WORK(&hidpp->work, delayed_work_cb);
3195 	mutex_init(&hidpp->send_mutex);
3196 	init_waitqueue_head(&hidpp->wait);
3197 
3198 	/* indicates we are handling the battery properties in the kernel */
3199 	ret = sysfs_create_group(&hdev->dev.kobj, &ps_attribute_group);
3200 	if (ret)
3201 		hid_warn(hdev, "Cannot allocate sysfs group for %s\n",
3202 			 hdev->name);
3203 
3204 	ret = hid_parse(hdev);
3205 	if (ret) {
3206 		hid_err(hdev, "%s:parse failed\n", __func__);
3207 		goto hid_parse_fail;
3208 	}
3209 
3210 	if (hidpp->quirks & HIDPP_QUIRK_NO_HIDINPUT)
3211 		connect_mask &= ~HID_CONNECT_HIDINPUT;
3212 
3213 	if (hidpp->quirks & HIDPP_QUIRK_CLASS_G920) {
3214 		ret = hid_hw_start(hdev, connect_mask);
3215 		if (ret) {
3216 			hid_err(hdev, "hw start failed\n");
3217 			goto hid_hw_start_fail;
3218 		}
3219 		ret = hid_hw_open(hdev);
3220 		if (ret < 0) {
3221 			dev_err(&hdev->dev, "%s:hid_hw_open returned error:%d\n",
3222 				__func__, ret);
3223 			hid_hw_stop(hdev);
3224 			goto hid_hw_start_fail;
3225 		}
3226 	}
3227 
3228 
3229 	/* Allow incoming packets */
3230 	hid_device_io_start(hdev);
3231 
3232 	if (hidpp->quirks & HIDPP_QUIRK_UNIFYING)
3233 		hidpp_unifying_init(hidpp);
3234 
3235 	connected = hidpp_is_connected(hidpp);
3236 	atomic_set(&hidpp->connected, connected);
3237 	if (!(hidpp->quirks & HIDPP_QUIRK_UNIFYING)) {
3238 		if (!connected) {
3239 			ret = -ENODEV;
3240 			hid_err(hdev, "Device not connected");
3241 			goto hid_hw_open_failed;
3242 		}
3243 
3244 		hid_info(hdev, "HID++ %u.%u device connected.\n",
3245 			 hidpp->protocol_major, hidpp->protocol_minor);
3246 
3247 		hidpp_overwrite_name(hdev);
3248 	}
3249 
3250 	if (connected && (hidpp->quirks & HIDPP_QUIRK_CLASS_WTP)) {
3251 		ret = wtp_get_config(hidpp);
3252 		if (ret)
3253 			goto hid_hw_open_failed;
3254 	} else if (connected && (hidpp->quirks & HIDPP_QUIRK_CLASS_G920)) {
3255 		ret = g920_get_config(hidpp);
3256 		if (ret)
3257 			goto hid_hw_open_failed;
3258 	}
3259 
3260 	/* Block incoming packets */
3261 	hid_device_io_stop(hdev);
3262 
3263 	if (!(hidpp->quirks & HIDPP_QUIRK_CLASS_G920)) {
3264 		ret = hid_hw_start(hdev, connect_mask);
3265 		if (ret) {
3266 			hid_err(hdev, "%s:hid_hw_start returned error\n", __func__);
3267 			goto hid_hw_start_fail;
3268 		}
3269 	}
3270 
3271 	/* Allow incoming packets */
3272 	hid_device_io_start(hdev);
3273 
3274 	hidpp_connect_event(hidpp);
3275 
3276 	return ret;
3277 
3278 hid_hw_open_failed:
3279 	hid_device_io_stop(hdev);
3280 	if (hidpp->quirks & HIDPP_QUIRK_CLASS_G920) {
3281 		hid_hw_close(hdev);
3282 		hid_hw_stop(hdev);
3283 	}
3284 hid_hw_start_fail:
3285 hid_parse_fail:
3286 	sysfs_remove_group(&hdev->dev.kobj, &ps_attribute_group);
3287 	cancel_work_sync(&hidpp->work);
3288 	mutex_destroy(&hidpp->send_mutex);
3289 allocate_fail:
3290 	hid_set_drvdata(hdev, NULL);
3291 	return ret;
3292 }
3293 
3294 static void hidpp_remove(struct hid_device *hdev)
3295 {
3296 	struct hidpp_device *hidpp = hid_get_drvdata(hdev);
3297 
3298 	sysfs_remove_group(&hdev->dev.kobj, &ps_attribute_group);
3299 
3300 	if (hidpp->quirks & HIDPP_QUIRK_CLASS_G920) {
3301 		hidpp_ff_deinit(hdev);
3302 		hid_hw_close(hdev);
3303 	}
3304 	hid_hw_stop(hdev);
3305 	cancel_work_sync(&hidpp->work);
3306 	mutex_destroy(&hidpp->send_mutex);
3307 }
3308 
3309 #define LDJ_DEVICE(product) \
3310 	HID_DEVICE(BUS_USB, HID_GROUP_LOGITECH_DJ_DEVICE, \
3311 		   USB_VENDOR_ID_LOGITECH, (product))
3312 
3313 static const struct hid_device_id hidpp_devices[] = {
3314 	{ /* wireless touchpad */
3315 	  LDJ_DEVICE(0x4011),
3316 	  .driver_data = HIDPP_QUIRK_CLASS_WTP | HIDPP_QUIRK_DELAYED_INIT |
3317 			 HIDPP_QUIRK_WTP_PHYSICAL_BUTTONS },
3318 	{ /* wireless touchpad T650 */
3319 	  LDJ_DEVICE(0x4101),
3320 	  .driver_data = HIDPP_QUIRK_CLASS_WTP | HIDPP_QUIRK_DELAYED_INIT },
3321 	{ /* wireless touchpad T651 */
3322 	  HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_LOGITECH,
3323 		USB_DEVICE_ID_LOGITECH_T651),
3324 	  .driver_data = HIDPP_QUIRK_CLASS_WTP },
3325 	{ /* Mouse Logitech Anywhere MX */
3326 	  LDJ_DEVICE(0x1017), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_1P0 },
3327 	{ /* Mouse Logitech Cube */
3328 	  LDJ_DEVICE(0x4010), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2120 },
3329 	{ /* Mouse Logitech M335 */
3330 	  LDJ_DEVICE(0x4050), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3331 	{ /* Mouse Logitech M515 */
3332 	  LDJ_DEVICE(0x4007), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2120 },
3333 	{ /* Mouse logitech M560 */
3334 	  LDJ_DEVICE(0x402d),
3335 	  .driver_data = HIDPP_QUIRK_DELAYED_INIT | HIDPP_QUIRK_CLASS_M560
3336 		| HIDPP_QUIRK_HI_RES_SCROLL_X2120 },
3337 	{ /* Mouse Logitech M705 (firmware RQM17) */
3338 	  LDJ_DEVICE(0x101b), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_1P0 },
3339 	{ /* Mouse Logitech M705 (firmware RQM67) */
3340 	  LDJ_DEVICE(0x406d), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3341 	{ /* Mouse Logitech M720 */
3342 	  LDJ_DEVICE(0x405e), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3343 	{ /* Mouse Logitech MX Anywhere 2 */
3344 	  LDJ_DEVICE(0x404a), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3345 	{ LDJ_DEVICE(0xb013), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3346 	{ LDJ_DEVICE(0xb018), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3347 	{ LDJ_DEVICE(0xb01f), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3348 	{ /* Mouse Logitech MX Anywhere 2S */
3349 	  LDJ_DEVICE(0x406a), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3350 	{ /* Mouse Logitech MX Master */
3351 	  LDJ_DEVICE(0x4041), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3352 	{ LDJ_DEVICE(0x4060), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3353 	{ LDJ_DEVICE(0x4071), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3354 	{ /* Mouse Logitech MX Master 2S */
3355 	  LDJ_DEVICE(0x4069), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_X2121 },
3356 	{ /* Mouse Logitech Performance MX */
3357 	  LDJ_DEVICE(0x101a), .driver_data = HIDPP_QUIRK_HI_RES_SCROLL_1P0 },
3358 	{ /* Keyboard logitech K400 */
3359 	  LDJ_DEVICE(0x4024),
3360 	  .driver_data = HIDPP_QUIRK_CLASS_K400 },
3361 	{ /* Solar Keyboard Logitech K750 */
3362 	  LDJ_DEVICE(0x4002),
3363 	  .driver_data = HIDPP_QUIRK_CLASS_K750 },
3364 
3365 	{ LDJ_DEVICE(HID_ANY_ID) },
3366 
3367 	{ HID_USB_DEVICE(USB_VENDOR_ID_LOGITECH, USB_DEVICE_ID_LOGITECH_G920_WHEEL),
3368 		.driver_data = HIDPP_QUIRK_CLASS_G920 | HIDPP_QUIRK_FORCE_OUTPUT_REPORTS},
3369 	{}
3370 };
3371 
3372 MODULE_DEVICE_TABLE(hid, hidpp_devices);
3373 
3374 static const struct hid_usage_id hidpp_usages[] = {
3375 	{ HID_GD_WHEEL, EV_REL, REL_WHEEL },
3376 	{ HID_ANY_ID - 1, HID_ANY_ID - 1, HID_ANY_ID - 1}
3377 };
3378 
3379 static struct hid_driver hidpp_driver = {
3380 	.name = "logitech-hidpp-device",
3381 	.id_table = hidpp_devices,
3382 	.probe = hidpp_probe,
3383 	.remove = hidpp_remove,
3384 	.raw_event = hidpp_raw_event,
3385 	.usage_table = hidpp_usages,
3386 	.event = hidpp_event,
3387 	.input_configured = hidpp_input_configured,
3388 	.input_mapping = hidpp_input_mapping,
3389 	.input_mapped = hidpp_input_mapped,
3390 };
3391 
3392 module_hid_driver(hidpp_driver);
3393