1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * keyspan_remote: USB driver for the Keyspan DMR
4  *
5  * Copyright (C) 2005 Zymeta Corporation - Michael Downey (downey@zymeta.com)
6  *
7  * This driver has been put together with the support of Innosys, Inc.
8  * and Keyspan, Inc the manufacturers of the Keyspan USB DMR product.
9  */
10 
11 #include <linux/kernel.h>
12 #include <linux/errno.h>
13 #include <linux/slab.h>
14 #include <linux/module.h>
15 #include <linux/usb/input.h>
16 
17 /* Parameters that can be passed to the driver. */
18 static int debug;
19 module_param(debug, int, 0444);
20 MODULE_PARM_DESC(debug, "Enable extra debug messages and information");
21 
22 /* Vendor and product ids */
23 #define USB_KEYSPAN_VENDOR_ID		0x06CD
24 #define USB_KEYSPAN_PRODUCT_UIA11	0x0202
25 
26 /* Defines for converting the data from the remote. */
27 #define ZERO		0x18
28 #define ZERO_MASK	0x1F	/* 5 bits for a 0 */
29 #define ONE		0x3C
30 #define ONE_MASK	0x3F	/* 6 bits for a 1 */
31 #define SYNC		0x3F80
32 #define SYNC_MASK	0x3FFF	/* 14 bits for a SYNC sequence */
33 #define STOP		0x00
34 #define STOP_MASK	0x1F	/* 5 bits for the STOP sequence */
35 #define GAP		0xFF
36 
37 #define RECV_SIZE	8	/* The UIA-11 type have a 8 byte limit. */
38 
39 /*
40  * Table that maps the 31 possible keycodes to input keys.
41  * Currently there are 15 and 17 button models so RESERVED codes
42  * are blank areas in the mapping.
43  */
44 static const unsigned short keyspan_key_table[] = {
45 	KEY_RESERVED,		/* 0 is just a place holder. */
46 	KEY_RESERVED,
47 	KEY_STOP,
48 	KEY_PLAYCD,
49 	KEY_RESERVED,
50 	KEY_PREVIOUSSONG,
51 	KEY_REWIND,
52 	KEY_FORWARD,
53 	KEY_NEXTSONG,
54 	KEY_RESERVED,
55 	KEY_RESERVED,
56 	KEY_RESERVED,
57 	KEY_PAUSE,
58 	KEY_VOLUMEUP,
59 	KEY_RESERVED,
60 	KEY_RESERVED,
61 	KEY_RESERVED,
62 	KEY_VOLUMEDOWN,
63 	KEY_RESERVED,
64 	KEY_UP,
65 	KEY_RESERVED,
66 	KEY_MUTE,
67 	KEY_LEFT,
68 	KEY_ENTER,
69 	KEY_RIGHT,
70 	KEY_RESERVED,
71 	KEY_RESERVED,
72 	KEY_DOWN,
73 	KEY_RESERVED,
74 	KEY_KPASTERISK,
75 	KEY_RESERVED,
76 	KEY_MENU
77 };
78 
79 /* table of devices that work with this driver */
80 static const struct usb_device_id keyspan_table[] = {
81 	{ USB_DEVICE(USB_KEYSPAN_VENDOR_ID, USB_KEYSPAN_PRODUCT_UIA11) },
82 	{ }					/* Terminating entry */
83 };
84 
85 /* Structure to store all the real stuff that a remote sends to us. */
86 struct keyspan_message {
87 	u16	system;
88 	u8	button;
89 	u8	toggle;
90 };
91 
92 /* Structure used for all the bit testing magic needed to be done. */
93 struct bit_tester {
94 	u32	tester;
95 	int	len;
96 	int	pos;
97 	int	bits_left;
98 	u8	buffer[32];
99 };
100 
101 /* Structure to hold all of our driver specific stuff */
102 struct usb_keyspan {
103 	char				name[128];
104 	char				phys[64];
105 	unsigned short			keymap[ARRAY_SIZE(keyspan_key_table)];
106 	struct usb_device		*udev;
107 	struct input_dev		*input;
108 	struct usb_interface		*interface;
109 	struct usb_endpoint_descriptor	*in_endpoint;
110 	struct urb*			irq_urb;
111 	int				open;
112 	dma_addr_t			in_dma;
113 	unsigned char			*in_buffer;
114 
115 	/* variables used to parse messages from remote. */
116 	struct bit_tester		data;
117 	int				stage;
118 	int				toggle;
119 };
120 
121 static struct usb_driver keyspan_driver;
122 
123 /*
124  * Debug routine that prints out what we've received from the remote.
125  */
126 static void keyspan_print(struct usb_keyspan* dev) /*unsigned char* data)*/
127 {
128 	char codes[4 * RECV_SIZE];
129 	int i;
130 
131 	for (i = 0; i < RECV_SIZE; i++)
132 		snprintf(codes + i * 3, 4, "%02x ", dev->in_buffer[i]);
133 
134 	dev_info(&dev->udev->dev, "%s\n", codes);
135 }
136 
137 /*
138  * Routine that manages the bit_tester structure.  It makes sure that there are
139  * at least bits_needed bits loaded into the tester.
140  */
141 static int keyspan_load_tester(struct usb_keyspan* dev, int bits_needed)
142 {
143 	if (dev->data.bits_left >= bits_needed)
144 		return 0;
145 
146 	/*
147 	 * Somehow we've missed the last message. The message will be repeated
148 	 * though so it's not too big a deal
149 	 */
150 	if (dev->data.pos >= dev->data.len) {
151 		dev_dbg(&dev->interface->dev,
152 			"%s - Error ran out of data. pos: %d, len: %d\n",
153 			__func__, dev->data.pos, dev->data.len);
154 		return -1;
155 	}
156 
157 	/* Load as much as we can into the tester. */
158 	while ((dev->data.bits_left + 7 < (sizeof(dev->data.tester) * 8)) &&
159 	       (dev->data.pos < dev->data.len)) {
160 		dev->data.tester += (dev->data.buffer[dev->data.pos++] << dev->data.bits_left);
161 		dev->data.bits_left += 8;
162 	}
163 
164 	return 0;
165 }
166 
167 static void keyspan_report_button(struct usb_keyspan *remote, int button, int press)
168 {
169 	struct input_dev *input = remote->input;
170 
171 	input_event(input, EV_MSC, MSC_SCAN, button);
172 	input_report_key(input, remote->keymap[button], press);
173 	input_sync(input);
174 }
175 
176 /*
177  * Routine that handles all the logic needed to parse out the message from the remote.
178  */
179 static void keyspan_check_data(struct usb_keyspan *remote)
180 {
181 	int i;
182 	int found = 0;
183 	struct keyspan_message message;
184 
185 	switch(remote->stage) {
186 	case 0:
187 		/*
188 		 * In stage 0 we want to find the start of a message.  The remote sends a 0xFF as filler.
189 		 * So the first byte that isn't a FF should be the start of a new message.
190 		 */
191 		for (i = 0; i < RECV_SIZE && remote->in_buffer[i] == GAP; ++i);
192 
193 		if (i < RECV_SIZE) {
194 			memcpy(remote->data.buffer, remote->in_buffer, RECV_SIZE);
195 			remote->data.len = RECV_SIZE;
196 			remote->data.pos = 0;
197 			remote->data.tester = 0;
198 			remote->data.bits_left = 0;
199 			remote->stage = 1;
200 		}
201 		break;
202 
203 	case 1:
204 		/*
205 		 * Stage 1 we should have 16 bytes and should be able to detect a
206 		 * SYNC.  The SYNC is 14 bits, 7 0's and then 7 1's.
207 		 */
208 		memcpy(remote->data.buffer + remote->data.len, remote->in_buffer, RECV_SIZE);
209 		remote->data.len += RECV_SIZE;
210 
211 		found = 0;
212 		while ((remote->data.bits_left >= 14 || remote->data.pos < remote->data.len) && !found) {
213 			for (i = 0; i < 8; ++i) {
214 				if (keyspan_load_tester(remote, 14) != 0) {
215 					remote->stage = 0;
216 					return;
217 				}
218 
219 				if ((remote->data.tester & SYNC_MASK) == SYNC) {
220 					remote->data.tester = remote->data.tester >> 14;
221 					remote->data.bits_left -= 14;
222 					found = 1;
223 					break;
224 				} else {
225 					remote->data.tester = remote->data.tester >> 1;
226 					--remote->data.bits_left;
227 				}
228 			}
229 		}
230 
231 		if (!found) {
232 			remote->stage = 0;
233 			remote->data.len = 0;
234 		} else {
235 			remote->stage = 2;
236 		}
237 		break;
238 
239 	case 2:
240 		/*
241 		 * Stage 2 we should have 24 bytes which will be enough for a full
242 		 * message.  We need to parse out the system code, button code,
243 		 * toggle code, and stop.
244 		 */
245 		memcpy(remote->data.buffer + remote->data.len, remote->in_buffer, RECV_SIZE);
246 		remote->data.len += RECV_SIZE;
247 
248 		message.system = 0;
249 		for (i = 0; i < 9; i++) {
250 			keyspan_load_tester(remote, 6);
251 
252 			if ((remote->data.tester & ZERO_MASK) == ZERO) {
253 				message.system = message.system << 1;
254 				remote->data.tester = remote->data.tester >> 5;
255 				remote->data.bits_left -= 5;
256 			} else if ((remote->data.tester & ONE_MASK) == ONE) {
257 				message.system = (message.system << 1) + 1;
258 				remote->data.tester = remote->data.tester >> 6;
259 				remote->data.bits_left -= 6;
260 			} else {
261 				dev_err(&remote->interface->dev,
262 					"%s - Unknown sequence found in system data.\n",
263 					__func__);
264 				remote->stage = 0;
265 				return;
266 			}
267 		}
268 
269 		message.button = 0;
270 		for (i = 0; i < 5; i++) {
271 			keyspan_load_tester(remote, 6);
272 
273 			if ((remote->data.tester & ZERO_MASK) == ZERO) {
274 				message.button = message.button << 1;
275 				remote->data.tester = remote->data.tester >> 5;
276 				remote->data.bits_left -= 5;
277 			} else if ((remote->data.tester & ONE_MASK) == ONE) {
278 				message.button = (message.button << 1) + 1;
279 				remote->data.tester = remote->data.tester >> 6;
280 				remote->data.bits_left -= 6;
281 			} else {
282 				dev_err(&remote->interface->dev,
283 					"%s - Unknown sequence found in button data.\n",
284 					__func__);
285 				remote->stage = 0;
286 				return;
287 			}
288 		}
289 
290 		keyspan_load_tester(remote, 6);
291 		if ((remote->data.tester & ZERO_MASK) == ZERO) {
292 			message.toggle = 0;
293 			remote->data.tester = remote->data.tester >> 5;
294 			remote->data.bits_left -= 5;
295 		} else if ((remote->data.tester & ONE_MASK) == ONE) {
296 			message.toggle = 1;
297 			remote->data.tester = remote->data.tester >> 6;
298 			remote->data.bits_left -= 6;
299 		} else {
300 			dev_err(&remote->interface->dev,
301 				"%s - Error in message, invalid toggle.\n",
302 				__func__);
303 			remote->stage = 0;
304 			return;
305 		}
306 
307 		keyspan_load_tester(remote, 5);
308 		if ((remote->data.tester & STOP_MASK) == STOP) {
309 			remote->data.tester = remote->data.tester >> 5;
310 			remote->data.bits_left -= 5;
311 		} else {
312 			dev_err(&remote->interface->dev,
313 				"Bad message received, no stop bit found.\n");
314 		}
315 
316 		dev_dbg(&remote->interface->dev,
317 			"%s found valid message: system: %d, button: %d, toggle: %d\n",
318 			__func__, message.system, message.button, message.toggle);
319 
320 		if (message.toggle != remote->toggle) {
321 			keyspan_report_button(remote, message.button, 1);
322 			keyspan_report_button(remote, message.button, 0);
323 			remote->toggle = message.toggle;
324 		}
325 
326 		remote->stage = 0;
327 		break;
328 	}
329 }
330 
331 /*
332  * Routine for sending all the initialization messages to the remote.
333  */
334 static int keyspan_setup(struct usb_device* dev)
335 {
336 	int retval = 0;
337 
338 	retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
339 				 0x11, 0x40, 0x5601, 0x0, NULL, 0, 0);
340 	if (retval) {
341 		dev_dbg(&dev->dev, "%s - failed to set bit rate due to error: %d\n",
342 			__func__, retval);
343 		return(retval);
344 	}
345 
346 	retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
347 				 0x44, 0x40, 0x0, 0x0, NULL, 0, 0);
348 	if (retval) {
349 		dev_dbg(&dev->dev, "%s - failed to set resume sensitivity due to error: %d\n",
350 			__func__, retval);
351 		return(retval);
352 	}
353 
354 	retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
355 				 0x22, 0x40, 0x0, 0x0, NULL, 0, 0);
356 	if (retval) {
357 		dev_dbg(&dev->dev, "%s - failed to turn receive on due to error: %d\n",
358 			__func__, retval);
359 		return(retval);
360 	}
361 
362 	dev_dbg(&dev->dev, "%s - Setup complete.\n", __func__);
363 	return(retval);
364 }
365 
366 /*
367  * Routine used to handle a new message that has come in.
368  */
369 static void keyspan_irq_recv(struct urb *urb)
370 {
371 	struct usb_keyspan *dev = urb->context;
372 	int retval;
373 
374 	/* Check our status in case we need to bail out early. */
375 	switch (urb->status) {
376 	case 0:
377 		break;
378 
379 	/* Device went away so don't keep trying to read from it. */
380 	case -ECONNRESET:
381 	case -ENOENT:
382 	case -ESHUTDOWN:
383 		return;
384 
385 	default:
386 		goto resubmit;
387 	}
388 
389 	if (debug)
390 		keyspan_print(dev);
391 
392 	keyspan_check_data(dev);
393 
394 resubmit:
395 	retval = usb_submit_urb(urb, GFP_ATOMIC);
396 	if (retval)
397 		dev_err(&dev->interface->dev,
398 			"%s - usb_submit_urb failed with result: %d\n",
399 			__func__, retval);
400 }
401 
402 static int keyspan_open(struct input_dev *dev)
403 {
404 	struct usb_keyspan *remote = input_get_drvdata(dev);
405 
406 	remote->irq_urb->dev = remote->udev;
407 	if (usb_submit_urb(remote->irq_urb, GFP_KERNEL))
408 		return -EIO;
409 
410 	return 0;
411 }
412 
413 static void keyspan_close(struct input_dev *dev)
414 {
415 	struct usb_keyspan *remote = input_get_drvdata(dev);
416 
417 	usb_kill_urb(remote->irq_urb);
418 }
419 
420 static struct usb_endpoint_descriptor *keyspan_get_in_endpoint(struct usb_host_interface *iface)
421 {
422 
423 	struct usb_endpoint_descriptor *endpoint;
424 	int i;
425 
426 	for (i = 0; i < iface->desc.bNumEndpoints; ++i) {
427 		endpoint = &iface->endpoint[i].desc;
428 
429 		if (usb_endpoint_is_int_in(endpoint)) {
430 			/* we found our interrupt in endpoint */
431 			return endpoint;
432 		}
433 	}
434 
435 	return NULL;
436 }
437 
438 /*
439  * Routine that sets up the driver to handle a specific USB device detected on the bus.
440  */
441 static int keyspan_probe(struct usb_interface *interface, const struct usb_device_id *id)
442 {
443 	struct usb_device *udev = interface_to_usbdev(interface);
444 	struct usb_endpoint_descriptor *endpoint;
445 	struct usb_keyspan *remote;
446 	struct input_dev *input_dev;
447 	int i, error;
448 
449 	endpoint = keyspan_get_in_endpoint(interface->cur_altsetting);
450 	if (!endpoint)
451 		return -ENODEV;
452 
453 	remote = kzalloc(sizeof(*remote), GFP_KERNEL);
454 	input_dev = input_allocate_device();
455 	if (!remote || !input_dev) {
456 		error = -ENOMEM;
457 		goto fail1;
458 	}
459 
460 	remote->udev = udev;
461 	remote->input = input_dev;
462 	remote->interface = interface;
463 	remote->in_endpoint = endpoint;
464 	remote->toggle = -1;	/* Set to -1 so we will always not match the toggle from the first remote message. */
465 
466 	remote->in_buffer = usb_alloc_coherent(udev, RECV_SIZE, GFP_KERNEL, &remote->in_dma);
467 	if (!remote->in_buffer) {
468 		error = -ENOMEM;
469 		goto fail1;
470 	}
471 
472 	remote->irq_urb = usb_alloc_urb(0, GFP_KERNEL);
473 	if (!remote->irq_urb) {
474 		error = -ENOMEM;
475 		goto fail2;
476 	}
477 
478 	error = keyspan_setup(udev);
479 	if (error) {
480 		error = -ENODEV;
481 		goto fail3;
482 	}
483 
484 	if (udev->manufacturer)
485 		strlcpy(remote->name, udev->manufacturer, sizeof(remote->name));
486 
487 	if (udev->product) {
488 		if (udev->manufacturer)
489 			strlcat(remote->name, " ", sizeof(remote->name));
490 		strlcat(remote->name, udev->product, sizeof(remote->name));
491 	}
492 
493 	if (!strlen(remote->name))
494 		snprintf(remote->name, sizeof(remote->name),
495 			 "USB Keyspan Remote %04x:%04x",
496 			 le16_to_cpu(udev->descriptor.idVendor),
497 			 le16_to_cpu(udev->descriptor.idProduct));
498 
499 	usb_make_path(udev, remote->phys, sizeof(remote->phys));
500 	strlcat(remote->phys, "/input0", sizeof(remote->phys));
501 	memcpy(remote->keymap, keyspan_key_table, sizeof(remote->keymap));
502 
503 	input_dev->name = remote->name;
504 	input_dev->phys = remote->phys;
505 	usb_to_input_id(udev, &input_dev->id);
506 	input_dev->dev.parent = &interface->dev;
507 	input_dev->keycode = remote->keymap;
508 	input_dev->keycodesize = sizeof(unsigned short);
509 	input_dev->keycodemax = ARRAY_SIZE(remote->keymap);
510 
511 	input_set_capability(input_dev, EV_MSC, MSC_SCAN);
512 	__set_bit(EV_KEY, input_dev->evbit);
513 	for (i = 0; i < ARRAY_SIZE(keyspan_key_table); i++)
514 		__set_bit(keyspan_key_table[i], input_dev->keybit);
515 	__clear_bit(KEY_RESERVED, input_dev->keybit);
516 
517 	input_set_drvdata(input_dev, remote);
518 
519 	input_dev->open = keyspan_open;
520 	input_dev->close = keyspan_close;
521 
522 	/*
523 	 * Initialize the URB to access the device.
524 	 * The urb gets sent to the device in keyspan_open()
525 	 */
526 	usb_fill_int_urb(remote->irq_urb,
527 			 remote->udev,
528 			 usb_rcvintpipe(remote->udev, endpoint->bEndpointAddress),
529 			 remote->in_buffer, RECV_SIZE, keyspan_irq_recv, remote,
530 			 endpoint->bInterval);
531 	remote->irq_urb->transfer_dma = remote->in_dma;
532 	remote->irq_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
533 
534 	/* we can register the device now, as it is ready */
535 	error = input_register_device(remote->input);
536 	if (error)
537 		goto fail3;
538 
539 	/* save our data pointer in this interface device */
540 	usb_set_intfdata(interface, remote);
541 
542 	return 0;
543 
544  fail3:	usb_free_urb(remote->irq_urb);
545  fail2:	usb_free_coherent(udev, RECV_SIZE, remote->in_buffer, remote->in_dma);
546  fail1:	kfree(remote);
547 	input_free_device(input_dev);
548 
549 	return error;
550 }
551 
552 /*
553  * Routine called when a device is disconnected from the USB.
554  */
555 static void keyspan_disconnect(struct usb_interface *interface)
556 {
557 	struct usb_keyspan *remote;
558 
559 	remote = usb_get_intfdata(interface);
560 	usb_set_intfdata(interface, NULL);
561 
562 	if (remote) {	/* We have a valid driver structure so clean up everything we allocated. */
563 		input_unregister_device(remote->input);
564 		usb_kill_urb(remote->irq_urb);
565 		usb_free_urb(remote->irq_urb);
566 		usb_free_coherent(remote->udev, RECV_SIZE, remote->in_buffer, remote->in_dma);
567 		kfree(remote);
568 	}
569 }
570 
571 /*
572  * Standard driver set up sections
573  */
574 static struct usb_driver keyspan_driver =
575 {
576 	.name =		"keyspan_remote",
577 	.probe =	keyspan_probe,
578 	.disconnect =	keyspan_disconnect,
579 	.id_table =	keyspan_table
580 };
581 
582 module_usb_driver(keyspan_driver);
583 
584 MODULE_DEVICE_TABLE(usb, keyspan_table);
585 MODULE_AUTHOR("Michael Downey <downey@zymeta.com>");
586 MODULE_DESCRIPTION("Driver for the USB Keyspan remote control.");
587 MODULE_LICENSE("GPL");
588