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