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