xref: /linux/drivers/usb/usb-skeleton.c (revision 56fb34d86e875dbb0d3e6a81c5d3d035db373031)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * USB Skeleton driver - 2.2
4  *
5  * Copyright (C) 2001-2004 Greg Kroah-Hartman (greg@kroah.com)
6  *
7  * This driver is based on the 2.6.3 version of drivers/usb/usb-skeleton.c
8  * but has been rewritten to be easier to read and use.
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/kref.h>
16 #include <linux/uaccess.h>
17 #include <linux/usb.h>
18 #include <linux/mutex.h>
19 
20 
21 /* Define these values to match your devices */
22 #define USB_SKEL_VENDOR_ID	0xfff0
23 #define USB_SKEL_PRODUCT_ID	0xfff0
24 
25 /* table of devices that work with this driver */
26 static const struct usb_device_id skel_table[] = {
27 	{ USB_DEVICE(USB_SKEL_VENDOR_ID, USB_SKEL_PRODUCT_ID) },
28 	{ }					/* Terminating entry */
29 };
30 MODULE_DEVICE_TABLE(usb, skel_table);
31 
32 
33 /* Get a minor range for your devices from the usb maintainer */
34 #define USB_SKEL_MINOR_BASE	192
35 
36 /* our private defines. if this grows any larger, use your own .h file */
37 #define MAX_TRANSFER		(PAGE_SIZE - 512)
38 /*
39  * MAX_TRANSFER is chosen so that the VM is not stressed by
40  * allocations > PAGE_SIZE and the number of packets in a page
41  * is an integer 512 is the largest possible packet on EHCI
42  */
43 #define WRITES_IN_FLIGHT	8
44 /* arbitrarily chosen */
45 
46 /* Structure to hold all of our device specific stuff */
47 struct usb_skel {
48 	struct usb_device	*udev;			/* the usb device for this device */
49 	struct usb_interface	*interface;		/* the interface for this device */
50 	struct semaphore	limit_sem;		/* limiting the number of writes in progress */
51 	struct usb_anchor	submitted;		/* in case we need to retract our submissions */
52 	struct urb		*bulk_in_urb;		/* the urb to read data with */
53 	unsigned char           *bulk_in_buffer;	/* the buffer to receive data */
54 	size_t			bulk_in_size;		/* the size of the receive buffer */
55 	size_t			bulk_in_filled;		/* number of bytes in the buffer */
56 	size_t			bulk_in_copied;		/* already copied to user space */
57 	__u8			bulk_in_endpointAddr;	/* the address of the bulk in endpoint */
58 	__u8			bulk_out_endpointAddr;	/* the address of the bulk out endpoint */
59 	int			errors;			/* the last request tanked */
60 	bool			ongoing_read;		/* a read is going on */
61 	spinlock_t		err_lock;		/* lock for errors */
62 	struct kref		kref;
63 	struct mutex		io_mutex;		/* synchronize I/O with disconnect */
64 	wait_queue_head_t	bulk_in_wait;		/* to wait for an ongoing read */
65 };
66 #define to_skel_dev(d) container_of(d, struct usb_skel, kref)
67 
68 static struct usb_driver skel_driver;
69 static void skel_draw_down(struct usb_skel *dev);
70 
71 static void skel_delete(struct kref *kref)
72 {
73 	struct usb_skel *dev = to_skel_dev(kref);
74 
75 	usb_free_urb(dev->bulk_in_urb);
76 	usb_put_dev(dev->udev);
77 	kfree(dev->bulk_in_buffer);
78 	kfree(dev);
79 }
80 
81 static int skel_open(struct inode *inode, struct file *file)
82 {
83 	struct usb_skel *dev;
84 	struct usb_interface *interface;
85 	int subminor;
86 	int retval = 0;
87 
88 	subminor = iminor(inode);
89 
90 	interface = usb_find_interface(&skel_driver, subminor);
91 	if (!interface) {
92 		pr_err("%s - error, can't find device for minor %d\n",
93 			__func__, subminor);
94 		retval = -ENODEV;
95 		goto exit;
96 	}
97 
98 	dev = usb_get_intfdata(interface);
99 	if (!dev) {
100 		retval = -ENODEV;
101 		goto exit;
102 	}
103 
104 	retval = usb_autopm_get_interface(interface);
105 	if (retval)
106 		goto exit;
107 
108 	/* increment our usage count for the device */
109 	kref_get(&dev->kref);
110 
111 	/* save our object in the file's private structure */
112 	file->private_data = dev;
113 
114 exit:
115 	return retval;
116 }
117 
118 static int skel_release(struct inode *inode, struct file *file)
119 {
120 	struct usb_skel *dev;
121 
122 	dev = file->private_data;
123 	if (dev == NULL)
124 		return -ENODEV;
125 
126 	/* allow the device to be autosuspended */
127 	mutex_lock(&dev->io_mutex);
128 	if (dev->interface)
129 		usb_autopm_put_interface(dev->interface);
130 	mutex_unlock(&dev->io_mutex);
131 
132 	/* decrement the count on our device */
133 	kref_put(&dev->kref, skel_delete);
134 	return 0;
135 }
136 
137 static int skel_flush(struct file *file, fl_owner_t id)
138 {
139 	struct usb_skel *dev;
140 	int res;
141 
142 	dev = file->private_data;
143 	if (dev == NULL)
144 		return -ENODEV;
145 
146 	/* wait for io to stop */
147 	mutex_lock(&dev->io_mutex);
148 	skel_draw_down(dev);
149 
150 	/* read out errors, leave subsequent opens a clean slate */
151 	spin_lock_irq(&dev->err_lock);
152 	res = dev->errors ? (dev->errors == -EPIPE ? -EPIPE : -EIO) : 0;
153 	dev->errors = 0;
154 	spin_unlock_irq(&dev->err_lock);
155 
156 	mutex_unlock(&dev->io_mutex);
157 
158 	return res;
159 }
160 
161 static void skel_read_bulk_callback(struct urb *urb)
162 {
163 	struct usb_skel *dev;
164 	unsigned long flags;
165 
166 	dev = urb->context;
167 
168 	spin_lock_irqsave(&dev->err_lock, flags);
169 	/* sync/async unlink faults aren't errors */
170 	if (urb->status) {
171 		if (!(urb->status == -ENOENT ||
172 		    urb->status == -ECONNRESET ||
173 		    urb->status == -ESHUTDOWN))
174 			dev_err(&dev->interface->dev,
175 				"%s - nonzero write bulk status received: %d\n",
176 				__func__, urb->status);
177 
178 		dev->errors = urb->status;
179 	} else {
180 		dev->bulk_in_filled = urb->actual_length;
181 	}
182 	dev->ongoing_read = 0;
183 	spin_unlock_irqrestore(&dev->err_lock, flags);
184 
185 	wake_up_interruptible(&dev->bulk_in_wait);
186 }
187 
188 static int skel_do_read_io(struct usb_skel *dev, size_t count)
189 {
190 	int rv;
191 
192 	/* prepare a read */
193 	usb_fill_bulk_urb(dev->bulk_in_urb,
194 			dev->udev,
195 			usb_rcvbulkpipe(dev->udev,
196 				dev->bulk_in_endpointAddr),
197 			dev->bulk_in_buffer,
198 			min(dev->bulk_in_size, count),
199 			skel_read_bulk_callback,
200 			dev);
201 	/* tell everybody to leave the URB alone */
202 	spin_lock_irq(&dev->err_lock);
203 	dev->ongoing_read = 1;
204 	spin_unlock_irq(&dev->err_lock);
205 
206 	/* submit bulk in urb, which means no data to deliver */
207 	dev->bulk_in_filled = 0;
208 	dev->bulk_in_copied = 0;
209 
210 	/* do it */
211 	rv = usb_submit_urb(dev->bulk_in_urb, GFP_KERNEL);
212 	if (rv < 0) {
213 		dev_err(&dev->interface->dev,
214 			"%s - failed submitting read urb, error %d\n",
215 			__func__, rv);
216 		rv = (rv == -ENOMEM) ? rv : -EIO;
217 		spin_lock_irq(&dev->err_lock);
218 		dev->ongoing_read = 0;
219 		spin_unlock_irq(&dev->err_lock);
220 	}
221 
222 	return rv;
223 }
224 
225 static ssize_t skel_read(struct file *file, char *buffer, size_t count,
226 			 loff_t *ppos)
227 {
228 	struct usb_skel *dev;
229 	int rv;
230 	bool ongoing_io;
231 
232 	dev = file->private_data;
233 
234 	/* if we cannot read at all, return EOF */
235 	if (!dev->bulk_in_urb || !count)
236 		return 0;
237 
238 	/* no concurrent readers */
239 	rv = mutex_lock_interruptible(&dev->io_mutex);
240 	if (rv < 0)
241 		return rv;
242 
243 	if (!dev->interface) {		/* disconnect() was called */
244 		rv = -ENODEV;
245 		goto exit;
246 	}
247 
248 	/* if IO is under way, we must not touch things */
249 retry:
250 	spin_lock_irq(&dev->err_lock);
251 	ongoing_io = dev->ongoing_read;
252 	spin_unlock_irq(&dev->err_lock);
253 
254 	if (ongoing_io) {
255 		/* nonblocking IO shall not wait */
256 		if (file->f_flags & O_NONBLOCK) {
257 			rv = -EAGAIN;
258 			goto exit;
259 		}
260 		/*
261 		 * IO may take forever
262 		 * hence wait in an interruptible state
263 		 */
264 		rv = wait_event_interruptible(dev->bulk_in_wait, (!dev->ongoing_read));
265 		if (rv < 0)
266 			goto exit;
267 	}
268 
269 	/* errors must be reported */
270 	rv = dev->errors;
271 	if (rv < 0) {
272 		/* any error is reported once */
273 		dev->errors = 0;
274 		/* to preserve notifications about reset */
275 		rv = (rv == -EPIPE) ? rv : -EIO;
276 		/* report it */
277 		goto exit;
278 	}
279 
280 	/*
281 	 * if the buffer is filled we may satisfy the read
282 	 * else we need to start IO
283 	 */
284 
285 	if (dev->bulk_in_filled) {
286 		/* we had read data */
287 		size_t available = dev->bulk_in_filled - dev->bulk_in_copied;
288 		size_t chunk = min(available, count);
289 
290 		if (!available) {
291 			/*
292 			 * all data has been used
293 			 * actual IO needs to be done
294 			 */
295 			rv = skel_do_read_io(dev, count);
296 			if (rv < 0)
297 				goto exit;
298 			else
299 				goto retry;
300 		}
301 		/*
302 		 * data is available
303 		 * chunk tells us how much shall be copied
304 		 */
305 
306 		if (copy_to_user(buffer,
307 				 dev->bulk_in_buffer + dev->bulk_in_copied,
308 				 chunk))
309 			rv = -EFAULT;
310 		else
311 			rv = chunk;
312 
313 		dev->bulk_in_copied += chunk;
314 
315 		/*
316 		 * if we are asked for more than we have,
317 		 * we start IO but don't wait
318 		 */
319 		if (available < count)
320 			skel_do_read_io(dev, count - chunk);
321 	} else {
322 		/* no data in the buffer */
323 		rv = skel_do_read_io(dev, count);
324 		if (rv < 0)
325 			goto exit;
326 		else
327 			goto retry;
328 	}
329 exit:
330 	mutex_unlock(&dev->io_mutex);
331 	return rv;
332 }
333 
334 static void skel_write_bulk_callback(struct urb *urb)
335 {
336 	struct usb_skel *dev;
337 	unsigned long flags;
338 
339 	dev = urb->context;
340 
341 	/* sync/async unlink faults aren't errors */
342 	if (urb->status) {
343 		if (!(urb->status == -ENOENT ||
344 		    urb->status == -ECONNRESET ||
345 		    urb->status == -ESHUTDOWN))
346 			dev_err(&dev->interface->dev,
347 				"%s - nonzero write bulk status received: %d\n",
348 				__func__, urb->status);
349 
350 		spin_lock_irqsave(&dev->err_lock, flags);
351 		dev->errors = urb->status;
352 		spin_unlock_irqrestore(&dev->err_lock, flags);
353 	}
354 
355 	/* free up our allocated buffer */
356 	usb_free_coherent(urb->dev, urb->transfer_buffer_length,
357 			  urb->transfer_buffer, urb->transfer_dma);
358 	up(&dev->limit_sem);
359 }
360 
361 static ssize_t skel_write(struct file *file, const char *user_buffer,
362 			  size_t count, loff_t *ppos)
363 {
364 	struct usb_skel *dev;
365 	int retval = 0;
366 	struct urb *urb = NULL;
367 	char *buf = NULL;
368 	size_t writesize = min(count, (size_t)MAX_TRANSFER);
369 
370 	dev = file->private_data;
371 
372 	/* verify that we actually have some data to write */
373 	if (count == 0)
374 		goto exit;
375 
376 	/*
377 	 * limit the number of URBs in flight to stop a user from using up all
378 	 * RAM
379 	 */
380 	if (!(file->f_flags & O_NONBLOCK)) {
381 		if (down_interruptible(&dev->limit_sem)) {
382 			retval = -ERESTARTSYS;
383 			goto exit;
384 		}
385 	} else {
386 		if (down_trylock(&dev->limit_sem)) {
387 			retval = -EAGAIN;
388 			goto exit;
389 		}
390 	}
391 
392 	spin_lock_irq(&dev->err_lock);
393 	retval = dev->errors;
394 	if (retval < 0) {
395 		/* any error is reported once */
396 		dev->errors = 0;
397 		/* to preserve notifications about reset */
398 		retval = (retval == -EPIPE) ? retval : -EIO;
399 	}
400 	spin_unlock_irq(&dev->err_lock);
401 	if (retval < 0)
402 		goto error;
403 
404 	/* create a urb, and a buffer for it, and copy the data to the urb */
405 	urb = usb_alloc_urb(0, GFP_KERNEL);
406 	if (!urb) {
407 		retval = -ENOMEM;
408 		goto error;
409 	}
410 
411 	buf = usb_alloc_coherent(dev->udev, writesize, GFP_KERNEL,
412 				 &urb->transfer_dma);
413 	if (!buf) {
414 		retval = -ENOMEM;
415 		goto error;
416 	}
417 
418 	if (copy_from_user(buf, user_buffer, writesize)) {
419 		retval = -EFAULT;
420 		goto error;
421 	}
422 
423 	/* this lock makes sure we don't submit URBs to gone devices */
424 	mutex_lock(&dev->io_mutex);
425 	if (!dev->interface) {		/* disconnect() was called */
426 		mutex_unlock(&dev->io_mutex);
427 		retval = -ENODEV;
428 		goto error;
429 	}
430 
431 	/* initialize the urb properly */
432 	usb_fill_bulk_urb(urb, dev->udev,
433 			  usb_sndbulkpipe(dev->udev, dev->bulk_out_endpointAddr),
434 			  buf, writesize, skel_write_bulk_callback, dev);
435 	urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
436 	usb_anchor_urb(urb, &dev->submitted);
437 
438 	/* send the data out the bulk port */
439 	retval = usb_submit_urb(urb, GFP_KERNEL);
440 	mutex_unlock(&dev->io_mutex);
441 	if (retval) {
442 		dev_err(&dev->interface->dev,
443 			"%s - failed submitting write urb, error %d\n",
444 			__func__, retval);
445 		goto error_unanchor;
446 	}
447 
448 	/*
449 	 * release our reference to this urb, the USB core will eventually free
450 	 * it entirely
451 	 */
452 	usb_free_urb(urb);
453 
454 
455 	return writesize;
456 
457 error_unanchor:
458 	usb_unanchor_urb(urb);
459 error:
460 	if (urb) {
461 		usb_free_coherent(dev->udev, writesize, buf, urb->transfer_dma);
462 		usb_free_urb(urb);
463 	}
464 	up(&dev->limit_sem);
465 
466 exit:
467 	return retval;
468 }
469 
470 static const struct file_operations skel_fops = {
471 	.owner =	THIS_MODULE,
472 	.read =		skel_read,
473 	.write =	skel_write,
474 	.open =		skel_open,
475 	.release =	skel_release,
476 	.flush =	skel_flush,
477 	.llseek =	noop_llseek,
478 };
479 
480 /*
481  * usb class driver info in order to get a minor number from the usb core,
482  * and to have the device registered with the driver core
483  */
484 static struct usb_class_driver skel_class = {
485 	.name =		"skel%d",
486 	.fops =		&skel_fops,
487 	.minor_base =	USB_SKEL_MINOR_BASE,
488 };
489 
490 static int skel_probe(struct usb_interface *interface,
491 		      const struct usb_device_id *id)
492 {
493 	struct usb_skel *dev;
494 	struct usb_endpoint_descriptor *bulk_in, *bulk_out;
495 	int retval;
496 
497 	/* allocate memory for our device state and initialize it */
498 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
499 	if (!dev)
500 		return -ENOMEM;
501 
502 	kref_init(&dev->kref);
503 	sema_init(&dev->limit_sem, WRITES_IN_FLIGHT);
504 	mutex_init(&dev->io_mutex);
505 	spin_lock_init(&dev->err_lock);
506 	init_usb_anchor(&dev->submitted);
507 	init_waitqueue_head(&dev->bulk_in_wait);
508 
509 	dev->udev = usb_get_dev(interface_to_usbdev(interface));
510 	dev->interface = interface;
511 
512 	/* set up the endpoint information */
513 	/* use only the first bulk-in and bulk-out endpoints */
514 	retval = usb_find_common_endpoints(interface->cur_altsetting,
515 			&bulk_in, &bulk_out, NULL, NULL);
516 	if (retval) {
517 		dev_err(&interface->dev,
518 			"Could not find both bulk-in and bulk-out endpoints\n");
519 		goto error;
520 	}
521 
522 	dev->bulk_in_size = usb_endpoint_maxp(bulk_in);
523 	dev->bulk_in_endpointAddr = bulk_in->bEndpointAddress;
524 	dev->bulk_in_buffer = kmalloc(dev->bulk_in_size, GFP_KERNEL);
525 	if (!dev->bulk_in_buffer) {
526 		retval = -ENOMEM;
527 		goto error;
528 	}
529 	dev->bulk_in_urb = usb_alloc_urb(0, GFP_KERNEL);
530 	if (!dev->bulk_in_urb) {
531 		retval = -ENOMEM;
532 		goto error;
533 	}
534 
535 	dev->bulk_out_endpointAddr = bulk_out->bEndpointAddress;
536 
537 	/* save our data pointer in this interface device */
538 	usb_set_intfdata(interface, dev);
539 
540 	/* we can register the device now, as it is ready */
541 	retval = usb_register_dev(interface, &skel_class);
542 	if (retval) {
543 		/* something prevented us from registering this driver */
544 		dev_err(&interface->dev,
545 			"Not able to get a minor for this device.\n");
546 		usb_set_intfdata(interface, NULL);
547 		goto error;
548 	}
549 
550 	/* let the user know what node this device is now attached to */
551 	dev_info(&interface->dev,
552 		 "USB Skeleton device now attached to USBSkel-%d",
553 		 interface->minor);
554 	return 0;
555 
556 error:
557 	/* this frees allocated memory */
558 	kref_put(&dev->kref, skel_delete);
559 
560 	return retval;
561 }
562 
563 static void skel_disconnect(struct usb_interface *interface)
564 {
565 	struct usb_skel *dev;
566 	int minor = interface->minor;
567 
568 	dev = usb_get_intfdata(interface);
569 	usb_set_intfdata(interface, NULL);
570 
571 	/* give back our minor */
572 	usb_deregister_dev(interface, &skel_class);
573 
574 	/* prevent more I/O from starting */
575 	mutex_lock(&dev->io_mutex);
576 	dev->interface = NULL;
577 	mutex_unlock(&dev->io_mutex);
578 
579 	usb_kill_anchored_urbs(&dev->submitted);
580 
581 	/* decrement our usage count */
582 	kref_put(&dev->kref, skel_delete);
583 
584 	dev_info(&interface->dev, "USB Skeleton #%d now disconnected", minor);
585 }
586 
587 static void skel_draw_down(struct usb_skel *dev)
588 {
589 	int time;
590 
591 	time = usb_wait_anchor_empty_timeout(&dev->submitted, 1000);
592 	if (!time)
593 		usb_kill_anchored_urbs(&dev->submitted);
594 	usb_kill_urb(dev->bulk_in_urb);
595 }
596 
597 static int skel_suspend(struct usb_interface *intf, pm_message_t message)
598 {
599 	struct usb_skel *dev = usb_get_intfdata(intf);
600 
601 	if (!dev)
602 		return 0;
603 	skel_draw_down(dev);
604 	return 0;
605 }
606 
607 static int skel_resume(struct usb_interface *intf)
608 {
609 	return 0;
610 }
611 
612 static int skel_pre_reset(struct usb_interface *intf)
613 {
614 	struct usb_skel *dev = usb_get_intfdata(intf);
615 
616 	mutex_lock(&dev->io_mutex);
617 	skel_draw_down(dev);
618 
619 	return 0;
620 }
621 
622 static int skel_post_reset(struct usb_interface *intf)
623 {
624 	struct usb_skel *dev = usb_get_intfdata(intf);
625 
626 	/* we are sure no URBs are active - no locking needed */
627 	dev->errors = -EPIPE;
628 	mutex_unlock(&dev->io_mutex);
629 
630 	return 0;
631 }
632 
633 static struct usb_driver skel_driver = {
634 	.name =		"skeleton",
635 	.probe =	skel_probe,
636 	.disconnect =	skel_disconnect,
637 	.suspend =	skel_suspend,
638 	.resume =	skel_resume,
639 	.pre_reset =	skel_pre_reset,
640 	.post_reset =	skel_post_reset,
641 	.id_table =	skel_table,
642 	.supports_autosuspend = 1,
643 };
644 
645 module_usb_driver(skel_driver);
646 
647 MODULE_LICENSE("GPL v2");
648