xref: /openbmc/linux/drivers/hid/hid-steam.c (revision f220d3eb)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * HID driver for Valve Steam Controller
4  *
5  * Copyright (c) 2018 Rodrigo Rivas Costa <rodrigorivascosta@gmail.com>
6  *
7  * Supports both the wired and wireless interfaces.
8  *
9  * This controller has a builtin emulation of mouse and keyboard: the right pad
10  * can be used as a mouse, the shoulder buttons are mouse buttons, A and B
11  * buttons are ENTER and ESCAPE, and so on. This is implemented as additional
12  * HID interfaces.
13  *
14  * This is known as the "lizard mode", because apparently lizards like to use
15  * the computer from the coach, without a proper mouse and keyboard.
16  *
17  * This driver will disable the lizard mode when the input device is opened
18  * and re-enable it when the input device is closed, so as not to break user
19  * mode behaviour. The lizard_mode parameter can be used to change that.
20  *
21  * There are a few user space applications (notably Steam Client) that use
22  * the hidraw interface directly to create input devices (XTest, uinput...).
23  * In order to avoid breaking them this driver creates a layered hidraw device,
24  * so it can detect when the client is running and then:
25  *  - it will not send any command to the controller.
26  *  - this input device will be disabled, to avoid double input of the same
27  *    user action.
28  *
29  * For additional functions, such as changing the right-pad margin or switching
30  * the led, you can use the user-space tool at:
31  *
32  *   https://github.com/rodrigorc/steamctrl
33  */
34 
35 #include <linux/device.h>
36 #include <linux/input.h>
37 #include <linux/hid.h>
38 #include <linux/module.h>
39 #include <linux/workqueue.h>
40 #include <linux/mutex.h>
41 #include <linux/rcupdate.h>
42 #include <linux/delay.h>
43 #include <linux/power_supply.h>
44 #include "hid-ids.h"
45 
46 MODULE_LICENSE("GPL");
47 MODULE_AUTHOR("Rodrigo Rivas Costa <rodrigorivascosta@gmail.com>");
48 
49 static bool lizard_mode = true;
50 
51 static DEFINE_MUTEX(steam_devices_lock);
52 static LIST_HEAD(steam_devices);
53 
54 #define STEAM_QUIRK_WIRELESS		BIT(0)
55 
56 /* Touch pads are 40 mm in diameter and 65535 units */
57 #define STEAM_PAD_RESOLUTION 1638
58 /* Trigger runs are about 5 mm and 256 units */
59 #define STEAM_TRIGGER_RESOLUTION 51
60 /* Joystick runs are about 5 mm and 256 units */
61 #define STEAM_JOYSTICK_RESOLUTION 51
62 
63 #define STEAM_PAD_FUZZ 256
64 
65 /*
66  * Commands that can be sent in a feature report.
67  * Thanks to Valve for some valuable hints.
68  */
69 #define STEAM_CMD_SET_MAPPINGS		0x80
70 #define STEAM_CMD_CLEAR_MAPPINGS	0x81
71 #define STEAM_CMD_GET_MAPPINGS		0x82
72 #define STEAM_CMD_GET_ATTRIB		0x83
73 #define STEAM_CMD_GET_ATTRIB_LABEL	0x84
74 #define STEAM_CMD_DEFAULT_MAPPINGS	0x85
75 #define STEAM_CMD_FACTORY_RESET		0x86
76 #define STEAM_CMD_WRITE_REGISTER	0x87
77 #define STEAM_CMD_CLEAR_REGISTER	0x88
78 #define STEAM_CMD_READ_REGISTER		0x89
79 #define STEAM_CMD_GET_REGISTER_LABEL	0x8a
80 #define STEAM_CMD_GET_REGISTER_MAX	0x8b
81 #define STEAM_CMD_GET_REGISTER_DEFAULT	0x8c
82 #define STEAM_CMD_SET_MODE		0x8d
83 #define STEAM_CMD_DEFAULT_MOUSE		0x8e
84 #define STEAM_CMD_FORCEFEEDBAK		0x8f
85 #define STEAM_CMD_REQUEST_COMM_STATUS	0xb4
86 #define STEAM_CMD_GET_SERIAL		0xae
87 
88 /* Some useful register ids */
89 #define STEAM_REG_LPAD_MODE		0x07
90 #define STEAM_REG_RPAD_MODE		0x08
91 #define STEAM_REG_RPAD_MARGIN		0x18
92 #define STEAM_REG_LED			0x2d
93 #define STEAM_REG_GYRO_MODE		0x30
94 
95 /* Raw event identifiers */
96 #define STEAM_EV_INPUT_DATA		0x01
97 #define STEAM_EV_CONNECT		0x03
98 #define STEAM_EV_BATTERY		0x04
99 
100 /* Values for GYRO_MODE (bitmask) */
101 #define STEAM_GYRO_MODE_OFF		0x0000
102 #define STEAM_GYRO_MODE_STEERING	0x0001
103 #define STEAM_GYRO_MODE_TILT		0x0002
104 #define STEAM_GYRO_MODE_SEND_ORIENTATION	0x0004
105 #define STEAM_GYRO_MODE_SEND_RAW_ACCEL		0x0008
106 #define STEAM_GYRO_MODE_SEND_RAW_GYRO		0x0010
107 
108 /* Other random constants */
109 #define STEAM_SERIAL_LEN 10
110 
111 struct steam_device {
112 	struct list_head list;
113 	spinlock_t lock;
114 	struct hid_device *hdev, *client_hdev;
115 	struct mutex mutex;
116 	bool client_opened, input_opened;
117 	struct input_dev __rcu *input;
118 	unsigned long quirks;
119 	struct work_struct work_connect;
120 	bool connected;
121 	char serial_no[STEAM_SERIAL_LEN + 1];
122 	struct power_supply_desc battery_desc;
123 	struct power_supply __rcu *battery;
124 	u8 battery_charge;
125 	u16 voltage;
126 };
127 
128 static int steam_recv_report(struct steam_device *steam,
129 		u8 *data, int size)
130 {
131 	struct hid_report *r;
132 	u8 *buf;
133 	int ret;
134 
135 	r = steam->hdev->report_enum[HID_FEATURE_REPORT].report_id_hash[0];
136 	if (hid_report_len(r) < 64)
137 		return -EINVAL;
138 
139 	buf = hid_alloc_report_buf(r, GFP_KERNEL);
140 	if (!buf)
141 		return -ENOMEM;
142 
143 	/*
144 	 * The report ID is always 0, so strip the first byte from the output.
145 	 * hid_report_len() is not counting the report ID, so +1 to the length
146 	 * or else we get a EOVERFLOW. We are safe from a buffer overflow
147 	 * because hid_alloc_report_buf() allocates +7 bytes.
148 	 */
149 	ret = hid_hw_raw_request(steam->hdev, 0x00,
150 			buf, hid_report_len(r) + 1,
151 			HID_FEATURE_REPORT, HID_REQ_GET_REPORT);
152 	if (ret > 0)
153 		memcpy(data, buf + 1, min(size, ret - 1));
154 	kfree(buf);
155 	return ret;
156 }
157 
158 static int steam_send_report(struct steam_device *steam,
159 		u8 *cmd, int size)
160 {
161 	struct hid_report *r;
162 	u8 *buf;
163 	unsigned int retries = 50;
164 	int ret;
165 
166 	r = steam->hdev->report_enum[HID_FEATURE_REPORT].report_id_hash[0];
167 	if (hid_report_len(r) < 64)
168 		return -EINVAL;
169 
170 	buf = hid_alloc_report_buf(r, GFP_KERNEL);
171 	if (!buf)
172 		return -ENOMEM;
173 
174 	/* The report ID is always 0 */
175 	memcpy(buf + 1, cmd, size);
176 
177 	/*
178 	 * Sometimes the wireless controller fails with EPIPE
179 	 * when sending a feature report.
180 	 * Doing a HID_REQ_GET_REPORT and waiting for a while
181 	 * seems to fix that.
182 	 */
183 	do {
184 		ret = hid_hw_raw_request(steam->hdev, 0,
185 				buf, size + 1,
186 				HID_FEATURE_REPORT, HID_REQ_SET_REPORT);
187 		if (ret != -EPIPE)
188 			break;
189 		msleep(20);
190 	} while (--retries);
191 
192 	kfree(buf);
193 	if (ret < 0)
194 		hid_err(steam->hdev, "%s: error %d (%*ph)\n", __func__,
195 				ret, size, cmd);
196 	return ret;
197 }
198 
199 static inline int steam_send_report_byte(struct steam_device *steam, u8 cmd)
200 {
201 	return steam_send_report(steam, &cmd, 1);
202 }
203 
204 static int steam_write_registers(struct steam_device *steam,
205 		/* u8 reg, u16 val */...)
206 {
207 	/* Send: 0x87 len (reg valLo valHi)* */
208 	u8 reg;
209 	u16 val;
210 	u8 cmd[64] = {STEAM_CMD_WRITE_REGISTER, 0x00};
211 	va_list args;
212 
213 	va_start(args, steam);
214 	for (;;) {
215 		reg = va_arg(args, int);
216 		if (reg == 0)
217 			break;
218 		val = va_arg(args, int);
219 		cmd[cmd[1] + 2] = reg;
220 		cmd[cmd[1] + 3] = val & 0xff;
221 		cmd[cmd[1] + 4] = val >> 8;
222 		cmd[1] += 3;
223 	}
224 	va_end(args);
225 
226 	return steam_send_report(steam, cmd, 2 + cmd[1]);
227 }
228 
229 static int steam_get_serial(struct steam_device *steam)
230 {
231 	/*
232 	 * Send: 0xae 0x15 0x01
233 	 * Recv: 0xae 0x15 0x01 serialnumber (10 chars)
234 	 */
235 	int ret;
236 	u8 cmd[] = {STEAM_CMD_GET_SERIAL, 0x15, 0x01};
237 	u8 reply[3 + STEAM_SERIAL_LEN + 1];
238 
239 	ret = steam_send_report(steam, cmd, sizeof(cmd));
240 	if (ret < 0)
241 		return ret;
242 	ret = steam_recv_report(steam, reply, sizeof(reply));
243 	if (ret < 0)
244 		return ret;
245 	if (reply[0] != 0xae || reply[1] != 0x15 || reply[2] != 0x01)
246 		return -EIO;
247 	reply[3 + STEAM_SERIAL_LEN] = 0;
248 	strlcpy(steam->serial_no, reply + 3, sizeof(steam->serial_no));
249 	return 0;
250 }
251 
252 /*
253  * This command requests the wireless adaptor to post an event
254  * with the connection status. Useful if this driver is loaded when
255  * the controller is already connected.
256  */
257 static inline int steam_request_conn_status(struct steam_device *steam)
258 {
259 	return steam_send_report_byte(steam, STEAM_CMD_REQUEST_COMM_STATUS);
260 }
261 
262 static void steam_set_lizard_mode(struct steam_device *steam, bool enable)
263 {
264 	if (enable) {
265 		/* enable esc, enter, cursors */
266 		steam_send_report_byte(steam, STEAM_CMD_DEFAULT_MAPPINGS);
267 		/* enable mouse */
268 		steam_send_report_byte(steam, STEAM_CMD_DEFAULT_MOUSE);
269 		steam_write_registers(steam,
270 			STEAM_REG_RPAD_MARGIN, 0x01, /* enable margin */
271 			0);
272 	} else {
273 		/* disable esc, enter, cursor */
274 		steam_send_report_byte(steam, STEAM_CMD_CLEAR_MAPPINGS);
275 		steam_write_registers(steam,
276 			STEAM_REG_RPAD_MODE, 0x07, /* disable mouse */
277 			STEAM_REG_RPAD_MARGIN, 0x00, /* disable margin */
278 			0);
279 	}
280 }
281 
282 static void steam_update_lizard_mode(struct steam_device *steam)
283 {
284 	mutex_lock(&steam->mutex);
285 	if (!steam->client_opened) {
286 		if (steam->input_opened)
287 			steam_set_lizard_mode(steam, false);
288 		else
289 			steam_set_lizard_mode(steam, lizard_mode);
290 	}
291 	mutex_unlock(&steam->mutex);
292 }
293 
294 static int steam_input_open(struct input_dev *dev)
295 {
296 	struct steam_device *steam = input_get_drvdata(dev);
297 	int ret;
298 
299 	ret = hid_hw_open(steam->hdev);
300 	if (ret)
301 		return ret;
302 
303 	mutex_lock(&steam->mutex);
304 	steam->input_opened = true;
305 	if (!steam->client_opened && lizard_mode)
306 		steam_set_lizard_mode(steam, false);
307 	mutex_unlock(&steam->mutex);
308 	return 0;
309 }
310 
311 static void steam_input_close(struct input_dev *dev)
312 {
313 	struct steam_device *steam = input_get_drvdata(dev);
314 
315 	mutex_lock(&steam->mutex);
316 	steam->input_opened = false;
317 	if (!steam->client_opened && lizard_mode)
318 		steam_set_lizard_mode(steam, true);
319 	mutex_unlock(&steam->mutex);
320 
321 	hid_hw_close(steam->hdev);
322 }
323 
324 static enum power_supply_property steam_battery_props[] = {
325 	POWER_SUPPLY_PROP_PRESENT,
326 	POWER_SUPPLY_PROP_SCOPE,
327 	POWER_SUPPLY_PROP_VOLTAGE_NOW,
328 	POWER_SUPPLY_PROP_CAPACITY,
329 };
330 
331 static int steam_battery_get_property(struct power_supply *psy,
332 				enum power_supply_property psp,
333 				union power_supply_propval *val)
334 {
335 	struct steam_device *steam = power_supply_get_drvdata(psy);
336 	unsigned long flags;
337 	s16 volts;
338 	u8 batt;
339 	int ret = 0;
340 
341 	spin_lock_irqsave(&steam->lock, flags);
342 	volts = steam->voltage;
343 	batt = steam->battery_charge;
344 	spin_unlock_irqrestore(&steam->lock, flags);
345 
346 	switch (psp) {
347 	case POWER_SUPPLY_PROP_PRESENT:
348 		val->intval = 1;
349 		break;
350 	case POWER_SUPPLY_PROP_SCOPE:
351 		val->intval = POWER_SUPPLY_SCOPE_DEVICE;
352 		break;
353 	case POWER_SUPPLY_PROP_VOLTAGE_NOW:
354 		val->intval = volts * 1000; /* mV -> uV */
355 		break;
356 	case POWER_SUPPLY_PROP_CAPACITY:
357 		val->intval = batt;
358 		break;
359 	default:
360 		ret = -EINVAL;
361 		break;
362 	}
363 	return ret;
364 }
365 
366 static int steam_battery_register(struct steam_device *steam)
367 {
368 	struct power_supply *battery;
369 	struct power_supply_config battery_cfg = { .drv_data = steam, };
370 	unsigned long flags;
371 	int ret;
372 
373 	steam->battery_desc.type = POWER_SUPPLY_TYPE_BATTERY;
374 	steam->battery_desc.properties = steam_battery_props;
375 	steam->battery_desc.num_properties = ARRAY_SIZE(steam_battery_props);
376 	steam->battery_desc.get_property = steam_battery_get_property;
377 	steam->battery_desc.name = devm_kasprintf(&steam->hdev->dev,
378 			GFP_KERNEL, "steam-controller-%s-battery",
379 			steam->serial_no);
380 	if (!steam->battery_desc.name)
381 		return -ENOMEM;
382 
383 	/* avoid the warning of 0% battery while waiting for the first info */
384 	spin_lock_irqsave(&steam->lock, flags);
385 	steam->voltage = 3000;
386 	steam->battery_charge = 100;
387 	spin_unlock_irqrestore(&steam->lock, flags);
388 
389 	battery = power_supply_register(&steam->hdev->dev,
390 			&steam->battery_desc, &battery_cfg);
391 	if (IS_ERR(battery)) {
392 		ret = PTR_ERR(battery);
393 		hid_err(steam->hdev,
394 				"%s:power_supply_register failed with error %d\n",
395 				__func__, ret);
396 		return ret;
397 	}
398 	rcu_assign_pointer(steam->battery, battery);
399 	power_supply_powers(battery, &steam->hdev->dev);
400 	return 0;
401 }
402 
403 static int steam_register(struct steam_device *steam)
404 {
405 	struct hid_device *hdev = steam->hdev;
406 	struct input_dev *input;
407 	int ret;
408 
409 	rcu_read_lock();
410 	input = rcu_dereference(steam->input);
411 	rcu_read_unlock();
412 	if (input) {
413 		dbg_hid("%s: already connected\n", __func__);
414 		return 0;
415 	}
416 
417 	/*
418 	 * Unlikely, but getting the serial could fail, and it is not so
419 	 * important, so make up a serial number and go on.
420 	 */
421 	if (steam_get_serial(steam) < 0)
422 		strlcpy(steam->serial_no, "XXXXXXXXXX",
423 				sizeof(steam->serial_no));
424 
425 	hid_info(hdev, "Steam Controller '%s' connected",
426 			steam->serial_no);
427 
428 	input = input_allocate_device();
429 	if (!input)
430 		return -ENOMEM;
431 
432 	input_set_drvdata(input, steam);
433 	input->dev.parent = &hdev->dev;
434 	input->open = steam_input_open;
435 	input->close = steam_input_close;
436 
437 	input->name = (steam->quirks & STEAM_QUIRK_WIRELESS) ?
438 		"Wireless Steam Controller" :
439 		"Steam Controller";
440 	input->phys = hdev->phys;
441 	input->uniq = steam->serial_no;
442 	input->id.bustype = hdev->bus;
443 	input->id.vendor = hdev->vendor;
444 	input->id.product = hdev->product;
445 	input->id.version = hdev->version;
446 
447 	input_set_capability(input, EV_KEY, BTN_TR2);
448 	input_set_capability(input, EV_KEY, BTN_TL2);
449 	input_set_capability(input, EV_KEY, BTN_TR);
450 	input_set_capability(input, EV_KEY, BTN_TL);
451 	input_set_capability(input, EV_KEY, BTN_Y);
452 	input_set_capability(input, EV_KEY, BTN_B);
453 	input_set_capability(input, EV_KEY, BTN_X);
454 	input_set_capability(input, EV_KEY, BTN_A);
455 	input_set_capability(input, EV_KEY, BTN_DPAD_UP);
456 	input_set_capability(input, EV_KEY, BTN_DPAD_RIGHT);
457 	input_set_capability(input, EV_KEY, BTN_DPAD_LEFT);
458 	input_set_capability(input, EV_KEY, BTN_DPAD_DOWN);
459 	input_set_capability(input, EV_KEY, BTN_SELECT);
460 	input_set_capability(input, EV_KEY, BTN_MODE);
461 	input_set_capability(input, EV_KEY, BTN_START);
462 	input_set_capability(input, EV_KEY, BTN_GEAR_DOWN);
463 	input_set_capability(input, EV_KEY, BTN_GEAR_UP);
464 	input_set_capability(input, EV_KEY, BTN_THUMBR);
465 	input_set_capability(input, EV_KEY, BTN_THUMBL);
466 	input_set_capability(input, EV_KEY, BTN_THUMB);
467 	input_set_capability(input, EV_KEY, BTN_THUMB2);
468 
469 	input_set_abs_params(input, ABS_HAT2Y, 0, 255, 0, 0);
470 	input_set_abs_params(input, ABS_HAT2X, 0, 255, 0, 0);
471 	input_set_abs_params(input, ABS_X, -32767, 32767, 0, 0);
472 	input_set_abs_params(input, ABS_Y, -32767, 32767, 0, 0);
473 	input_set_abs_params(input, ABS_RX, -32767, 32767,
474 			STEAM_PAD_FUZZ, 0);
475 	input_set_abs_params(input, ABS_RY, -32767, 32767,
476 			STEAM_PAD_FUZZ, 0);
477 	input_set_abs_params(input, ABS_HAT0X, -32767, 32767,
478 			STEAM_PAD_FUZZ, 0);
479 	input_set_abs_params(input, ABS_HAT0Y, -32767, 32767,
480 			STEAM_PAD_FUZZ, 0);
481 	input_abs_set_res(input, ABS_X, STEAM_JOYSTICK_RESOLUTION);
482 	input_abs_set_res(input, ABS_Y, STEAM_JOYSTICK_RESOLUTION);
483 	input_abs_set_res(input, ABS_RX, STEAM_PAD_RESOLUTION);
484 	input_abs_set_res(input, ABS_RY, STEAM_PAD_RESOLUTION);
485 	input_abs_set_res(input, ABS_HAT0X, STEAM_PAD_RESOLUTION);
486 	input_abs_set_res(input, ABS_HAT0Y, STEAM_PAD_RESOLUTION);
487 	input_abs_set_res(input, ABS_HAT2Y, STEAM_TRIGGER_RESOLUTION);
488 	input_abs_set_res(input, ABS_HAT2X, STEAM_TRIGGER_RESOLUTION);
489 
490 	ret = input_register_device(input);
491 	if (ret)
492 		goto input_register_fail;
493 
494 	rcu_assign_pointer(steam->input, input);
495 
496 	/* ignore battery errors, we can live without it */
497 	if (steam->quirks & STEAM_QUIRK_WIRELESS)
498 		steam_battery_register(steam);
499 
500 	return 0;
501 
502 input_register_fail:
503 	input_free_device(input);
504 	return ret;
505 }
506 
507 static void steam_unregister(struct steam_device *steam)
508 {
509 	struct input_dev *input;
510 	struct power_supply *battery;
511 
512 	rcu_read_lock();
513 	input = rcu_dereference(steam->input);
514 	battery = rcu_dereference(steam->battery);
515 	rcu_read_unlock();
516 
517 	if (battery) {
518 		RCU_INIT_POINTER(steam->battery, NULL);
519 		synchronize_rcu();
520 		power_supply_unregister(battery);
521 	}
522 	if (input) {
523 		RCU_INIT_POINTER(steam->input, NULL);
524 		synchronize_rcu();
525 		hid_info(steam->hdev, "Steam Controller '%s' disconnected",
526 				steam->serial_no);
527 		input_unregister_device(input);
528 	}
529 }
530 
531 static void steam_work_connect_cb(struct work_struct *work)
532 {
533 	struct steam_device *steam = container_of(work, struct steam_device,
534 							work_connect);
535 	unsigned long flags;
536 	bool connected;
537 	int ret;
538 
539 	spin_lock_irqsave(&steam->lock, flags);
540 	connected = steam->connected;
541 	spin_unlock_irqrestore(&steam->lock, flags);
542 
543 	if (connected) {
544 		ret = steam_register(steam);
545 		if (ret) {
546 			hid_err(steam->hdev,
547 				"%s:steam_register failed with error %d\n",
548 				__func__, ret);
549 		}
550 	} else {
551 		steam_unregister(steam);
552 	}
553 }
554 
555 static bool steam_is_valve_interface(struct hid_device *hdev)
556 {
557 	struct hid_report_enum *rep_enum;
558 
559 	/*
560 	 * The wired device creates 3 interfaces:
561 	 *  0: emulated mouse.
562 	 *  1: emulated keyboard.
563 	 *  2: the real game pad.
564 	 * The wireless device creates 5 interfaces:
565 	 *  0: emulated keyboard.
566 	 *  1-4: slots where up to 4 real game pads will be connected to.
567 	 * We know which one is the real gamepad interface because they are the
568 	 * only ones with a feature report.
569 	 */
570 	rep_enum = &hdev->report_enum[HID_FEATURE_REPORT];
571 	return !list_empty(&rep_enum->report_list);
572 }
573 
574 static int steam_client_ll_parse(struct hid_device *hdev)
575 {
576 	struct steam_device *steam = hdev->driver_data;
577 
578 	return hid_parse_report(hdev, steam->hdev->dev_rdesc,
579 			steam->hdev->dev_rsize);
580 }
581 
582 static int steam_client_ll_start(struct hid_device *hdev)
583 {
584 	return 0;
585 }
586 
587 static void steam_client_ll_stop(struct hid_device *hdev)
588 {
589 }
590 
591 static int steam_client_ll_open(struct hid_device *hdev)
592 {
593 	struct steam_device *steam = hdev->driver_data;
594 	int ret;
595 
596 	ret = hid_hw_open(steam->hdev);
597 	if (ret)
598 		return ret;
599 
600 	mutex_lock(&steam->mutex);
601 	steam->client_opened = true;
602 	mutex_unlock(&steam->mutex);
603 	return ret;
604 }
605 
606 static void steam_client_ll_close(struct hid_device *hdev)
607 {
608 	struct steam_device *steam = hdev->driver_data;
609 
610 	mutex_lock(&steam->mutex);
611 	steam->client_opened = false;
612 	if (steam->input_opened)
613 		steam_set_lizard_mode(steam, false);
614 	else
615 		steam_set_lizard_mode(steam, lizard_mode);
616 	mutex_unlock(&steam->mutex);
617 
618 	hid_hw_close(steam->hdev);
619 }
620 
621 static int steam_client_ll_raw_request(struct hid_device *hdev,
622 				unsigned char reportnum, u8 *buf,
623 				size_t count, unsigned char report_type,
624 				int reqtype)
625 {
626 	struct steam_device *steam = hdev->driver_data;
627 
628 	return hid_hw_raw_request(steam->hdev, reportnum, buf, count,
629 			report_type, reqtype);
630 }
631 
632 static struct hid_ll_driver steam_client_ll_driver = {
633 	.parse = steam_client_ll_parse,
634 	.start = steam_client_ll_start,
635 	.stop = steam_client_ll_stop,
636 	.open = steam_client_ll_open,
637 	.close = steam_client_ll_close,
638 	.raw_request = steam_client_ll_raw_request,
639 };
640 
641 static struct hid_device *steam_create_client_hid(struct hid_device *hdev)
642 {
643 	struct hid_device *client_hdev;
644 
645 	client_hdev = hid_allocate_device();
646 	if (IS_ERR(client_hdev))
647 		return client_hdev;
648 
649 	client_hdev->ll_driver = &steam_client_ll_driver;
650 	client_hdev->dev.parent = hdev->dev.parent;
651 	client_hdev->bus = hdev->bus;
652 	client_hdev->vendor = hdev->vendor;
653 	client_hdev->product = hdev->product;
654 	client_hdev->version = hdev->version;
655 	client_hdev->type = hdev->type;
656 	client_hdev->country = hdev->country;
657 	strlcpy(client_hdev->name, hdev->name,
658 			sizeof(client_hdev->name));
659 	strlcpy(client_hdev->phys, hdev->phys,
660 			sizeof(client_hdev->phys));
661 	/*
662 	 * Since we use the same device info than the real interface to
663 	 * trick userspace, we will be calling steam_probe recursively.
664 	 * We need to recognize the client interface somehow.
665 	 */
666 	client_hdev->group = HID_GROUP_STEAM;
667 	return client_hdev;
668 }
669 
670 static int steam_probe(struct hid_device *hdev,
671 				const struct hid_device_id *id)
672 {
673 	struct steam_device *steam;
674 	int ret;
675 
676 	ret = hid_parse(hdev);
677 	if (ret) {
678 		hid_err(hdev,
679 			"%s:parse of hid interface failed\n", __func__);
680 		return ret;
681 	}
682 
683 	/*
684 	 * The virtual client_dev is only used for hidraw.
685 	 * Also avoid the recursive probe.
686 	 */
687 	if (hdev->group == HID_GROUP_STEAM)
688 		return hid_hw_start(hdev, HID_CONNECT_HIDRAW);
689 	/*
690 	 * The non-valve interfaces (mouse and keyboard emulation) are
691 	 * connected without changes.
692 	 */
693 	if (!steam_is_valve_interface(hdev))
694 		return hid_hw_start(hdev, HID_CONNECT_DEFAULT);
695 
696 	steam = devm_kzalloc(&hdev->dev, sizeof(*steam), GFP_KERNEL);
697 	if (!steam) {
698 		ret = -ENOMEM;
699 		goto steam_alloc_fail;
700 	}
701 	steam->hdev = hdev;
702 	hid_set_drvdata(hdev, steam);
703 	spin_lock_init(&steam->lock);
704 	mutex_init(&steam->mutex);
705 	steam->quirks = id->driver_data;
706 	INIT_WORK(&steam->work_connect, steam_work_connect_cb);
707 
708 	steam->client_hdev = steam_create_client_hid(hdev);
709 	if (IS_ERR(steam->client_hdev)) {
710 		ret = PTR_ERR(steam->client_hdev);
711 		goto client_hdev_fail;
712 	}
713 	steam->client_hdev->driver_data = steam;
714 
715 	/*
716 	 * With the real steam controller interface, do not connect hidraw.
717 	 * Instead, create the client_hid and connect that.
718 	 */
719 	ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT & ~HID_CONNECT_HIDRAW);
720 	if (ret)
721 		goto hid_hw_start_fail;
722 
723 	ret = hid_add_device(steam->client_hdev);
724 	if (ret)
725 		goto client_hdev_add_fail;
726 
727 	if (steam->quirks & STEAM_QUIRK_WIRELESS) {
728 		ret = hid_hw_open(hdev);
729 		if (ret) {
730 			hid_err(hdev,
731 				"%s:hid_hw_open for wireless\n",
732 				__func__);
733 			goto hid_hw_open_fail;
734 		}
735 		hid_info(hdev, "Steam wireless receiver connected");
736 		steam_request_conn_status(steam);
737 	} else {
738 		ret = steam_register(steam);
739 		if (ret) {
740 			hid_err(hdev,
741 				"%s:steam_register failed with error %d\n",
742 				__func__, ret);
743 			goto input_register_fail;
744 		}
745 	}
746 
747 	mutex_lock(&steam_devices_lock);
748 	steam_update_lizard_mode(steam);
749 	list_add(&steam->list, &steam_devices);
750 	mutex_unlock(&steam_devices_lock);
751 
752 	return 0;
753 
754 hid_hw_open_fail:
755 input_register_fail:
756 client_hdev_add_fail:
757 	hid_hw_stop(hdev);
758 hid_hw_start_fail:
759 	hid_destroy_device(steam->client_hdev);
760 client_hdev_fail:
761 	cancel_work_sync(&steam->work_connect);
762 steam_alloc_fail:
763 	hid_err(hdev, "%s: failed with error %d\n",
764 			__func__, ret);
765 	return ret;
766 }
767 
768 static void steam_remove(struct hid_device *hdev)
769 {
770 	struct steam_device *steam = hid_get_drvdata(hdev);
771 
772 	if (!steam || hdev->group == HID_GROUP_STEAM) {
773 		hid_hw_stop(hdev);
774 		return;
775 	}
776 
777 	mutex_lock(&steam_devices_lock);
778 	list_del(&steam->list);
779 	mutex_unlock(&steam_devices_lock);
780 
781 	hid_destroy_device(steam->client_hdev);
782 	steam->client_opened = false;
783 	cancel_work_sync(&steam->work_connect);
784 	if (steam->quirks & STEAM_QUIRK_WIRELESS) {
785 		hid_info(hdev, "Steam wireless receiver disconnected");
786 		hid_hw_close(hdev);
787 	}
788 	hid_hw_stop(hdev);
789 	steam_unregister(steam);
790 }
791 
792 static void steam_do_connect_event(struct steam_device *steam, bool connected)
793 {
794 	unsigned long flags;
795 
796 	spin_lock_irqsave(&steam->lock, flags);
797 	steam->connected = connected;
798 	spin_unlock_irqrestore(&steam->lock, flags);
799 
800 	if (schedule_work(&steam->work_connect) == 0)
801 		dbg_hid("%s: connected=%d event already queued\n",
802 				__func__, connected);
803 }
804 
805 /*
806  * Some input data in the protocol has the opposite sign.
807  * Clamp the values to 32767..-32767 so that the range is
808  * symmetrical and can be negated safely.
809  */
810 static inline s16 steam_le16(u8 *data)
811 {
812 	s16 x = (s16) le16_to_cpup((__le16 *)data);
813 
814 	return x == -32768 ? -32767 : x;
815 }
816 
817 /*
818  * The size for this message payload is 60.
819  * The known values are:
820  *  (* values are not sent through wireless)
821  *  (* accelerator/gyro is disabled by default)
822  *  Offset| Type  | Mapped to |Meaning
823  * -------+-------+-----------+--------------------------
824  *  4-7   | u32   | --        | sequence number
825  *  8-10  | 24bit | see below | buttons
826  *  11    | u8    | ABS_HAT2Y | left trigger
827  *  12    | u8    | ABS_HAT2X | right trigger
828  *  13-15 | --    | --        | always 0
829  *  16-17 | s16   | ABS_X/ABS_HAT0X     | X value
830  *  18-19 | s16   | ABS_Y/ABS_HAT0Y     | Y value
831  *  20-21 | s16   | ABS_RX    | right-pad X value
832  *  22-23 | s16   | ABS_RY    | right-pad Y value
833  *  24-25 | s16   | --        | * left trigger
834  *  26-27 | s16   | --        | * right trigger
835  *  28-29 | s16   | --        | * accelerometer X value
836  *  30-31 | s16   | --        | * accelerometer Y value
837  *  32-33 | s16   | --        | * accelerometer Z value
838  *  34-35 | s16   | --        | gyro X value
839  *  36-36 | s16   | --        | gyro Y value
840  *  38-39 | s16   | --        | gyro Z value
841  *  40-41 | s16   | --        | quaternion W value
842  *  42-43 | s16   | --        | quaternion X value
843  *  44-45 | s16   | --        | quaternion Y value
844  *  46-47 | s16   | --        | quaternion Z value
845  *  48-49 | --    | --        | always 0
846  *  50-51 | s16   | --        | * left trigger (uncalibrated)
847  *  52-53 | s16   | --        | * right trigger (uncalibrated)
848  *  54-55 | s16   | --        | * joystick X value (uncalibrated)
849  *  56-57 | s16   | --        | * joystick Y value (uncalibrated)
850  *  58-59 | s16   | --        | * left-pad X value
851  *  60-61 | s16   | --        | * left-pad Y value
852  *  62-63 | u16   | --        | * battery voltage
853  *
854  * The buttons are:
855  *  Bit  | Mapped to  | Description
856  * ------+------------+--------------------------------
857  *  8.0  | BTN_TR2    | right trigger fully pressed
858  *  8.1  | BTN_TL2    | left trigger fully pressed
859  *  8.2  | BTN_TR     | right shoulder
860  *  8.3  | BTN_TL     | left shoulder
861  *  8.4  | BTN_Y      | button Y
862  *  8.5  | BTN_B      | button B
863  *  8.6  | BTN_X      | button X
864  *  8.7  | BTN_A      | button A
865  *  9.0  | BTN_DPAD_UP    | lef-pad up
866  *  9.1  | BTN_DPAD_RIGHT | lef-pad right
867  *  9.2  | BTN_DPAD_LEFT  | lef-pad left
868  *  9.3  | BTN_DPAD_DOWN  | lef-pad down
869  *  9.4  | BTN_SELECT | menu left
870  *  9.5  | BTN_MODE   | steam logo
871  *  9.6  | BTN_START  | menu right
872  *  9.7  | BTN_GEAR_DOWN | left back lever
873  * 10.0  | BTN_GEAR_UP   | right back lever
874  * 10.1  | --         | left-pad clicked
875  * 10.2  | BTN_THUMBR | right-pad clicked
876  * 10.3  | BTN_THUMB  | left-pad touched (but see explanation below)
877  * 10.4  | BTN_THUMB2 | right-pad touched
878  * 10.5  | --         | unknown
879  * 10.6  | BTN_THUMBL | joystick clicked
880  * 10.7  | --         | lpad_and_joy
881  */
882 
883 static void steam_do_input_event(struct steam_device *steam,
884 		struct input_dev *input, u8 *data)
885 {
886 	/* 24 bits of buttons */
887 	u8 b8, b9, b10;
888 	s16 x, y;
889 	bool lpad_touched, lpad_and_joy;
890 
891 	b8 = data[8];
892 	b9 = data[9];
893 	b10 = data[10];
894 
895 	input_report_abs(input, ABS_HAT2Y, data[11]);
896 	input_report_abs(input, ABS_HAT2X, data[12]);
897 
898 	/*
899 	 * These two bits tells how to interpret the values X and Y.
900 	 * lpad_and_joy tells that the joystick and the lpad are used at the
901 	 * same time.
902 	 * lpad_touched tells whether X/Y are to be read as lpad coord or
903 	 * joystick values.
904 	 * (lpad_touched || lpad_and_joy) tells if the lpad is really touched.
905 	 */
906 	lpad_touched = b10 & BIT(3);
907 	lpad_and_joy = b10 & BIT(7);
908 	x = steam_le16(data + 16);
909 	y = -steam_le16(data + 18);
910 
911 	input_report_abs(input, lpad_touched ? ABS_HAT0X : ABS_X, x);
912 	input_report_abs(input, lpad_touched ? ABS_HAT0Y : ABS_Y, y);
913 	/* Check if joystick is centered */
914 	if (lpad_touched && !lpad_and_joy) {
915 		input_report_abs(input, ABS_X, 0);
916 		input_report_abs(input, ABS_Y, 0);
917 	}
918 	/* Check if lpad is untouched */
919 	if (!(lpad_touched || lpad_and_joy)) {
920 		input_report_abs(input, ABS_HAT0X, 0);
921 		input_report_abs(input, ABS_HAT0Y, 0);
922 	}
923 
924 	input_report_abs(input, ABS_RX, steam_le16(data + 20));
925 	input_report_abs(input, ABS_RY, -steam_le16(data + 22));
926 
927 	input_event(input, EV_KEY, BTN_TR2, !!(b8 & BIT(0)));
928 	input_event(input, EV_KEY, BTN_TL2, !!(b8 & BIT(1)));
929 	input_event(input, EV_KEY, BTN_TR, !!(b8 & BIT(2)));
930 	input_event(input, EV_KEY, BTN_TL, !!(b8 & BIT(3)));
931 	input_event(input, EV_KEY, BTN_Y, !!(b8 & BIT(4)));
932 	input_event(input, EV_KEY, BTN_B, !!(b8 & BIT(5)));
933 	input_event(input, EV_KEY, BTN_X, !!(b8 & BIT(6)));
934 	input_event(input, EV_KEY, BTN_A, !!(b8 & BIT(7)));
935 	input_event(input, EV_KEY, BTN_SELECT, !!(b9 & BIT(4)));
936 	input_event(input, EV_KEY, BTN_MODE, !!(b9 & BIT(5)));
937 	input_event(input, EV_KEY, BTN_START, !!(b9 & BIT(6)));
938 	input_event(input, EV_KEY, BTN_GEAR_DOWN, !!(b9 & BIT(7)));
939 	input_event(input, EV_KEY, BTN_GEAR_UP, !!(b10 & BIT(0)));
940 	input_event(input, EV_KEY, BTN_THUMBR, !!(b10 & BIT(2)));
941 	input_event(input, EV_KEY, BTN_THUMBL, !!(b10 & BIT(6)));
942 	input_event(input, EV_KEY, BTN_THUMB, lpad_touched || lpad_and_joy);
943 	input_event(input, EV_KEY, BTN_THUMB2, !!(b10 & BIT(4)));
944 	input_event(input, EV_KEY, BTN_DPAD_UP, !!(b9 & BIT(0)));
945 	input_event(input, EV_KEY, BTN_DPAD_RIGHT, !!(b9 & BIT(1)));
946 	input_event(input, EV_KEY, BTN_DPAD_LEFT, !!(b9 & BIT(2)));
947 	input_event(input, EV_KEY, BTN_DPAD_DOWN, !!(b9 & BIT(3)));
948 
949 	input_sync(input);
950 }
951 
952 /*
953  * The size for this message payload is 11.
954  * The known values are:
955  *  Offset| Type  | Meaning
956  * -------+-------+---------------------------
957  *  4-7   | u32   | sequence number
958  *  8-11  | --    | always 0
959  *  12-13 | u16   | voltage (mV)
960  *  14    | u8    | battery percent
961  */
962 static void steam_do_battery_event(struct steam_device *steam,
963 		struct power_supply *battery, u8 *data)
964 {
965 	unsigned long flags;
966 
967 	s16 volts = steam_le16(data + 12);
968 	u8 batt = data[14];
969 
970 	/* Creating the battery may have failed */
971 	rcu_read_lock();
972 	battery = rcu_dereference(steam->battery);
973 	if (likely(battery)) {
974 		spin_lock_irqsave(&steam->lock, flags);
975 		steam->voltage = volts;
976 		steam->battery_charge = batt;
977 		spin_unlock_irqrestore(&steam->lock, flags);
978 		power_supply_changed(battery);
979 	}
980 	rcu_read_unlock();
981 }
982 
983 static int steam_raw_event(struct hid_device *hdev,
984 			struct hid_report *report, u8 *data,
985 			int size)
986 {
987 	struct steam_device *steam = hid_get_drvdata(hdev);
988 	struct input_dev *input;
989 	struct power_supply *battery;
990 
991 	if (!steam)
992 		return 0;
993 
994 	if (steam->client_opened)
995 		hid_input_report(steam->client_hdev, HID_FEATURE_REPORT,
996 				data, size, 0);
997 	/*
998 	 * All messages are size=64, all values little-endian.
999 	 * The format is:
1000 	 *  Offset| Meaning
1001 	 * -------+--------------------------------------------
1002 	 *  0-1   | always 0x01, 0x00, maybe protocol version?
1003 	 *  2     | type of message
1004 	 *  3     | length of the real payload (not checked)
1005 	 *  4-n   | payload data, depends on the type
1006 	 *
1007 	 * There are these known types of message:
1008 	 *  0x01: input data (60 bytes)
1009 	 *  0x03: wireless connect/disconnect (1 byte)
1010 	 *  0x04: battery status (11 bytes)
1011 	 */
1012 
1013 	if (size != 64 || data[0] != 1 || data[1] != 0)
1014 		return 0;
1015 
1016 	switch (data[2]) {
1017 	case STEAM_EV_INPUT_DATA:
1018 		if (steam->client_opened)
1019 			return 0;
1020 		rcu_read_lock();
1021 		input = rcu_dereference(steam->input);
1022 		if (likely(input)) {
1023 			steam_do_input_event(steam, input, data);
1024 		} else {
1025 			dbg_hid("%s: input data without connect event\n",
1026 					__func__);
1027 			steam_do_connect_event(steam, true);
1028 		}
1029 		rcu_read_unlock();
1030 		break;
1031 	case STEAM_EV_CONNECT:
1032 		/*
1033 		 * The payload of this event is a single byte:
1034 		 *  0x01: disconnected.
1035 		 *  0x02: connected.
1036 		 */
1037 		switch (data[4]) {
1038 		case 0x01:
1039 			steam_do_connect_event(steam, false);
1040 			break;
1041 		case 0x02:
1042 			steam_do_connect_event(steam, true);
1043 			break;
1044 		}
1045 		break;
1046 	case STEAM_EV_BATTERY:
1047 		if (steam->quirks & STEAM_QUIRK_WIRELESS) {
1048 			rcu_read_lock();
1049 			battery = rcu_dereference(steam->battery);
1050 			if (likely(battery)) {
1051 				steam_do_battery_event(steam, battery, data);
1052 			} else {
1053 				dbg_hid(
1054 					"%s: battery data without connect event\n",
1055 					__func__);
1056 				steam_do_connect_event(steam, true);
1057 			}
1058 			rcu_read_unlock();
1059 		}
1060 		break;
1061 	}
1062 	return 0;
1063 }
1064 
1065 static int steam_param_set_lizard_mode(const char *val,
1066 					const struct kernel_param *kp)
1067 {
1068 	struct steam_device *steam;
1069 	int ret;
1070 
1071 	ret = param_set_bool(val, kp);
1072 	if (ret)
1073 		return ret;
1074 
1075 	mutex_lock(&steam_devices_lock);
1076 	list_for_each_entry(steam, &steam_devices, list) {
1077 		steam_update_lizard_mode(steam);
1078 	}
1079 	mutex_unlock(&steam_devices_lock);
1080 	return 0;
1081 }
1082 
1083 static const struct kernel_param_ops steam_lizard_mode_ops = {
1084 	.set	= steam_param_set_lizard_mode,
1085 	.get	= param_get_bool,
1086 };
1087 
1088 module_param_cb(lizard_mode, &steam_lizard_mode_ops, &lizard_mode, 0644);
1089 MODULE_PARM_DESC(lizard_mode,
1090 	"Enable mouse and keyboard emulation (lizard mode) when the gamepad is not in use");
1091 
1092 static const struct hid_device_id steam_controllers[] = {
1093 	{ /* Wired Steam Controller */
1094 	  HID_USB_DEVICE(USB_VENDOR_ID_VALVE,
1095 		USB_DEVICE_ID_STEAM_CONTROLLER)
1096 	},
1097 	{ /* Wireless Steam Controller */
1098 	  HID_USB_DEVICE(USB_VENDOR_ID_VALVE,
1099 		USB_DEVICE_ID_STEAM_CONTROLLER_WIRELESS),
1100 	  .driver_data = STEAM_QUIRK_WIRELESS
1101 	},
1102 	{}
1103 };
1104 
1105 MODULE_DEVICE_TABLE(hid, steam_controllers);
1106 
1107 static struct hid_driver steam_controller_driver = {
1108 	.name = "hid-steam",
1109 	.id_table = steam_controllers,
1110 	.probe = steam_probe,
1111 	.remove = steam_remove,
1112 	.raw_event = steam_raw_event,
1113 };
1114 
1115 module_hid_driver(steam_controller_driver);
1116