1/*
2 * Driver for Meywa-Denki & KAYAC YUREX
3 *
4 * Copyright (C) 2010 Tomoki Sekiyama (tomoki.sekiyama@gmail.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 */
11
12#include <linux/kernel.h>
13#include <linux/errno.h>
14#include <linux/init.h>
15#include <linux/slab.h>
16#include <linux/module.h>
17#include <linux/kref.h>
18#include <linux/mutex.h>
19#include <linux/uaccess.h>
20#include <linux/usb.h>
21#include <linux/hid.h>
22
23#define DRIVER_AUTHOR "Tomoki Sekiyama"
24#define DRIVER_DESC "Driver for Meywa-Denki & KAYAC YUREX"
25
26#define YUREX_VENDOR_ID		0x0c45
27#define YUREX_PRODUCT_ID	0x1010
28
29#define CMD_ACK		'!'
30#define CMD_ANIMATE	'A'
31#define CMD_COUNT	'C'
32#define CMD_LED		'L'
33#define CMD_READ	'R'
34#define CMD_SET		'S'
35#define CMD_VERSION	'V'
36#define CMD_EOF		0x0d
37#define CMD_PADDING	0xff
38
39#define YUREX_BUF_SIZE		8
40#define YUREX_WRITE_TIMEOUT	(HZ*2)
41
42/* table of devices that work with this driver */
43static struct usb_device_id yurex_table[] = {
44	{ USB_DEVICE(YUREX_VENDOR_ID, YUREX_PRODUCT_ID) },
45	{ }					/* Terminating entry */
46};
47MODULE_DEVICE_TABLE(usb, yurex_table);
48
49#ifdef CONFIG_USB_DYNAMIC_MINORS
50#define YUREX_MINOR_BASE	0
51#else
52#define YUREX_MINOR_BASE	192
53#endif
54
55/* Structure to hold all of our device specific stuff */
56struct usb_yurex {
57	struct usb_device	*udev;
58	struct usb_interface	*interface;
59	__u8			int_in_endpointAddr;
60	struct urb		*urb;		/* URB for interrupt in */
61	unsigned char           *int_buffer;	/* buffer for intterupt in */
62	struct urb		*cntl_urb;	/* URB for control msg */
63	struct usb_ctrlrequest	*cntl_req;	/* req for control msg */
64	unsigned char		*cntl_buffer;	/* buffer for control msg */
65
66	struct kref		kref;
67	struct mutex		io_mutex;
68	struct fasync_struct	*async_queue;
69	wait_queue_head_t	waitq;
70
71	spinlock_t		lock;
72	__s64			bbu;		/* BBU from device */
73};
74#define to_yurex_dev(d) container_of(d, struct usb_yurex, kref)
75
76static struct usb_driver yurex_driver;
77static const struct file_operations yurex_fops;
78
79
80static void yurex_control_callback(struct urb *urb)
81{
82	struct usb_yurex *dev = urb->context;
83	int status = urb->status;
84
85	if (status) {
86		err("%s - control failed: %d\n", __func__, status);
87		wake_up_interruptible(&dev->waitq);
88		return;
89	}
90	/* on success, sender woken up by CMD_ACK int in, or timeout */
91}
92
93static void yurex_delete(struct kref *kref)
94{
95	struct usb_yurex *dev = to_yurex_dev(kref);
96
97	dbg("yurex_delete");
98
99	usb_put_dev(dev->udev);
100	if (dev->cntl_urb) {
101		usb_kill_urb(dev->cntl_urb);
102		kfree(dev->cntl_req);
103		if (dev->cntl_buffer)
104			usb_free_coherent(dev->udev, YUREX_BUF_SIZE,
105				dev->cntl_buffer, dev->cntl_urb->transfer_dma);
106		usb_free_urb(dev->cntl_urb);
107	}
108	if (dev->urb) {
109		usb_kill_urb(dev->urb);
110		if (dev->int_buffer)
111			usb_free_coherent(dev->udev, YUREX_BUF_SIZE,
112				dev->int_buffer, dev->urb->transfer_dma);
113		usb_free_urb(dev->urb);
114	}
115	kfree(dev);
116}
117
118/*
119 * usb class driver info in order to get a minor number from the usb core,
120 * and to have the device registered with the driver core
121 */
122static struct usb_class_driver yurex_class = {
123	.name =		"yurex%d",
124	.fops =		&yurex_fops,
125	.minor_base =	YUREX_MINOR_BASE,
126};
127
128static void yurex_interrupt(struct urb *urb)
129{
130	struct usb_yurex *dev = urb->context;
131	unsigned char *buf = dev->int_buffer;
132	int status = urb->status;
133	unsigned long flags;
134	int retval, i;
135
136	switch (status) {
137	case 0: /*success*/
138		break;
139	case -EOVERFLOW:
140		err("%s - overflow with length %d, actual length is %d",
141		    __func__, YUREX_BUF_SIZE, dev->urb->actual_length);
142	case -ECONNRESET:
143	case -ENOENT:
144	case -ESHUTDOWN:
145	case -EILSEQ:
146		/* The device is terminated, clean up */
147		return;
148	default:
149		err("%s - unknown status received: %d", __func__, status);
150		goto exit;
151	}
152
153	/* handle received message */
154	switch (buf[0]) {
155	case CMD_COUNT:
156	case CMD_READ:
157		if (buf[6] == CMD_EOF) {
158			spin_lock_irqsave(&dev->lock, flags);
159			dev->bbu = 0;
160			for (i = 1; i < 6; i++) {
161				dev->bbu += buf[i];
162				if (i != 5)
163					dev->bbu <<= 8;
164			}
165			dbg("%s count: %lld", __func__, dev->bbu);
166			spin_unlock_irqrestore(&dev->lock, flags);
167
168			kill_fasync(&dev->async_queue, SIGIO, POLL_IN);
169		}
170		else
171			dbg("data format error - no EOF");
172		break;
173	case CMD_ACK:
174		dbg("%s ack: %c", __func__, buf[1]);
175		wake_up_interruptible(&dev->waitq);
176		break;
177	}
178
179exit:
180	retval = usb_submit_urb(dev->urb, GFP_ATOMIC);
181	if (retval) {
182		err("%s - usb_submit_urb failed: %d",
183			__func__, retval);
184	}
185}
186
187static int yurex_probe(struct usb_interface *interface, const struct usb_device_id *id)
188{
189	struct usb_yurex *dev;
190	struct usb_host_interface *iface_desc;
191	struct usb_endpoint_descriptor *endpoint;
192	int retval = -ENOMEM;
193	int i;
194	DEFINE_WAIT(wait);
195
196	/* allocate memory for our device state and initialize it */
197	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
198	if (!dev) {
199		err("Out of memory");
200		goto error;
201	}
202	kref_init(&dev->kref);
203	mutex_init(&dev->io_mutex);
204	spin_lock_init(&dev->lock);
205	init_waitqueue_head(&dev->waitq);
206
207	dev->udev = usb_get_dev(interface_to_usbdev(interface));
208	dev->interface = interface;
209
210	/* set up the endpoint information */
211	iface_desc = interface->cur_altsetting;
212	for (i = 0; i < iface_desc->desc.bNumEndpoints; i++) {
213		endpoint = &iface_desc->endpoint[i].desc;
214
215		if (usb_endpoint_is_int_in(endpoint)) {
216			dev->int_in_endpointAddr = endpoint->bEndpointAddress;
217			break;
218		}
219	}
220	if (!dev->int_in_endpointAddr) {
221		retval = -ENODEV;
222		err("Could not find endpoints");
223		goto error;
224	}
225
226
227	/* allocate control URB */
228	dev->cntl_urb = usb_alloc_urb(0, GFP_KERNEL);
229	if (!dev->cntl_urb) {
230		err("Could not allocate control URB");
231		goto error;
232	}
233
234	/* allocate buffer for control req */
235	dev->cntl_req = kmalloc(YUREX_BUF_SIZE, GFP_KERNEL);
236	if (!dev->cntl_req) {
237		err("Could not allocate cntl_req");
238		goto error;
239	}
240
241	/* allocate buffer for control msg */
242	dev->cntl_buffer = usb_alloc_coherent(dev->udev, YUREX_BUF_SIZE,
243					      GFP_KERNEL,
244					      &dev->cntl_urb->transfer_dma);
245	if (!dev->cntl_buffer) {
246		err("Could not allocate cntl_buffer");
247		goto error;
248	}
249
250	/* configure control URB */
251	dev->cntl_req->bRequestType = USB_DIR_OUT | USB_TYPE_CLASS |
252				      USB_RECIP_INTERFACE;
253	dev->cntl_req->bRequest	= HID_REQ_SET_REPORT;
254	dev->cntl_req->wValue	= cpu_to_le16((HID_OUTPUT_REPORT + 1) << 8);
255	dev->cntl_req->wIndex	= cpu_to_le16(iface_desc->desc.bInterfaceNumber);
256	dev->cntl_req->wLength	= cpu_to_le16(YUREX_BUF_SIZE);
257
258	usb_fill_control_urb(dev->cntl_urb, dev->udev,
259			     usb_sndctrlpipe(dev->udev, 0),
260			     (void *)dev->cntl_req, dev->cntl_buffer,
261			     YUREX_BUF_SIZE, yurex_control_callback, dev);
262	dev->cntl_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
263
264
265	/* allocate interrupt URB */
266	dev->urb = usb_alloc_urb(0, GFP_KERNEL);
267	if (!dev->urb) {
268		err("Could not allocate URB");
269		goto error;
270	}
271
272	/* allocate buffer for interrupt in */
273	dev->int_buffer = usb_alloc_coherent(dev->udev, YUREX_BUF_SIZE,
274					GFP_KERNEL, &dev->urb->transfer_dma);
275	if (!dev->int_buffer) {
276		err("Could not allocate int_buffer");
277		goto error;
278	}
279
280	/* configure interrupt URB */
281	usb_fill_int_urb(dev->urb, dev->udev,
282			 usb_rcvintpipe(dev->udev, dev->int_in_endpointAddr),
283			 dev->int_buffer, YUREX_BUF_SIZE, yurex_interrupt,
284			 dev, 1);
285	dev->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
286	if (usb_submit_urb(dev->urb, GFP_KERNEL)) {
287		retval = -EIO;
288		err("Could not submitting URB");
289		goto error;
290	}
291
292	/* save our data pointer in this interface device */
293	usb_set_intfdata(interface, dev);
294
295	/* we can register the device now, as it is ready */
296	retval = usb_register_dev(interface, &yurex_class);
297	if (retval) {
298		err("Not able to get a minor for this device.");
299		usb_set_intfdata(interface, NULL);
300		goto error;
301	}
302
303	dev->bbu = -1;
304
305	dev_info(&interface->dev,
306		 "USB YUREX device now attached to Yurex #%d\n",
307		 interface->minor);
308
309	return 0;
310
311error:
312	if (dev)
313		/* this frees allocated memory */
314		kref_put(&dev->kref, yurex_delete);
315	return retval;
316}
317
318static void yurex_disconnect(struct usb_interface *interface)
319{
320	struct usb_yurex *dev;
321	int minor = interface->minor;
322
323	dev = usb_get_intfdata(interface);
324	usb_set_intfdata(interface, NULL);
325
326	/* give back our minor */
327	usb_deregister_dev(interface, &yurex_class);
328
329	/* prevent more I/O from starting */
330	mutex_lock(&dev->io_mutex);
331	dev->interface = NULL;
332	mutex_unlock(&dev->io_mutex);
333
334	/* wakeup waiters */
335	kill_fasync(&dev->async_queue, SIGIO, POLL_IN);
336	wake_up_interruptible(&dev->waitq);
337
338	/* decrement our usage count */
339	kref_put(&dev->kref, yurex_delete);
340
341	dev_info(&interface->dev, "USB YUREX #%d now disconnected\n", minor);
342}
343
344static struct usb_driver yurex_driver = {
345	.name =		"yurex",
346	.probe =	yurex_probe,
347	.disconnect =	yurex_disconnect,
348	.id_table =	yurex_table,
349};
350
351
352static int yurex_fasync(int fd, struct file *file, int on)
353{
354	struct usb_yurex *dev;
355
356	dev = (struct usb_yurex *)file->private_data;
357	return fasync_helper(fd, file, on, &dev->async_queue);
358}
359
360static int yurex_open(struct inode *inode, struct file *file)
361{
362	struct usb_yurex *dev;
363	struct usb_interface *interface;
364	int subminor;
365	int retval = 0;
366
367	subminor = iminor(inode);
368
369	interface = usb_find_interface(&yurex_driver, subminor);
370	if (!interface) {
371		err("%s - error, can't find device for minor %d",
372		    __func__, subminor);
373		retval = -ENODEV;
374		goto exit;
375	}
376
377	dev = usb_get_intfdata(interface);
378	if (!dev) {
379		retval = -ENODEV;
380		goto exit;
381	}
382
383	/* increment our usage count for the device */
384	kref_get(&dev->kref);
385
386	/* save our object in the file's private structure */
387	mutex_lock(&dev->io_mutex);
388	file->private_data = dev;
389	mutex_unlock(&dev->io_mutex);
390
391exit:
392	return retval;
393}
394
395static int yurex_release(struct inode *inode, struct file *file)
396{
397	struct usb_yurex *dev;
398
399	dev = (struct usb_yurex *)file->private_data;
400	if (dev == NULL)
401		return -ENODEV;
402
403	yurex_fasync(-1, file, 0);
404
405	/* decrement the count on our device */
406	kref_put(&dev->kref, yurex_delete);
407	return 0;
408}
409
410static ssize_t yurex_read(struct file *file, char *buffer, size_t count, loff_t *ppos)
411{
412	struct usb_yurex *dev;
413	int retval = 0;
414	int bytes_read = 0;
415	char in_buffer[20];
416	unsigned long flags;
417
418	dev = (struct usb_yurex *)file->private_data;
419
420	mutex_lock(&dev->io_mutex);
421	if (!dev->interface) {		/* already disconnected */
422		retval = -ENODEV;
423		goto exit;
424	}
425
426	spin_lock_irqsave(&dev->lock, flags);
427	bytes_read = snprintf(in_buffer, 20, "%lld\n", dev->bbu);
428	spin_unlock_irqrestore(&dev->lock, flags);
429
430	if (*ppos < bytes_read) {
431		if (copy_to_user(buffer, in_buffer + *ppos, bytes_read - *ppos))
432			retval = -EFAULT;
433		else {
434			retval = bytes_read - *ppos;
435			*ppos += bytes_read;
436		}
437	}
438
439exit:
440	mutex_unlock(&dev->io_mutex);
441	return retval;
442}
443
444static ssize_t yurex_write(struct file *file, const char *user_buffer, size_t count, loff_t *ppos)
445{
446	struct usb_yurex *dev;
447	int i, set = 0, retval = 0;
448	char buffer[16];
449	char *data = buffer;
450	unsigned long long c, c2 = 0;
451	signed long timeout = 0;
452	DEFINE_WAIT(wait);
453
454	count = min(sizeof(buffer), count);
455	dev = (struct usb_yurex *)file->private_data;
456
457	/* verify that we actually have some data to write */
458	if (count == 0)
459		goto error;
460
461	mutex_lock(&dev->io_mutex);
462	if (!dev->interface) {		/* alreaday disconnected */
463		mutex_unlock(&dev->io_mutex);
464		retval = -ENODEV;
465		goto error;
466	}
467
468	if (copy_from_user(buffer, user_buffer, count)) {
469		mutex_unlock(&dev->io_mutex);
470		retval = -EFAULT;
471		goto error;
472	}
473	memset(dev->cntl_buffer, CMD_PADDING, YUREX_BUF_SIZE);
474
475	switch (buffer[0]) {
476	case CMD_ANIMATE:
477	case CMD_LED:
478		dev->cntl_buffer[0] = buffer[0];
479		dev->cntl_buffer[1] = buffer[1];
480		dev->cntl_buffer[2] = CMD_EOF;
481		break;
482	case CMD_READ:
483	case CMD_VERSION:
484		dev->cntl_buffer[0] = buffer[0];
485		dev->cntl_buffer[1] = 0x00;
486		dev->cntl_buffer[2] = CMD_EOF;
487		break;
488	case CMD_SET:
489		data++;
490		/* FALL THROUGH */
491	case '0' ... '9':
492		set = 1;
493		c = c2 = simple_strtoull(data, NULL, 0);
494		dev->cntl_buffer[0] = CMD_SET;
495		for (i = 1; i < 6; i++) {
496			dev->cntl_buffer[i] = (c>>32) & 0xff;
497			c <<= 8;
498		}
499		buffer[6] = CMD_EOF;
500		break;
501	default:
502		mutex_unlock(&dev->io_mutex);
503		return -EINVAL;
504	}
505
506	/* send the data as the control msg */
507	prepare_to_wait(&dev->waitq, &wait, TASK_INTERRUPTIBLE);
508	dbg("%s - submit %c", __func__, dev->cntl_buffer[0]);
509	retval = usb_submit_urb(dev->cntl_urb, GFP_KERNEL);
510	if (retval >= 0)
511		timeout = schedule_timeout(YUREX_WRITE_TIMEOUT);
512	finish_wait(&dev->waitq, &wait);
513
514	mutex_unlock(&dev->io_mutex);
515
516	if (retval < 0) {
517		err("%s - failed to send bulk msg, error %d", __func__, retval);
518		goto error;
519	}
520	if (set && timeout)
521		dev->bbu = c2;
522	return timeout ? count : -EIO;
523
524error:
525	return retval;
526}
527
528static const struct file_operations yurex_fops = {
529	.owner =	THIS_MODULE,
530	.read =		yurex_read,
531	.write =	yurex_write,
532	.open =		yurex_open,
533	.release =	yurex_release,
534	.fasync	=	yurex_fasync,
535	.llseek =	default_llseek,
536};
537
538module_usb_driver(yurex_driver);
539
540MODULE_LICENSE("GPL");
541