1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES.  All rights reserved.
4  *
5  *  HID driver for NVIDIA SHIELD peripherals.
6  */
7 
8 #include <linux/hid.h>
9 #include <linux/idr.h>
10 #include <linux/input-event-codes.h>
11 #include <linux/input.h>
12 #include <linux/jiffies.h>
13 #include <linux/leds.h>
14 #include <linux/module.h>
15 #include <linux/power_supply.h>
16 #include <linux/spinlock.h>
17 #include <linux/timer.h>
18 #include <linux/workqueue.h>
19 
20 #include "hid-ids.h"
21 
22 #define NOT_INIT_STR "NOT INITIALIZED"
23 #define android_map_key(c) hid_map_usage(hi, usage, bit, max, EV_KEY, (c))
24 
25 enum {
26 	HID_USAGE_ANDROID_PLAYPAUSE_BTN = 0xcd, /* Double-tap volume slider */
27 	HID_USAGE_ANDROID_VOLUMEUP_BTN = 0xe9,
28 	HID_USAGE_ANDROID_VOLUMEDOWN_BTN = 0xea,
29 	HID_USAGE_ANDROID_SEARCH_BTN = 0x221, /* NVIDIA btn on Thunderstrike */
30 	HID_USAGE_ANDROID_HOME_BTN = 0x223,
31 	HID_USAGE_ANDROID_BACK_BTN = 0x224,
32 };
33 
34 enum {
35 	SHIELD_FW_VERSION_INITIALIZED = 0,
36 	SHIELD_BOARD_INFO_INITIALIZED,
37 	SHIELD_BATTERY_STATS_INITIALIZED,
38 	SHIELD_CHARGER_STATE_INITIALIZED,
39 };
40 
41 enum {
42 	THUNDERSTRIKE_FW_VERSION_UPDATE = 0,
43 	THUNDERSTRIKE_BOARD_INFO_UPDATE,
44 	THUNDERSTRIKE_HAPTICS_UPDATE,
45 	THUNDERSTRIKE_LED_UPDATE,
46 	THUNDERSTRIKE_POWER_SUPPLY_STATS_UPDATE,
47 };
48 
49 enum {
50 	THUNDERSTRIKE_HOSTCMD_REPORT_SIZE = 33,
51 	THUNDERSTRIKE_HOSTCMD_REQ_REPORT_ID = 0x4,
52 	THUNDERSTRIKE_HOSTCMD_RESP_REPORT_ID = 0x3,
53 };
54 
55 enum {
56 	THUNDERSTRIKE_HOSTCMD_ID_FW_VERSION = 1,
57 	THUNDERSTRIKE_HOSTCMD_ID_LED = 6,
58 	THUNDERSTRIKE_HOSTCMD_ID_BATTERY,
59 	THUNDERSTRIKE_HOSTCMD_ID_BOARD_INFO = 16,
60 	THUNDERSTRIKE_HOSTCMD_ID_USB_INIT = 53,
61 	THUNDERSTRIKE_HOSTCMD_ID_HAPTICS = 57,
62 	THUNDERSTRIKE_HOSTCMD_ID_CHARGER,
63 };
64 
65 struct power_supply_dev {
66 	struct power_supply *psy;
67 	struct power_supply_desc desc;
68 };
69 
70 struct thunderstrike_psy_prop_values {
71 	int voltage_min;
72 	int voltage_now;
73 	int voltage_avg;
74 	int voltage_boot;
75 	int capacity;
76 	int status;
77 	int charge_type;
78 	int temp;
79 };
80 
81 static const enum power_supply_property thunderstrike_battery_props[] = {
82 	POWER_SUPPLY_PROP_STATUS,
83 	POWER_SUPPLY_PROP_CHARGE_TYPE,
84 	POWER_SUPPLY_PROP_PRESENT,
85 	POWER_SUPPLY_PROP_VOLTAGE_MIN,
86 	POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN,
87 	POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
88 	POWER_SUPPLY_PROP_VOLTAGE_NOW,
89 	POWER_SUPPLY_PROP_VOLTAGE_AVG,
90 	POWER_SUPPLY_PROP_VOLTAGE_BOOT,
91 	POWER_SUPPLY_PROP_CAPACITY,
92 	POWER_SUPPLY_PROP_SCOPE,
93 	POWER_SUPPLY_PROP_TEMP,
94 	POWER_SUPPLY_PROP_TEMP_MIN,
95 	POWER_SUPPLY_PROP_TEMP_MAX,
96 	POWER_SUPPLY_PROP_TEMP_ALERT_MIN,
97 	POWER_SUPPLY_PROP_TEMP_ALERT_MAX,
98 };
99 
100 enum thunderstrike_led_state {
101 	THUNDERSTRIKE_LED_OFF = 1,
102 	THUNDERSTRIKE_LED_ON = 8,
103 } __packed;
104 static_assert(sizeof(enum thunderstrike_led_state) == 1);
105 
106 struct thunderstrike_hostcmd_battery {
107 	__le16 voltage_avg;
108 	u8 reserved_at_10;
109 	__le16 thermistor;
110 	__le16 voltage_min;
111 	__le16 voltage_boot;
112 	__le16 voltage_now;
113 	u8 capacity;
114 } __packed;
115 
116 enum thunderstrike_charger_type {
117 	THUNDERSTRIKE_CHARGER_TYPE_NONE = 0,
118 	THUNDERSTRIKE_CHARGER_TYPE_TRICKLE,
119 	THUNDERSTRIKE_CHARGER_TYPE_NORMAL,
120 } __packed;
121 static_assert(sizeof(enum thunderstrike_charger_type) == 1);
122 
123 enum thunderstrike_charger_state {
124 	THUNDERSTRIKE_CHARGER_STATE_UNKNOWN = 0,
125 	THUNDERSTRIKE_CHARGER_STATE_DISABLED,
126 	THUNDERSTRIKE_CHARGER_STATE_CHARGING,
127 	THUNDERSTRIKE_CHARGER_STATE_FULL,
128 	THUNDERSTRIKE_CHARGER_STATE_FAILED = 8,
129 } __packed;
130 static_assert(sizeof(enum thunderstrike_charger_state) == 1);
131 
132 struct thunderstrike_hostcmd_charger {
133 	u8 connected;
134 	enum thunderstrike_charger_type type;
135 	enum thunderstrike_charger_state state;
136 } __packed;
137 
138 struct thunderstrike_hostcmd_board_info {
139 	__le16 revision;
140 	__le16 serial[7];
141 } __packed;
142 
143 struct thunderstrike_hostcmd_haptics {
144 	u8 motor_left;
145 	u8 motor_right;
146 } __packed;
147 
148 struct thunderstrike_hostcmd_resp_report {
149 	u8 report_id; /* THUNDERSTRIKE_HOSTCMD_RESP_REPORT_ID */
150 	u8 cmd_id;
151 	u8 reserved_at_10;
152 
153 	union {
154 		struct thunderstrike_hostcmd_board_info board_info;
155 		struct thunderstrike_hostcmd_haptics motors;
156 		__le16 fw_version;
157 		enum thunderstrike_led_state led_state;
158 		struct thunderstrike_hostcmd_battery battery;
159 		struct thunderstrike_hostcmd_charger charger;
160 		u8 payload[30];
161 	} __packed;
162 } __packed;
163 static_assert(sizeof(struct thunderstrike_hostcmd_resp_report) ==
164 	      THUNDERSTRIKE_HOSTCMD_REPORT_SIZE);
165 
166 struct thunderstrike_hostcmd_req_report {
167 	u8 report_id; /* THUNDERSTRIKE_HOSTCMD_REQ_REPORT_ID */
168 	u8 cmd_id;
169 	u8 reserved_at_10;
170 
171 	union {
172 		struct __packed {
173 			u8 update;
174 			enum thunderstrike_led_state state;
175 		} led;
176 		struct __packed {
177 			u8 update;
178 			struct thunderstrike_hostcmd_haptics motors;
179 		} haptics;
180 	} __packed;
181 	u8 reserved_at_30[27];
182 } __packed;
183 static_assert(sizeof(struct thunderstrike_hostcmd_req_report) ==
184 	      THUNDERSTRIKE_HOSTCMD_REPORT_SIZE);
185 
186 /* Common struct for shield accessories. */
187 struct shield_device {
188 	struct hid_device *hdev;
189 	struct power_supply_dev battery_dev;
190 
191 	unsigned long initialized_flags;
192 	const char *codename;
193 	u16 fw_version;
194 	struct {
195 		u16 revision;
196 		char serial_number[15];
197 	} board_info;
198 };
199 
200 /*
201  * Non-trivial to uniquely identify Thunderstrike controllers at initialization
202  * time. Use an ID allocator to help with this.
203  */
204 static DEFINE_IDA(thunderstrike_ida);
205 
206 struct thunderstrike {
207 	struct shield_device base;
208 
209 	int id;
210 
211 	/* Sub-devices */
212 	struct input_dev *haptics_dev;
213 	struct led_classdev led_dev;
214 
215 	/* Resources */
216 	void *req_report_dmabuf;
217 	unsigned long update_flags;
218 	struct thunderstrike_hostcmd_haptics haptics_val;
219 	spinlock_t haptics_update_lock;
220 	u8 led_state : 1;
221 	enum thunderstrike_led_state led_value;
222 	struct thunderstrike_psy_prop_values psy_stats;
223 	spinlock_t psy_stats_lock;
224 	struct timer_list psy_stats_timer;
225 	struct work_struct hostcmd_req_work;
226 };
227 
228 static inline void thunderstrike_hostcmd_req_report_init(
229 	struct thunderstrike_hostcmd_req_report *report, u8 cmd_id)
230 {
231 	memset(report, 0, sizeof(*report));
232 	report->report_id = THUNDERSTRIKE_HOSTCMD_REQ_REPORT_ID;
233 	report->cmd_id = cmd_id;
234 }
235 
236 static inline void shield_strrev(char *dest, size_t len, u16 rev)
237 {
238 	dest[0] = ('A' - 1) + (rev >> 8);
239 	snprintf(&dest[1], len - 1, "%02X", 0xff & rev);
240 }
241 
242 static struct input_dev *shield_allocate_input_dev(struct hid_device *hdev,
243 						   const char *name_suffix)
244 {
245 	struct input_dev *idev;
246 
247 	idev = input_allocate_device();
248 	if (!idev)
249 		goto err_device;
250 
251 	idev->id.bustype = hdev->bus;
252 	idev->id.vendor = hdev->vendor;
253 	idev->id.product = hdev->product;
254 	idev->id.version = hdev->version;
255 	idev->uniq = hdev->uniq;
256 	idev->name = devm_kasprintf(&hdev->dev, GFP_KERNEL, "%s %s", hdev->name,
257 				    name_suffix);
258 	if (!idev->name)
259 		goto err_name;
260 
261 	input_set_drvdata(idev, hdev);
262 
263 	return idev;
264 
265 err_name:
266 	input_free_device(idev);
267 err_device:
268 	return ERR_PTR(-ENOMEM);
269 }
270 
271 static struct input_dev *shield_haptics_create(
272 	struct shield_device *dev,
273 	int (*play_effect)(struct input_dev *, void *, struct ff_effect *))
274 {
275 	struct input_dev *haptics;
276 	int ret;
277 
278 	if (!IS_ENABLED(CONFIG_NVIDIA_SHIELD_FF))
279 		return NULL;
280 
281 	haptics = shield_allocate_input_dev(dev->hdev, "Haptics");
282 	if (IS_ERR(haptics))
283 		return haptics;
284 
285 	input_set_capability(haptics, EV_FF, FF_RUMBLE);
286 	input_ff_create_memless(haptics, NULL, play_effect);
287 
288 	ret = input_register_device(haptics);
289 	if (ret)
290 		goto err;
291 
292 	return haptics;
293 
294 err:
295 	input_free_device(haptics);
296 	return ERR_PTR(ret);
297 }
298 
299 static inline void thunderstrike_send_hostcmd_request(struct thunderstrike *ts)
300 {
301 	struct thunderstrike_hostcmd_req_report *report = ts->req_report_dmabuf;
302 	struct shield_device *shield_dev = &ts->base;
303 	int ret;
304 
305 	ret = hid_hw_raw_request(shield_dev->hdev, report->report_id,
306 				 ts->req_report_dmabuf,
307 				 THUNDERSTRIKE_HOSTCMD_REPORT_SIZE,
308 				 HID_OUTPUT_REPORT, HID_REQ_SET_REPORT);
309 
310 	if (ret < 0) {
311 		hid_err(shield_dev->hdev,
312 			"Failed to output Thunderstrike HOSTCMD request HID report due to %pe\n",
313 			ERR_PTR(ret));
314 	}
315 }
316 
317 static void thunderstrike_hostcmd_req_work_handler(struct work_struct *work)
318 {
319 	struct thunderstrike *ts =
320 		container_of(work, struct thunderstrike, hostcmd_req_work);
321 	struct thunderstrike_hostcmd_req_report *report;
322 	unsigned long flags;
323 
324 	report = ts->req_report_dmabuf;
325 
326 	if (test_and_clear_bit(THUNDERSTRIKE_FW_VERSION_UPDATE, &ts->update_flags)) {
327 		thunderstrike_hostcmd_req_report_init(
328 			report, THUNDERSTRIKE_HOSTCMD_ID_FW_VERSION);
329 		thunderstrike_send_hostcmd_request(ts);
330 	}
331 
332 	if (test_and_clear_bit(THUNDERSTRIKE_LED_UPDATE, &ts->update_flags)) {
333 		thunderstrike_hostcmd_req_report_init(report, THUNDERSTRIKE_HOSTCMD_ID_LED);
334 		report->led.update = 1;
335 		report->led.state = ts->led_value;
336 		thunderstrike_send_hostcmd_request(ts);
337 	}
338 
339 	if (test_and_clear_bit(THUNDERSTRIKE_POWER_SUPPLY_STATS_UPDATE, &ts->update_flags)) {
340 		thunderstrike_hostcmd_req_report_init(
341 			report, THUNDERSTRIKE_HOSTCMD_ID_BATTERY);
342 		thunderstrike_send_hostcmd_request(ts);
343 
344 		thunderstrike_hostcmd_req_report_init(
345 			report, THUNDERSTRIKE_HOSTCMD_ID_CHARGER);
346 		thunderstrike_send_hostcmd_request(ts);
347 	}
348 
349 	if (test_and_clear_bit(THUNDERSTRIKE_BOARD_INFO_UPDATE, &ts->update_flags)) {
350 		thunderstrike_hostcmd_req_report_init(
351 			report, THUNDERSTRIKE_HOSTCMD_ID_BOARD_INFO);
352 		thunderstrike_send_hostcmd_request(ts);
353 	}
354 
355 	if (test_and_clear_bit(THUNDERSTRIKE_HAPTICS_UPDATE, &ts->update_flags)) {
356 		thunderstrike_hostcmd_req_report_init(
357 			report, THUNDERSTRIKE_HOSTCMD_ID_HAPTICS);
358 
359 		report->haptics.update = 1;
360 		spin_lock_irqsave(&ts->haptics_update_lock, flags);
361 		report->haptics.motors = ts->haptics_val;
362 		spin_unlock_irqrestore(&ts->haptics_update_lock, flags);
363 
364 		thunderstrike_send_hostcmd_request(ts);
365 	}
366 }
367 
368 static inline void thunderstrike_request_firmware_version(struct thunderstrike *ts)
369 {
370 	set_bit(THUNDERSTRIKE_FW_VERSION_UPDATE, &ts->update_flags);
371 	schedule_work(&ts->hostcmd_req_work);
372 }
373 
374 static inline void thunderstrike_request_board_info(struct thunderstrike *ts)
375 {
376 	set_bit(THUNDERSTRIKE_BOARD_INFO_UPDATE, &ts->update_flags);
377 	schedule_work(&ts->hostcmd_req_work);
378 }
379 
380 static inline int
381 thunderstrike_update_haptics(struct thunderstrike *ts,
382 			     struct thunderstrike_hostcmd_haptics *motors)
383 {
384 	unsigned long flags;
385 
386 	spin_lock_irqsave(&ts->haptics_update_lock, flags);
387 	ts->haptics_val = *motors;
388 	spin_unlock_irqrestore(&ts->haptics_update_lock, flags);
389 
390 	set_bit(THUNDERSTRIKE_HAPTICS_UPDATE, &ts->update_flags);
391 	schedule_work(&ts->hostcmd_req_work);
392 
393 	return 0;
394 }
395 
396 static int thunderstrike_play_effect(struct input_dev *idev, void *data,
397 				     struct ff_effect *effect)
398 {
399 	struct hid_device *hdev = input_get_drvdata(idev);
400 	struct thunderstrike_hostcmd_haptics motors;
401 	struct shield_device *shield_dev;
402 	struct thunderstrike *ts;
403 
404 	if (effect->type != FF_RUMBLE)
405 		return 0;
406 
407 	shield_dev = hid_get_drvdata(hdev);
408 	ts = container_of(shield_dev, struct thunderstrike, base);
409 
410 	/* Thunderstrike motor values range from 0 to 32 inclusively */
411 	motors.motor_left = effect->u.rumble.strong_magnitude / 2047;
412 	motors.motor_right = effect->u.rumble.weak_magnitude / 2047;
413 
414 	hid_dbg(hdev, "Thunderstrike FF_RUMBLE request, left: %u right: %u\n",
415 		motors.motor_left, motors.motor_right);
416 
417 	return thunderstrike_update_haptics(ts, &motors);
418 }
419 
420 static enum led_brightness
421 thunderstrike_led_get_brightness(struct led_classdev *led)
422 {
423 	struct hid_device *hdev = to_hid_device(led->dev->parent);
424 	struct shield_device *shield_dev = hid_get_drvdata(hdev);
425 	struct thunderstrike *ts;
426 
427 	ts = container_of(shield_dev, struct thunderstrike, base);
428 
429 	return ts->led_state;
430 }
431 
432 static void thunderstrike_led_set_brightness(struct led_classdev *led,
433 					    enum led_brightness value)
434 {
435 	struct hid_device *hdev = to_hid_device(led->dev->parent);
436 	struct shield_device *shield_dev = hid_get_drvdata(hdev);
437 	struct thunderstrike *ts;
438 
439 	ts = container_of(shield_dev, struct thunderstrike, base);
440 
441 	switch (value) {
442 	case LED_OFF:
443 		ts->led_value = THUNDERSTRIKE_LED_OFF;
444 		break;
445 	default:
446 		ts->led_value = THUNDERSTRIKE_LED_ON;
447 		break;
448 	}
449 
450 	set_bit(THUNDERSTRIKE_LED_UPDATE, &ts->update_flags);
451 	schedule_work(&ts->hostcmd_req_work);
452 }
453 
454 static int thunderstrike_battery_get_property(struct power_supply *psy,
455 					      enum power_supply_property psp,
456 					      union power_supply_propval *val)
457 {
458 	struct shield_device *shield_dev = power_supply_get_drvdata(psy);
459 	struct thunderstrike_psy_prop_values prop_values;
460 	struct thunderstrike *ts;
461 	int ret = 0;
462 
463 	ts = container_of(shield_dev, struct thunderstrike, base);
464 	spin_lock(&ts->psy_stats_lock);
465 	prop_values = ts->psy_stats;
466 	spin_unlock(&ts->psy_stats_lock);
467 
468 	switch (psp) {
469 	case POWER_SUPPLY_PROP_STATUS:
470 		val->intval = prop_values.status;
471 		break;
472 	case POWER_SUPPLY_PROP_CHARGE_TYPE:
473 		val->intval = prop_values.charge_type;
474 		break;
475 	case POWER_SUPPLY_PROP_PRESENT:
476 		val->intval = 1;
477 		break;
478 	case POWER_SUPPLY_PROP_VOLTAGE_MIN:
479 		val->intval = prop_values.voltage_min;
480 		break;
481 	case POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN:
482 		val->intval = 2900000; /* 2.9 V */
483 		break;
484 	case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
485 		val->intval = 2200000; /* 2.2 V */
486 		break;
487 	case POWER_SUPPLY_PROP_VOLTAGE_NOW:
488 		val->intval = prop_values.voltage_now;
489 		break;
490 	case POWER_SUPPLY_PROP_VOLTAGE_AVG:
491 		val->intval = prop_values.voltage_avg;
492 		break;
493 	case POWER_SUPPLY_PROP_VOLTAGE_BOOT:
494 		val->intval = prop_values.voltage_boot;
495 		break;
496 	case POWER_SUPPLY_PROP_CAPACITY:
497 		val->intval = prop_values.capacity;
498 		break;
499 	case POWER_SUPPLY_PROP_SCOPE:
500 		val->intval = POWER_SUPPLY_SCOPE_DEVICE;
501 		break;
502 	case POWER_SUPPLY_PROP_TEMP:
503 		val->intval = prop_values.temp;
504 		break;
505 	case POWER_SUPPLY_PROP_TEMP_MIN:
506 		val->intval = 0; /* 0 C */
507 		break;
508 	case POWER_SUPPLY_PROP_TEMP_MAX:
509 		val->intval = 400; /* 40 C */
510 		break;
511 	case POWER_SUPPLY_PROP_TEMP_ALERT_MIN:
512 		val->intval = 15; /* 1.5 C */
513 		break;
514 	case POWER_SUPPLY_PROP_TEMP_ALERT_MAX:
515 		val->intval = 380; /* 38 C */
516 		break;
517 	default:
518 		ret = -EINVAL;
519 		break;
520 	}
521 
522 	return ret;
523 }
524 
525 static inline void thunderstrike_request_psy_stats(struct thunderstrike *ts)
526 {
527 	set_bit(THUNDERSTRIKE_POWER_SUPPLY_STATS_UPDATE, &ts->update_flags);
528 	schedule_work(&ts->hostcmd_req_work);
529 }
530 
531 static void thunderstrike_psy_stats_timer_handler(struct timer_list *timer)
532 {
533 	struct thunderstrike *ts =
534 		container_of(timer, struct thunderstrike, psy_stats_timer);
535 
536 	thunderstrike_request_psy_stats(ts);
537 	/* Query battery statistics from device every five minutes */
538 	mod_timer(timer, jiffies + 300 * HZ);
539 }
540 
541 static void
542 thunderstrike_parse_fw_version_payload(struct shield_device *shield_dev,
543 				       __le16 fw_version)
544 {
545 	shield_dev->fw_version = le16_to_cpu(fw_version);
546 
547 	set_bit(SHIELD_FW_VERSION_INITIALIZED, &shield_dev->initialized_flags);
548 
549 	hid_dbg(shield_dev->hdev, "Thunderstrike firmware version 0x%04X\n",
550 		shield_dev->fw_version);
551 }
552 
553 static void
554 thunderstrike_parse_board_info_payload(struct shield_device *shield_dev,
555 				       struct thunderstrike_hostcmd_board_info *board_info)
556 {
557 	char board_revision_str[4];
558 	int i;
559 
560 	shield_dev->board_info.revision = le16_to_cpu(board_info->revision);
561 	for (i = 0; i < 7; ++i) {
562 		u16 val = le16_to_cpu(board_info->serial[i]);
563 
564 		shield_dev->board_info.serial_number[2 * i] = val & 0xFF;
565 		shield_dev->board_info.serial_number[2 * i + 1] = val >> 8;
566 	}
567 	shield_dev->board_info.serial_number[14] = '\0';
568 
569 	set_bit(SHIELD_BOARD_INFO_INITIALIZED, &shield_dev->initialized_flags);
570 
571 	shield_strrev(board_revision_str, 4, shield_dev->board_info.revision);
572 	hid_dbg(shield_dev->hdev,
573 		"Thunderstrike BOARD_REVISION_%s (0x%04X) S/N: %s\n",
574 		board_revision_str, shield_dev->board_info.revision,
575 		shield_dev->board_info.serial_number);
576 }
577 
578 static inline void
579 thunderstrike_parse_haptics_payload(struct shield_device *shield_dev,
580 				    struct thunderstrike_hostcmd_haptics *haptics)
581 {
582 	hid_dbg(shield_dev->hdev,
583 		"Thunderstrike haptics HOSTCMD response, left: %u right: %u\n",
584 		haptics->motor_left, haptics->motor_right);
585 }
586 
587 static void
588 thunderstrike_parse_led_payload(struct shield_device *shield_dev,
589 				enum thunderstrike_led_state led_state)
590 {
591 	struct thunderstrike *ts = container_of(shield_dev, struct thunderstrike, base);
592 
593 	switch (led_state) {
594 	case THUNDERSTRIKE_LED_OFF:
595 		ts->led_state = 0;
596 		break;
597 	case THUNDERSTRIKE_LED_ON:
598 		ts->led_state = 1;
599 		break;
600 	}
601 
602 	hid_dbg(shield_dev->hdev, "Thunderstrike led HOSTCMD response, 0x%02X\n", led_state);
603 }
604 
605 static void thunderstrike_parse_battery_payload(
606 	struct shield_device *shield_dev,
607 	struct thunderstrike_hostcmd_battery *battery)
608 {
609 	struct thunderstrike *ts = container_of(shield_dev, struct thunderstrike, base);
610 	u16 hostcmd_voltage_boot = le16_to_cpu(battery->voltage_boot);
611 	u16 hostcmd_voltage_avg = le16_to_cpu(battery->voltage_avg);
612 	u16 hostcmd_voltage_min = le16_to_cpu(battery->voltage_min);
613 	u16 hostcmd_voltage_now = le16_to_cpu(battery->voltage_now);
614 	u16 hostcmd_thermistor = le16_to_cpu(battery->thermistor);
615 	int voltage_boot, voltage_avg, voltage_min, voltage_now;
616 	struct hid_device *hdev = shield_dev->hdev;
617 	u8 capacity = battery->capacity;
618 	int temp;
619 
620 	/* Convert thunderstrike device values to µV and tenths of degree Celsius */
621 	voltage_boot = hostcmd_voltage_boot * 1000;
622 	voltage_avg = hostcmd_voltage_avg * 1000;
623 	voltage_min = hostcmd_voltage_min * 1000;
624 	voltage_now = hostcmd_voltage_now * 1000;
625 	temp = (1378 - (int)hostcmd_thermistor) * 10 / 19;
626 
627 	/* Copy converted values */
628 	spin_lock(&ts->psy_stats_lock);
629 	ts->psy_stats.voltage_boot = voltage_boot;
630 	ts->psy_stats.voltage_avg = voltage_avg;
631 	ts->psy_stats.voltage_min = voltage_min;
632 	ts->psy_stats.voltage_now = voltage_now;
633 	ts->psy_stats.capacity = capacity;
634 	ts->psy_stats.temp = temp;
635 	spin_unlock(&ts->psy_stats_lock);
636 
637 	set_bit(SHIELD_BATTERY_STATS_INITIALIZED, &shield_dev->initialized_flags);
638 
639 	hid_dbg(hdev,
640 		"Thunderstrike battery HOSTCMD response, voltage_avg: %u voltage_now: %u\n",
641 		hostcmd_voltage_avg, hostcmd_voltage_now);
642 	hid_dbg(hdev,
643 		"Thunderstrike battery HOSTCMD response, voltage_boot: %u voltage_min: %u\n",
644 		hostcmd_voltage_boot, hostcmd_voltage_min);
645 	hid_dbg(hdev,
646 		"Thunderstrike battery HOSTCMD response, thermistor: %u\n",
647 		hostcmd_thermistor);
648 	hid_dbg(hdev,
649 		"Thunderstrike battery HOSTCMD response, capacity: %u%%\n",
650 		capacity);
651 }
652 
653 static void thunderstrike_parse_charger_payload(
654 	struct shield_device *shield_dev,
655 	struct thunderstrike_hostcmd_charger *charger)
656 {
657 	struct thunderstrike *ts = container_of(shield_dev, struct thunderstrike, base);
658 	int charge_type = POWER_SUPPLY_CHARGE_TYPE_UNKNOWN;
659 	struct hid_device *hdev = shield_dev->hdev;
660 	int status = POWER_SUPPLY_STATUS_UNKNOWN;
661 
662 	switch (charger->type) {
663 	case THUNDERSTRIKE_CHARGER_TYPE_NONE:
664 		charge_type = POWER_SUPPLY_CHARGE_TYPE_NONE;
665 		break;
666 	case THUNDERSTRIKE_CHARGER_TYPE_TRICKLE:
667 		charge_type = POWER_SUPPLY_CHARGE_TYPE_TRICKLE;
668 		break;
669 	case THUNDERSTRIKE_CHARGER_TYPE_NORMAL:
670 		charge_type = POWER_SUPPLY_CHARGE_TYPE_STANDARD;
671 		break;
672 	default:
673 		hid_warn(hdev, "Unhandled Thunderstrike charger HOSTCMD type, %u\n",
674 			 charger->type);
675 		break;
676 	}
677 
678 	switch (charger->state) {
679 	case THUNDERSTRIKE_CHARGER_STATE_UNKNOWN:
680 		status = POWER_SUPPLY_STATUS_UNKNOWN;
681 		break;
682 	case THUNDERSTRIKE_CHARGER_STATE_DISABLED:
683 		/* Indicates charger is disconnected */
684 		break;
685 	case THUNDERSTRIKE_CHARGER_STATE_CHARGING:
686 		status = POWER_SUPPLY_STATUS_CHARGING;
687 		break;
688 	case THUNDERSTRIKE_CHARGER_STATE_FULL:
689 		status = POWER_SUPPLY_STATUS_FULL;
690 		break;
691 	case THUNDERSTRIKE_CHARGER_STATE_FAILED:
692 		status = POWER_SUPPLY_STATUS_NOT_CHARGING;
693 		hid_err(hdev, "Thunderstrike device failed to charge\n");
694 		break;
695 	default:
696 		hid_warn(hdev, "Unhandled Thunderstrike charger HOSTCMD state, %u\n",
697 			 charger->state);
698 		break;
699 	}
700 
701 	if (!charger->connected)
702 		status = POWER_SUPPLY_STATUS_DISCHARGING;
703 
704 	spin_lock(&ts->psy_stats_lock);
705 	ts->psy_stats.charge_type = charge_type;
706 	ts->psy_stats.status = status;
707 	spin_unlock(&ts->psy_stats_lock);
708 
709 	set_bit(SHIELD_CHARGER_STATE_INITIALIZED, &shield_dev->initialized_flags);
710 
711 	hid_dbg(hdev,
712 		"Thunderstrike charger HOSTCMD response, connected: %u, type: %u, state: %u\n",
713 		charger->connected, charger->type, charger->state);
714 }
715 
716 static inline void thunderstrike_device_init_info(struct shield_device *shield_dev)
717 {
718 	struct thunderstrike *ts =
719 		container_of(shield_dev, struct thunderstrike, base);
720 
721 	if (!test_bit(SHIELD_FW_VERSION_INITIALIZED, &shield_dev->initialized_flags))
722 		thunderstrike_request_firmware_version(ts);
723 
724 	if (!test_bit(SHIELD_BOARD_INFO_INITIALIZED, &shield_dev->initialized_flags))
725 		thunderstrike_request_board_info(ts);
726 
727 	if (!test_bit(SHIELD_BATTERY_STATS_INITIALIZED, &shield_dev->initialized_flags) ||
728 	    !test_bit(SHIELD_CHARGER_STATE_INITIALIZED, &shield_dev->initialized_flags))
729 		thunderstrike_psy_stats_timer_handler(&ts->psy_stats_timer);
730 }
731 
732 static int thunderstrike_parse_report(struct shield_device *shield_dev,
733 				      struct hid_report *report, u8 *data,
734 				      int size)
735 {
736 	struct thunderstrike_hostcmd_resp_report *hostcmd_resp_report;
737 	struct hid_device *hdev = shield_dev->hdev;
738 
739 	switch (report->id) {
740 	case THUNDERSTRIKE_HOSTCMD_RESP_REPORT_ID:
741 		if (size != THUNDERSTRIKE_HOSTCMD_REPORT_SIZE) {
742 			hid_err(hdev,
743 				"Encountered Thunderstrike HOSTCMD HID report with unexpected size %d\n",
744 				size);
745 			return -EINVAL;
746 		}
747 
748 		hostcmd_resp_report =
749 			(struct thunderstrike_hostcmd_resp_report *)data;
750 
751 		switch (hostcmd_resp_report->cmd_id) {
752 		case THUNDERSTRIKE_HOSTCMD_ID_FW_VERSION:
753 			thunderstrike_parse_fw_version_payload(
754 				shield_dev, hostcmd_resp_report->fw_version);
755 			break;
756 		case THUNDERSTRIKE_HOSTCMD_ID_LED:
757 			thunderstrike_parse_led_payload(shield_dev, hostcmd_resp_report->led_state);
758 			break;
759 		case THUNDERSTRIKE_HOSTCMD_ID_BATTERY:
760 			thunderstrike_parse_battery_payload(shield_dev,
761 							    &hostcmd_resp_report->battery);
762 			break;
763 		case THUNDERSTRIKE_HOSTCMD_ID_BOARD_INFO:
764 			thunderstrike_parse_board_info_payload(
765 				shield_dev, &hostcmd_resp_report->board_info);
766 			break;
767 		case THUNDERSTRIKE_HOSTCMD_ID_HAPTICS:
768 			thunderstrike_parse_haptics_payload(
769 				shield_dev, &hostcmd_resp_report->motors);
770 			break;
771 		case THUNDERSTRIKE_HOSTCMD_ID_USB_INIT:
772 			/* May block HOSTCMD requests till received initially */
773 			thunderstrike_device_init_info(shield_dev);
774 			break;
775 		case THUNDERSTRIKE_HOSTCMD_ID_CHARGER:
776 			/* May block HOSTCMD requests till received initially */
777 			thunderstrike_device_init_info(shield_dev);
778 
779 			thunderstrike_parse_charger_payload(
780 				shield_dev, &hostcmd_resp_report->charger);
781 			break;
782 		default:
783 			hid_warn(hdev,
784 				 "Unhandled Thunderstrike HOSTCMD id %d\n",
785 				 hostcmd_resp_report->cmd_id);
786 			return -ENOENT;
787 		}
788 
789 		break;
790 	default:
791 		return 0;
792 	}
793 
794 	return 0;
795 }
796 
797 static inline int thunderstrike_led_create(struct thunderstrike *ts)
798 {
799 	struct led_classdev *led = &ts->led_dev;
800 
801 	led->name = devm_kasprintf(&ts->base.hdev->dev, GFP_KERNEL,
802 				   "thunderstrike%d:blue:led", ts->id);
803 	led->max_brightness = 1;
804 	led->flags = LED_CORE_SUSPENDRESUME | LED_RETAIN_AT_SHUTDOWN;
805 	led->brightness_get = &thunderstrike_led_get_brightness;
806 	led->brightness_set = &thunderstrike_led_set_brightness;
807 
808 	return led_classdev_register(&ts->base.hdev->dev, led);
809 }
810 
811 static inline int thunderstrike_psy_create(struct shield_device *shield_dev)
812 {
813 	struct thunderstrike *ts = container_of(shield_dev, struct thunderstrike, base);
814 	struct power_supply_config psy_cfg = { .drv_data = shield_dev, };
815 	struct hid_device *hdev = shield_dev->hdev;
816 	int ret;
817 
818 	/*
819 	 * Set an initial capacity and temperature value to avoid prematurely
820 	 * triggering alerts. Will be replaced by values queried from initial
821 	 * HOSTCMD requests.
822 	 */
823 	ts->psy_stats.capacity = 100;
824 	ts->psy_stats.temp = 182;
825 
826 	shield_dev->battery_dev.desc.properties = thunderstrike_battery_props;
827 	shield_dev->battery_dev.desc.num_properties =
828 		ARRAY_SIZE(thunderstrike_battery_props);
829 	shield_dev->battery_dev.desc.get_property = thunderstrike_battery_get_property;
830 	shield_dev->battery_dev.desc.type = POWER_SUPPLY_TYPE_BATTERY;
831 	shield_dev->battery_dev.desc.name =
832 		devm_kasprintf(&ts->base.hdev->dev, GFP_KERNEL,
833 			       "thunderstrike_%d", ts->id);
834 
835 	shield_dev->battery_dev.psy = power_supply_register(
836 		&hdev->dev, &shield_dev->battery_dev.desc, &psy_cfg);
837 	if (IS_ERR(shield_dev->battery_dev.psy)) {
838 		hid_err(hdev, "Failed to register Thunderstrike battery device\n");
839 		return PTR_ERR(shield_dev->battery_dev.psy);
840 	}
841 
842 	ret = power_supply_powers(shield_dev->battery_dev.psy, &hdev->dev);
843 	if (ret) {
844 		hid_err(hdev, "Failed to associate battery device to Thunderstrike\n");
845 		goto err;
846 	}
847 
848 	return 0;
849 
850 err:
851 	power_supply_unregister(shield_dev->battery_dev.psy);
852 	return ret;
853 }
854 
855 static struct shield_device *thunderstrike_create(struct hid_device *hdev)
856 {
857 	struct shield_device *shield_dev;
858 	struct thunderstrike *ts;
859 	int ret;
860 
861 	ts = devm_kzalloc(&hdev->dev, sizeof(*ts), GFP_KERNEL);
862 	if (!ts)
863 		return ERR_PTR(-ENOMEM);
864 
865 	ts->req_report_dmabuf = devm_kzalloc(
866 		&hdev->dev, THUNDERSTRIKE_HOSTCMD_REPORT_SIZE, GFP_KERNEL);
867 	if (!ts->req_report_dmabuf)
868 		return ERR_PTR(-ENOMEM);
869 
870 	shield_dev = &ts->base;
871 	shield_dev->hdev = hdev;
872 	shield_dev->codename = "Thunderstrike";
873 
874 	spin_lock_init(&ts->haptics_update_lock);
875 	spin_lock_init(&ts->psy_stats_lock);
876 	INIT_WORK(&ts->hostcmd_req_work, thunderstrike_hostcmd_req_work_handler);
877 
878 	hid_set_drvdata(hdev, shield_dev);
879 
880 	ts->id = ida_alloc(&thunderstrike_ida, GFP_KERNEL);
881 	if (ts->id < 0)
882 		return ERR_PTR(ts->id);
883 
884 	ts->haptics_dev = shield_haptics_create(shield_dev, thunderstrike_play_effect);
885 	if (IS_ERR(ts->haptics_dev)) {
886 		hid_err(hdev, "Failed to create Thunderstrike haptics instance\n");
887 		ret = PTR_ERR(ts->haptics_dev);
888 		goto err_id;
889 	}
890 
891 	ret = thunderstrike_psy_create(shield_dev);
892 	if (ret) {
893 		hid_err(hdev, "Failed to create Thunderstrike power supply instance\n");
894 		goto err_haptics;
895 	}
896 
897 	ret = thunderstrike_led_create(ts);
898 	if (ret) {
899 		hid_err(hdev, "Failed to create Thunderstrike LED instance\n");
900 		goto err_psy;
901 	}
902 
903 	timer_setup(&ts->psy_stats_timer, thunderstrike_psy_stats_timer_handler, 0);
904 
905 	hid_info(hdev, "Registered Thunderstrike controller\n");
906 	return shield_dev;
907 
908 err_psy:
909 	power_supply_unregister(shield_dev->battery_dev.psy);
910 err_haptics:
911 	if (ts->haptics_dev)
912 		input_unregister_device(ts->haptics_dev);
913 err_id:
914 	ida_free(&thunderstrike_ida, ts->id);
915 	return ERR_PTR(ret);
916 }
917 
918 static int android_input_mapping(struct hid_device *hdev, struct hid_input *hi,
919 				 struct hid_field *field,
920 				 struct hid_usage *usage, unsigned long **bit,
921 				 int *max)
922 {
923 	if ((usage->hid & HID_USAGE_PAGE) != HID_UP_CONSUMER)
924 		return 0;
925 
926 	switch (usage->hid & HID_USAGE) {
927 	case HID_USAGE_ANDROID_PLAYPAUSE_BTN:
928 		android_map_key(KEY_PLAYPAUSE);
929 		break;
930 	case HID_USAGE_ANDROID_VOLUMEUP_BTN:
931 		android_map_key(KEY_VOLUMEUP);
932 		break;
933 	case HID_USAGE_ANDROID_VOLUMEDOWN_BTN:
934 		android_map_key(KEY_VOLUMEDOWN);
935 		break;
936 	case HID_USAGE_ANDROID_SEARCH_BTN:
937 		android_map_key(BTN_Z);
938 		break;
939 	case HID_USAGE_ANDROID_HOME_BTN:
940 		android_map_key(BTN_MODE);
941 		break;
942 	case HID_USAGE_ANDROID_BACK_BTN:
943 		android_map_key(BTN_SELECT);
944 		break;
945 	default:
946 		return 0;
947 	}
948 
949 	return 1;
950 }
951 
952 static ssize_t firmware_version_show(struct device *dev,
953 				     struct device_attribute *attr, char *buf)
954 {
955 	struct hid_device *hdev = to_hid_device(dev);
956 	struct shield_device *shield_dev;
957 	int ret;
958 
959 	shield_dev = hid_get_drvdata(hdev);
960 
961 	if (test_bit(SHIELD_FW_VERSION_INITIALIZED, &shield_dev->initialized_flags))
962 		ret = sysfs_emit(buf, "0x%04X\n", shield_dev->fw_version);
963 	else
964 		ret = sysfs_emit(buf, NOT_INIT_STR "\n");
965 
966 	return ret;
967 }
968 
969 static DEVICE_ATTR_RO(firmware_version);
970 
971 static ssize_t hardware_version_show(struct device *dev,
972 				     struct device_attribute *attr, char *buf)
973 {
974 	struct hid_device *hdev = to_hid_device(dev);
975 	struct shield_device *shield_dev;
976 	char board_revision_str[4];
977 	int ret;
978 
979 	shield_dev = hid_get_drvdata(hdev);
980 
981 	if (test_bit(SHIELD_BOARD_INFO_INITIALIZED, &shield_dev->initialized_flags)) {
982 		shield_strrev(board_revision_str, 4, shield_dev->board_info.revision);
983 		ret = sysfs_emit(buf, "%s BOARD_REVISION_%s (0x%04X)\n",
984 				 shield_dev->codename, board_revision_str,
985 				 shield_dev->board_info.revision);
986 	} else
987 		ret = sysfs_emit(buf, NOT_INIT_STR "\n");
988 
989 	return ret;
990 }
991 
992 static DEVICE_ATTR_RO(hardware_version);
993 
994 static ssize_t serial_number_show(struct device *dev,
995 				  struct device_attribute *attr, char *buf)
996 {
997 	struct hid_device *hdev = to_hid_device(dev);
998 	struct shield_device *shield_dev;
999 	int ret;
1000 
1001 	shield_dev = hid_get_drvdata(hdev);
1002 
1003 	if (test_bit(SHIELD_BOARD_INFO_INITIALIZED, &shield_dev->initialized_flags))
1004 		ret = sysfs_emit(buf, "%s\n", shield_dev->board_info.serial_number);
1005 	else
1006 		ret = sysfs_emit(buf, NOT_INIT_STR "\n");
1007 
1008 	return ret;
1009 }
1010 
1011 static DEVICE_ATTR_RO(serial_number);
1012 
1013 static struct attribute *shield_device_attrs[] = {
1014 	&dev_attr_firmware_version.attr,
1015 	&dev_attr_hardware_version.attr,
1016 	&dev_attr_serial_number.attr,
1017 	NULL,
1018 };
1019 ATTRIBUTE_GROUPS(shield_device);
1020 
1021 static int shield_raw_event(struct hid_device *hdev, struct hid_report *report,
1022 			    u8 *data, int size)
1023 {
1024 	struct shield_device *dev = hid_get_drvdata(hdev);
1025 
1026 	return thunderstrike_parse_report(dev, report, data, size);
1027 }
1028 
1029 static int shield_probe(struct hid_device *hdev, const struct hid_device_id *id)
1030 {
1031 	struct shield_device *shield_dev = NULL;
1032 	struct thunderstrike *ts;
1033 	int ret;
1034 
1035 	ret = hid_parse(hdev);
1036 	if (ret) {
1037 		hid_err(hdev, "Parse failed\n");
1038 		return ret;
1039 	}
1040 
1041 	switch (id->product) {
1042 	case USB_DEVICE_ID_NVIDIA_THUNDERSTRIKE_CONTROLLER:
1043 		shield_dev = thunderstrike_create(hdev);
1044 		break;
1045 	}
1046 
1047 	if (unlikely(!shield_dev)) {
1048 		hid_err(hdev, "Failed to identify SHIELD device\n");
1049 		return -ENODEV;
1050 	}
1051 	if (IS_ERR(shield_dev)) {
1052 		hid_err(hdev, "Failed to create SHIELD device\n");
1053 		return PTR_ERR(shield_dev);
1054 	}
1055 
1056 	ts = container_of(shield_dev, struct thunderstrike, base);
1057 
1058 	ret = hid_hw_start(hdev, HID_CONNECT_HIDINPUT);
1059 	if (ret) {
1060 		hid_err(hdev, "Failed to start HID device\n");
1061 		goto err_ts_create;
1062 	}
1063 
1064 	ret = hid_hw_open(hdev);
1065 	if (ret) {
1066 		hid_err(hdev, "Failed to open HID device\n");
1067 		goto err_stop;
1068 	}
1069 
1070 	thunderstrike_device_init_info(shield_dev);
1071 
1072 	return ret;
1073 
1074 err_stop:
1075 	hid_hw_stop(hdev);
1076 err_ts_create:
1077 	power_supply_unregister(ts->base.battery_dev.psy);
1078 	if (ts->haptics_dev)
1079 		input_unregister_device(ts->haptics_dev);
1080 	led_classdev_unregister(&ts->led_dev);
1081 	ida_free(&thunderstrike_ida, ts->id);
1082 	return ret;
1083 }
1084 
1085 static void shield_remove(struct hid_device *hdev)
1086 {
1087 	struct shield_device *dev = hid_get_drvdata(hdev);
1088 	struct thunderstrike *ts;
1089 
1090 	ts = container_of(dev, struct thunderstrike, base);
1091 
1092 	hid_hw_close(hdev);
1093 	power_supply_unregister(dev->battery_dev.psy);
1094 	if (ts->haptics_dev)
1095 		input_unregister_device(ts->haptics_dev);
1096 	led_classdev_unregister(&ts->led_dev);
1097 	ida_free(&thunderstrike_ida, ts->id);
1098 	del_timer_sync(&ts->psy_stats_timer);
1099 	cancel_work_sync(&ts->hostcmd_req_work);
1100 	hid_hw_stop(hdev);
1101 }
1102 
1103 static const struct hid_device_id shield_devices[] = {
1104 	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NVIDIA,
1105 			       USB_DEVICE_ID_NVIDIA_THUNDERSTRIKE_CONTROLLER) },
1106 	{ HID_USB_DEVICE(USB_VENDOR_ID_NVIDIA,
1107 			 USB_DEVICE_ID_NVIDIA_THUNDERSTRIKE_CONTROLLER) },
1108 	{ }
1109 };
1110 MODULE_DEVICE_TABLE(hid, shield_devices);
1111 
1112 static struct hid_driver shield_driver = {
1113 	.name          = "shield",
1114 	.id_table      = shield_devices,
1115 	.input_mapping = android_input_mapping,
1116 	.probe         = shield_probe,
1117 	.remove        = shield_remove,
1118 	.raw_event     = shield_raw_event,
1119 	.driver = {
1120 		.dev_groups = shield_device_groups,
1121 	},
1122 };
1123 module_hid_driver(shield_driver);
1124 
1125 MODULE_AUTHOR("Rahul Rameshbabu <rrameshbabu@nvidia.com>");
1126 MODULE_DESCRIPTION("HID Driver for NVIDIA SHIELD peripherals.");
1127 MODULE_LICENSE("GPL");
1128