xref: /linux/drivers/usb/serial/generic.c (revision 1e578ec51cace9dcef961225b72b8da46ade13ae)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * USB Serial Converter Generic functions
4  *
5  * Copyright (C) 2010 - 2013 Johan Hovold (jhovold@gmail.com)
6  * Copyright (C) 1999 - 2002 Greg Kroah-Hartman (greg@kroah.com)
7  */
8 
9 #include <linux/kernel.h>
10 #include <linux/sched/signal.h>
11 #include <linux/errno.h>
12 #include <linux/slab.h>
13 #include <linux/sysrq.h>
14 #include <linux/tty.h>
15 #include <linux/tty_flip.h>
16 #include <linux/module.h>
17 #include <linux/moduleparam.h>
18 #include <linux/usb.h>
19 #include <linux/usb/serial.h>
20 #include <linux/kfifo.h>
21 #include <linux/serial.h>
22 
23 #ifdef CONFIG_USB_SERIAL_GENERIC
24 
25 static __u16 vendor  = 0x05f9;
26 static __u16 product = 0xffff;
27 
28 module_param(vendor, ushort, 0);
29 MODULE_PARM_DESC(vendor, "User specified USB idVendor");
30 
31 module_param(product, ushort, 0);
32 MODULE_PARM_DESC(product, "User specified USB idProduct");
33 
34 static struct usb_device_id generic_device_ids[2]; /* Initially all zeroes. */
35 
36 static int usb_serial_generic_probe(struct usb_serial *serial,
37 					const struct usb_device_id *id)
38 {
39 	struct device *dev = &serial->interface->dev;
40 
41 	dev_info(dev, "The \"generic\" usb-serial driver is only for testing and one-off prototypes.\n");
42 	dev_info(dev, "Tell linux-usb@vger.kernel.org to add your device to a proper driver.\n");
43 
44 	return 0;
45 }
46 
47 static int usb_serial_generic_calc_num_ports(struct usb_serial *serial,
48 					struct usb_serial_endpoints *epds)
49 {
50 	struct device *dev = &serial->interface->dev;
51 	int num_ports;
52 
53 	num_ports = max(epds->num_bulk_in, epds->num_bulk_out);
54 
55 	if (num_ports == 0) {
56 		dev_err(dev, "device has no bulk endpoints\n");
57 		return -ENODEV;
58 	}
59 
60 	return num_ports;
61 }
62 
63 static struct usb_serial_driver usb_serial_generic_device = {
64 	.driver = {
65 		.name =		"generic",
66 	},
67 	.id_table =		generic_device_ids,
68 	.probe =		usb_serial_generic_probe,
69 	.calc_num_ports =	usb_serial_generic_calc_num_ports,
70 	.throttle =		usb_serial_generic_throttle,
71 	.unthrottle =		usb_serial_generic_unthrottle,
72 	.resume =		usb_serial_generic_resume,
73 };
74 
75 static struct usb_serial_driver * const serial_drivers[] = {
76 	&usb_serial_generic_device, NULL
77 };
78 
79 #endif
80 
81 int usb_serial_generic_register(void)
82 {
83 	int retval = 0;
84 
85 #ifdef CONFIG_USB_SERIAL_GENERIC
86 	generic_device_ids[0].idVendor = vendor;
87 	generic_device_ids[0].idProduct = product;
88 	generic_device_ids[0].match_flags =
89 		USB_DEVICE_ID_MATCH_VENDOR | USB_DEVICE_ID_MATCH_PRODUCT;
90 
91 	retval = usb_serial_register_drivers(serial_drivers,
92 			"usbserial_generic", generic_device_ids);
93 #endif
94 	return retval;
95 }
96 
97 void usb_serial_generic_deregister(void)
98 {
99 #ifdef CONFIG_USB_SERIAL_GENERIC
100 	usb_serial_deregister_drivers(serial_drivers);
101 #endif
102 }
103 
104 int usb_serial_generic_open(struct tty_struct *tty, struct usb_serial_port *port)
105 {
106 	int result = 0;
107 
108 	clear_bit(USB_SERIAL_THROTTLED, &port->flags);
109 
110 	if (port->bulk_in_size)
111 		result = usb_serial_generic_submit_read_urbs(port, GFP_KERNEL);
112 
113 	return result;
114 }
115 EXPORT_SYMBOL_GPL(usb_serial_generic_open);
116 
117 void usb_serial_generic_close(struct usb_serial_port *port)
118 {
119 	unsigned long flags;
120 	int i;
121 
122 	if (port->bulk_out_size) {
123 		for (i = 0; i < ARRAY_SIZE(port->write_urbs); ++i)
124 			usb_kill_urb(port->write_urbs[i]);
125 
126 		spin_lock_irqsave(&port->lock, flags);
127 		kfifo_reset_out(&port->write_fifo);
128 		spin_unlock_irqrestore(&port->lock, flags);
129 	}
130 	if (port->bulk_in_size) {
131 		for (i = 0; i < ARRAY_SIZE(port->read_urbs); ++i)
132 			usb_kill_urb(port->read_urbs[i]);
133 	}
134 }
135 EXPORT_SYMBOL_GPL(usb_serial_generic_close);
136 
137 int usb_serial_generic_prepare_write_buffer(struct usb_serial_port *port,
138 						void *dest, size_t size)
139 {
140 	return kfifo_out_locked(&port->write_fifo, dest, size, &port->lock);
141 }
142 
143 /**
144  * usb_serial_generic_write_start - start writing buffered data
145  * @port: usb-serial port
146  * @mem_flags: flags to use for memory allocations
147  *
148  * Serialised using USB_SERIAL_WRITE_BUSY flag.
149  *
150  * Return: Zero on success or if busy, otherwise a negative errno value.
151  */
152 int usb_serial_generic_write_start(struct usb_serial_port *port,
153 							gfp_t mem_flags)
154 {
155 	struct urb *urb;
156 	int count, result;
157 	unsigned long flags;
158 	int i;
159 
160 	if (test_and_set_bit_lock(USB_SERIAL_WRITE_BUSY, &port->flags))
161 		return 0;
162 retry:
163 	spin_lock_irqsave(&port->lock, flags);
164 	if (!port->write_urbs_free || !kfifo_len(&port->write_fifo)) {
165 		clear_bit_unlock(USB_SERIAL_WRITE_BUSY, &port->flags);
166 		spin_unlock_irqrestore(&port->lock, flags);
167 		return 0;
168 	}
169 	i = (int)find_first_bit(&port->write_urbs_free,
170 						ARRAY_SIZE(port->write_urbs));
171 	spin_unlock_irqrestore(&port->lock, flags);
172 
173 	urb = port->write_urbs[i];
174 	count = port->serial->type->prepare_write_buffer(port,
175 						urb->transfer_buffer,
176 						port->bulk_out_size);
177 	urb->transfer_buffer_length = count;
178 	usb_serial_debug_data(&port->dev, __func__, count, urb->transfer_buffer);
179 	spin_lock_irqsave(&port->lock, flags);
180 	port->tx_bytes += count;
181 	spin_unlock_irqrestore(&port->lock, flags);
182 
183 	clear_bit(i, &port->write_urbs_free);
184 	result = usb_submit_urb(urb, mem_flags);
185 	if (result) {
186 		dev_err_console(port, "%s - error submitting urb: %d\n",
187 						__func__, result);
188 		set_bit(i, &port->write_urbs_free);
189 		spin_lock_irqsave(&port->lock, flags);
190 		port->tx_bytes -= count;
191 		spin_unlock_irqrestore(&port->lock, flags);
192 
193 		clear_bit_unlock(USB_SERIAL_WRITE_BUSY, &port->flags);
194 		return result;
195 	}
196 
197 	goto retry;	/* try sending off another urb */
198 }
199 EXPORT_SYMBOL_GPL(usb_serial_generic_write_start);
200 
201 /**
202  * usb_serial_generic_write - generic write function
203  * @tty: tty for the port
204  * @port: usb-serial port
205  * @buf: data to write
206  * @count: number of bytes to write
207  *
208  * Return: The number of characters buffered, which may be anything from
209  * zero to @count, or a negative errno value.
210  */
211 int usb_serial_generic_write(struct tty_struct *tty,
212 	struct usb_serial_port *port, const unsigned char *buf, int count)
213 {
214 	int result;
215 
216 	if (!port->bulk_out_size)
217 		return -ENODEV;
218 
219 	if (!count)
220 		return 0;
221 
222 	count = kfifo_in_locked(&port->write_fifo, buf, count, &port->lock);
223 	result = usb_serial_generic_write_start(port, GFP_ATOMIC);
224 	if (result)
225 		return result;
226 
227 	return count;
228 }
229 EXPORT_SYMBOL_GPL(usb_serial_generic_write);
230 
231 unsigned int usb_serial_generic_write_room(struct tty_struct *tty)
232 {
233 	struct usb_serial_port *port = tty->driver_data;
234 	unsigned long flags;
235 	unsigned int room;
236 
237 	if (!port->bulk_out_size)
238 		return 0;
239 
240 	spin_lock_irqsave(&port->lock, flags);
241 	room = kfifo_avail(&port->write_fifo);
242 	spin_unlock_irqrestore(&port->lock, flags);
243 
244 	dev_dbg(&port->dev, "%s - returns %u\n", __func__, room);
245 	return room;
246 }
247 
248 unsigned int usb_serial_generic_chars_in_buffer(struct tty_struct *tty)
249 {
250 	struct usb_serial_port *port = tty->driver_data;
251 	unsigned long flags;
252 	unsigned int chars;
253 
254 	if (!port->bulk_out_size)
255 		return 0;
256 
257 	spin_lock_irqsave(&port->lock, flags);
258 	chars = kfifo_len(&port->write_fifo) + port->tx_bytes;
259 	spin_unlock_irqrestore(&port->lock, flags);
260 
261 	dev_dbg(&port->dev, "%s - returns %u\n", __func__, chars);
262 	return chars;
263 }
264 EXPORT_SYMBOL_GPL(usb_serial_generic_chars_in_buffer);
265 
266 void usb_serial_generic_wait_until_sent(struct tty_struct *tty, long timeout)
267 {
268 	struct usb_serial_port *port = tty->driver_data;
269 	unsigned int bps;
270 	unsigned long period;
271 	unsigned long expire;
272 
273 	bps = tty_get_baud_rate(tty);
274 	if (!bps)
275 		bps = 9600;	/* B0 */
276 	/*
277 	 * Use a poll-period of roughly the time it takes to send one
278 	 * character or at least one jiffy.
279 	 */
280 	period = max_t(unsigned long, (10 * HZ / bps), 1);
281 	if (timeout)
282 		period = min_t(unsigned long, period, timeout);
283 
284 	dev_dbg(&port->dev, "%s - timeout = %u ms, period = %u ms\n",
285 					__func__, jiffies_to_msecs(timeout),
286 					jiffies_to_msecs(period));
287 	expire = jiffies + timeout;
288 	while (!port->serial->type->tx_empty(port)) {
289 		schedule_timeout_interruptible(period);
290 		if (signal_pending(current))
291 			break;
292 		if (timeout && time_after(jiffies, expire))
293 			break;
294 	}
295 }
296 EXPORT_SYMBOL_GPL(usb_serial_generic_wait_until_sent);
297 
298 static int usb_serial_generic_submit_read_urb(struct usb_serial_port *port,
299 						int index, gfp_t mem_flags)
300 {
301 	int res;
302 
303 	if (!test_and_clear_bit(index, &port->read_urbs_free))
304 		return 0;
305 
306 	dev_dbg(&port->dev, "%s - urb %d\n", __func__, index);
307 
308 	res = usb_submit_urb(port->read_urbs[index], mem_flags);
309 	if (res) {
310 		if (res != -EPERM && res != -ENODEV) {
311 			dev_err(&port->dev,
312 					"%s - usb_submit_urb failed: %d\n",
313 					__func__, res);
314 		}
315 		set_bit(index, &port->read_urbs_free);
316 		return res;
317 	}
318 
319 	return 0;
320 }
321 
322 int usb_serial_generic_submit_read_urbs(struct usb_serial_port *port,
323 					gfp_t mem_flags)
324 {
325 	int res;
326 	int i;
327 
328 	for (i = 0; i < ARRAY_SIZE(port->read_urbs); ++i) {
329 		res = usb_serial_generic_submit_read_urb(port, i, mem_flags);
330 		if (res)
331 			goto err;
332 	}
333 
334 	return 0;
335 err:
336 	for (; i >= 0; --i)
337 		usb_kill_urb(port->read_urbs[i]);
338 
339 	return res;
340 }
341 EXPORT_SYMBOL_GPL(usb_serial_generic_submit_read_urbs);
342 
343 void usb_serial_generic_process_read_urb(struct urb *urb)
344 {
345 	struct usb_serial_port *port = urb->context;
346 	char *ch = urb->transfer_buffer;
347 	int i;
348 
349 	if (!urb->actual_length)
350 		return;
351 	/*
352 	 * The per character mucking around with sysrq path it too slow for
353 	 * stuff like 3G modems, so shortcircuit it in the 99.9999999% of
354 	 * cases where the USB serial is not a console anyway.
355 	 */
356 	if (port->sysrq) {
357 		for (i = 0; i < urb->actual_length; i++, ch++) {
358 			if (!usb_serial_handle_sysrq_char(port, *ch))
359 				tty_insert_flip_char(&port->port, *ch, TTY_NORMAL);
360 		}
361 	} else {
362 		tty_insert_flip_string(&port->port, ch, urb->actual_length);
363 	}
364 	tty_flip_buffer_push(&port->port);
365 }
366 EXPORT_SYMBOL_GPL(usb_serial_generic_process_read_urb);
367 
368 void usb_serial_generic_read_bulk_callback(struct urb *urb)
369 {
370 	struct usb_serial_port *port = urb->context;
371 	unsigned char *data = urb->transfer_buffer;
372 	bool stopped = false;
373 	int status = urb->status;
374 	int i;
375 
376 	for (i = 0; i < ARRAY_SIZE(port->read_urbs); ++i) {
377 		if (urb == port->read_urbs[i])
378 			break;
379 	}
380 
381 	dev_dbg(&port->dev, "%s - urb %d, len %d\n", __func__, i,
382 							urb->actual_length);
383 	switch (status) {
384 	case 0:
385 		usb_serial_debug_data(&port->dev, __func__, urb->actual_length,
386 							data);
387 		port->serial->type->process_read_urb(urb);
388 		break;
389 	case -ENOENT:
390 	case -ECONNRESET:
391 	case -ESHUTDOWN:
392 		dev_dbg(&port->dev, "%s - urb stopped: %d\n",
393 							__func__, status);
394 		stopped = true;
395 		break;
396 	case -EPIPE:
397 		dev_err(&port->dev, "%s - urb stopped: %d\n",
398 							__func__, status);
399 		stopped = true;
400 		break;
401 	default:
402 		dev_dbg(&port->dev, "%s - nonzero urb status: %d\n",
403 							__func__, status);
404 		break;
405 	}
406 
407 	/*
408 	 * Make sure URB processing is done before marking as free to avoid
409 	 * racing with unthrottle() on another CPU. Matches the barriers
410 	 * implied by the test_and_clear_bit() in
411 	 * usb_serial_generic_submit_read_urb().
412 	 */
413 	smp_mb__before_atomic();
414 	set_bit(i, &port->read_urbs_free);
415 	/*
416 	 * Make sure URB is marked as free before checking the throttled flag
417 	 * to avoid racing with unthrottle() on another CPU. Matches the
418 	 * smp_mb__after_atomic() in unthrottle().
419 	 */
420 	smp_mb__after_atomic();
421 
422 	if (stopped)
423 		return;
424 
425 	if (test_bit(USB_SERIAL_THROTTLED, &port->flags))
426 		return;
427 
428 	usb_serial_generic_submit_read_urb(port, i, GFP_ATOMIC);
429 }
430 EXPORT_SYMBOL_GPL(usb_serial_generic_read_bulk_callback);
431 
432 void usb_serial_generic_write_bulk_callback(struct urb *urb)
433 {
434 	unsigned long flags;
435 	struct usb_serial_port *port = urb->context;
436 	int status = urb->status;
437 	int i;
438 
439 	for (i = 0; i < ARRAY_SIZE(port->write_urbs); ++i) {
440 		if (port->write_urbs[i] == urb)
441 			break;
442 	}
443 	spin_lock_irqsave(&port->lock, flags);
444 	port->tx_bytes -= urb->transfer_buffer_length;
445 	set_bit(i, &port->write_urbs_free);
446 	spin_unlock_irqrestore(&port->lock, flags);
447 
448 	switch (status) {
449 	case 0:
450 		break;
451 	case -ENOENT:
452 	case -ECONNRESET:
453 	case -ESHUTDOWN:
454 		dev_dbg(&port->dev, "%s - urb stopped: %d\n",
455 							__func__, status);
456 		return;
457 	case -EPIPE:
458 		dev_err_console(port, "%s - urb stopped: %d\n",
459 							__func__, status);
460 		return;
461 	default:
462 		dev_err_console(port, "%s - nonzero urb status: %d\n",
463 							__func__, status);
464 		break;
465 	}
466 
467 	usb_serial_generic_write_start(port, GFP_ATOMIC);
468 	usb_serial_port_softint(port);
469 }
470 EXPORT_SYMBOL_GPL(usb_serial_generic_write_bulk_callback);
471 
472 void usb_serial_generic_throttle(struct tty_struct *tty)
473 {
474 	struct usb_serial_port *port = tty->driver_data;
475 
476 	set_bit(USB_SERIAL_THROTTLED, &port->flags);
477 }
478 EXPORT_SYMBOL_GPL(usb_serial_generic_throttle);
479 
480 void usb_serial_generic_unthrottle(struct tty_struct *tty)
481 {
482 	struct usb_serial_port *port = tty->driver_data;
483 
484 	clear_bit(USB_SERIAL_THROTTLED, &port->flags);
485 
486 	/*
487 	 * Matches the smp_mb__after_atomic() in
488 	 * usb_serial_generic_read_bulk_callback().
489 	 */
490 	smp_mb__after_atomic();
491 
492 	usb_serial_generic_submit_read_urbs(port, GFP_KERNEL);
493 }
494 EXPORT_SYMBOL_GPL(usb_serial_generic_unthrottle);
495 
496 static bool usb_serial_generic_msr_changed(struct tty_struct *tty,
497 				unsigned long arg, struct async_icount *cprev)
498 {
499 	struct usb_serial_port *port = tty->driver_data;
500 	struct async_icount cnow;
501 	unsigned long flags;
502 	bool ret;
503 
504 	/*
505 	 * Use tty-port initialised flag to detect all hangups including the
506 	 * one generated at USB-device disconnect.
507 	 */
508 	if (!tty_port_initialized(&port->port))
509 		return true;
510 
511 	spin_lock_irqsave(&port->lock, flags);
512 	cnow = port->icount;				/* atomic copy*/
513 	spin_unlock_irqrestore(&port->lock, flags);
514 
515 	ret =	((arg & TIOCM_RNG) && (cnow.rng != cprev->rng)) ||
516 		((arg & TIOCM_DSR) && (cnow.dsr != cprev->dsr)) ||
517 		((arg & TIOCM_CD)  && (cnow.dcd != cprev->dcd)) ||
518 		((arg & TIOCM_CTS) && (cnow.cts != cprev->cts));
519 
520 	*cprev = cnow;
521 
522 	return ret;
523 }
524 
525 int usb_serial_generic_tiocmiwait(struct tty_struct *tty, unsigned long arg)
526 {
527 	struct usb_serial_port *port = tty->driver_data;
528 	struct async_icount cnow;
529 	unsigned long flags;
530 	int ret;
531 
532 	spin_lock_irqsave(&port->lock, flags);
533 	cnow = port->icount;				/* atomic copy */
534 	spin_unlock_irqrestore(&port->lock, flags);
535 
536 	ret = wait_event_interruptible(port->port.delta_msr_wait,
537 			usb_serial_generic_msr_changed(tty, arg, &cnow));
538 	if (!ret && !tty_port_initialized(&port->port))
539 		ret = -EIO;
540 
541 	return ret;
542 }
543 EXPORT_SYMBOL_GPL(usb_serial_generic_tiocmiwait);
544 
545 int usb_serial_generic_get_icount(struct tty_struct *tty,
546 					struct serial_icounter_struct *icount)
547 {
548 	struct usb_serial_port *port = tty->driver_data;
549 	struct async_icount cnow;
550 	unsigned long flags;
551 
552 	spin_lock_irqsave(&port->lock, flags);
553 	cnow = port->icount;				/* atomic copy */
554 	spin_unlock_irqrestore(&port->lock, flags);
555 
556 	icount->cts = cnow.cts;
557 	icount->dsr = cnow.dsr;
558 	icount->rng = cnow.rng;
559 	icount->dcd = cnow.dcd;
560 	icount->tx = cnow.tx;
561 	icount->rx = cnow.rx;
562 	icount->frame = cnow.frame;
563 	icount->parity = cnow.parity;
564 	icount->overrun = cnow.overrun;
565 	icount->brk = cnow.brk;
566 	icount->buf_overrun = cnow.buf_overrun;
567 
568 	return 0;
569 }
570 EXPORT_SYMBOL_GPL(usb_serial_generic_get_icount);
571 
572 #if defined(CONFIG_USB_SERIAL_CONSOLE) && defined(CONFIG_MAGIC_SYSRQ)
573 int usb_serial_handle_sysrq_char(struct usb_serial_port *port, unsigned int ch)
574 {
575 	if (port->sysrq) {
576 		if (ch && time_before(jiffies, port->sysrq)) {
577 			handle_sysrq(ch);
578 			port->sysrq = 0;
579 			return 1;
580 		}
581 		port->sysrq = 0;
582 	}
583 	return 0;
584 }
585 EXPORT_SYMBOL_GPL(usb_serial_handle_sysrq_char);
586 
587 int usb_serial_handle_break(struct usb_serial_port *port)
588 {
589 	if (!port->port.console)
590 		return 0;
591 
592 	if (!port->sysrq) {
593 		port->sysrq = jiffies + HZ*5;
594 		return 1;
595 	}
596 	port->sysrq = 0;
597 	return 0;
598 }
599 EXPORT_SYMBOL_GPL(usb_serial_handle_break);
600 #endif
601 
602 /**
603  * usb_serial_handle_dcd_change - handle a change of carrier detect state
604  * @port: usb-serial port
605  * @tty: tty for the port
606  * @status: new carrier detect status, nonzero if active
607  */
608 void usb_serial_handle_dcd_change(struct usb_serial_port *port,
609 				struct tty_struct *tty, unsigned int status)
610 {
611 	dev_dbg(&port->dev, "%s - status %d\n", __func__, status);
612 
613 	if (tty) {
614 		struct tty_ldisc *ld = tty_ldisc_ref(tty);
615 
616 		if (ld) {
617 			if (ld->ops->dcd_change)
618 				ld->ops->dcd_change(tty, status);
619 			tty_ldisc_deref(ld);
620 		}
621 	}
622 
623 	if (status)
624 		wake_up_interruptible(&port->port.open_wait);
625 	else if (tty && !C_CLOCAL(tty))
626 		tty_hangup(tty);
627 }
628 EXPORT_SYMBOL_GPL(usb_serial_handle_dcd_change);
629 
630 int usb_serial_generic_resume(struct usb_serial *serial)
631 {
632 	struct usb_serial_port *port;
633 	int i, c = 0, r;
634 
635 	for (i = 0; i < serial->num_ports; i++) {
636 		port = serial->port[i];
637 		if (!tty_port_initialized(&port->port))
638 			continue;
639 
640 		if (port->bulk_in_size) {
641 			r = usb_serial_generic_submit_read_urbs(port,
642 								GFP_NOIO);
643 			if (r < 0)
644 				c++;
645 		}
646 
647 		if (port->bulk_out_size) {
648 			r = usb_serial_generic_write_start(port, GFP_NOIO);
649 			if (r < 0)
650 				c++;
651 		}
652 	}
653 
654 	return c ? -EIO : 0;
655 }
656 EXPORT_SYMBOL_GPL(usb_serial_generic_resume);
657