xref: /linux/drivers/usb/serial/generic.c (revision 4b7f393a01f88e8d03cba94cf4948652de14789b)
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 	struct tty_port *tport = &port->port;
270 	unsigned int bps;
271 	unsigned long period;
272 	unsigned long expire;
273 
274 	bps = tty_get_baud_rate(tty);
275 	if (!bps)
276 		bps = 9600;	/* B0 */
277 	/*
278 	 * Use a poll-period of roughly the time it takes to send one
279 	 * character or at least one jiffy.
280 	 */
281 	period = max_t(unsigned long, (10 * HZ / bps), 1);
282 	if (timeout)
283 		period = min_t(unsigned long, period, timeout);
284 
285 	dev_dbg(&port->dev, "%s - timeout = %u ms, period = %u ms\n",
286 					__func__, jiffies_to_msecs(timeout),
287 					jiffies_to_msecs(period));
288 	expire = jiffies + timeout;
289 	for (;;) {
290 		mutex_lock(&tport->mutex);
291 		if (tty_io_error(tty) || port->serial->type->tx_empty(port)) {
292 			mutex_unlock(&tport->mutex);
293 			break;
294 		}
295 		mutex_unlock(&tport->mutex);
296 
297 		schedule_timeout_interruptible(period);
298 		if (signal_pending(current))
299 			break;
300 		if (timeout && time_after(jiffies, expire))
301 			break;
302 	}
303 }
304 EXPORT_SYMBOL_GPL(usb_serial_generic_wait_until_sent);
305 
306 static int usb_serial_generic_submit_read_urb(struct usb_serial_port *port,
307 						int index, gfp_t mem_flags)
308 {
309 	int res;
310 
311 	if (!test_and_clear_bit(index, &port->read_urbs_free))
312 		return 0;
313 
314 	dev_dbg(&port->dev, "%s - urb %d\n", __func__, index);
315 
316 	res = usb_submit_urb(port->read_urbs[index], mem_flags);
317 	if (res) {
318 		if (res != -EPERM && res != -ENODEV) {
319 			dev_err(&port->dev,
320 					"%s - usb_submit_urb failed: %d\n",
321 					__func__, res);
322 		}
323 		set_bit(index, &port->read_urbs_free);
324 		return res;
325 	}
326 
327 	return 0;
328 }
329 
330 int usb_serial_generic_submit_read_urbs(struct usb_serial_port *port,
331 					gfp_t mem_flags)
332 {
333 	int res;
334 	int i;
335 
336 	for (i = 0; i < ARRAY_SIZE(port->read_urbs); ++i) {
337 		res = usb_serial_generic_submit_read_urb(port, i, mem_flags);
338 		if (res)
339 			goto err;
340 	}
341 
342 	return 0;
343 err:
344 	for (; i >= 0; --i)
345 		usb_kill_urb(port->read_urbs[i]);
346 
347 	return res;
348 }
349 EXPORT_SYMBOL_GPL(usb_serial_generic_submit_read_urbs);
350 
351 void usb_serial_generic_process_read_urb(struct urb *urb)
352 {
353 	struct usb_serial_port *port = urb->context;
354 	char *ch = urb->transfer_buffer;
355 	int i;
356 
357 	if (!urb->actual_length)
358 		return;
359 	/*
360 	 * The per character mucking around with sysrq path it too slow for
361 	 * stuff like 3G modems, so shortcircuit it in the 99.9999999% of
362 	 * cases where the USB serial is not a console anyway.
363 	 */
364 	if (port->sysrq) {
365 		for (i = 0; i < urb->actual_length; i++, ch++) {
366 			if (!usb_serial_handle_sysrq_char(port, *ch))
367 				tty_insert_flip_char(&port->port, *ch, TTY_NORMAL);
368 		}
369 	} else {
370 		tty_insert_flip_string(&port->port, ch, urb->actual_length);
371 	}
372 	tty_flip_buffer_push(&port->port);
373 }
374 EXPORT_SYMBOL_GPL(usb_serial_generic_process_read_urb);
375 
376 void usb_serial_generic_read_bulk_callback(struct urb *urb)
377 {
378 	struct usb_serial_port *port = urb->context;
379 	unsigned char *data = urb->transfer_buffer;
380 	bool stopped = false;
381 	int status = urb->status;
382 	int i;
383 
384 	for (i = 0; i < ARRAY_SIZE(port->read_urbs); ++i) {
385 		if (urb == port->read_urbs[i])
386 			break;
387 	}
388 
389 	dev_dbg(&port->dev, "%s - urb %d, len %d\n", __func__, i,
390 							urb->actual_length);
391 	switch (status) {
392 	case 0:
393 		usb_serial_debug_data(&port->dev, __func__, urb->actual_length,
394 							data);
395 		port->serial->type->process_read_urb(urb);
396 		break;
397 	case -ENOENT:
398 	case -ECONNRESET:
399 	case -ESHUTDOWN:
400 		dev_dbg(&port->dev, "%s - urb stopped: %d\n",
401 							__func__, status);
402 		stopped = true;
403 		break;
404 	case -EPIPE:
405 		dev_err(&port->dev, "%s - urb stopped: %d\n",
406 							__func__, status);
407 		stopped = true;
408 		break;
409 	default:
410 		dev_dbg(&port->dev, "%s - nonzero urb status: %d\n",
411 							__func__, status);
412 		break;
413 	}
414 
415 	/*
416 	 * Make sure URB processing is done before marking as free to avoid
417 	 * racing with unthrottle() on another CPU. Matches the barriers
418 	 * implied by the test_and_clear_bit() in
419 	 * usb_serial_generic_submit_read_urb().
420 	 */
421 	smp_mb__before_atomic();
422 	set_bit(i, &port->read_urbs_free);
423 	/*
424 	 * Make sure URB is marked as free before checking the throttled flag
425 	 * to avoid racing with unthrottle() on another CPU. Matches the
426 	 * smp_mb__after_atomic() in unthrottle().
427 	 */
428 	smp_mb__after_atomic();
429 
430 	if (stopped)
431 		return;
432 
433 	if (test_bit(USB_SERIAL_THROTTLED, &port->flags))
434 		return;
435 
436 	usb_serial_generic_submit_read_urb(port, i, GFP_ATOMIC);
437 }
438 EXPORT_SYMBOL_GPL(usb_serial_generic_read_bulk_callback);
439 
440 void usb_serial_generic_write_bulk_callback(struct urb *urb)
441 {
442 	unsigned long flags;
443 	struct usb_serial_port *port = urb->context;
444 	int status = urb->status;
445 	int i;
446 
447 	for (i = 0; i < ARRAY_SIZE(port->write_urbs); ++i) {
448 		if (port->write_urbs[i] == urb)
449 			break;
450 	}
451 	spin_lock_irqsave(&port->lock, flags);
452 	port->tx_bytes -= urb->transfer_buffer_length;
453 	set_bit(i, &port->write_urbs_free);
454 	spin_unlock_irqrestore(&port->lock, flags);
455 
456 	switch (status) {
457 	case 0:
458 		break;
459 	case -ENOENT:
460 	case -ECONNRESET:
461 	case -ESHUTDOWN:
462 		dev_dbg(&port->dev, "%s - urb stopped: %d\n",
463 							__func__, status);
464 		return;
465 	case -EPIPE:
466 		dev_err_console(port, "%s - urb stopped: %d\n",
467 							__func__, status);
468 		return;
469 	default:
470 		dev_err_console(port, "%s - nonzero urb status: %d\n",
471 							__func__, status);
472 		break;
473 	}
474 
475 	usb_serial_generic_write_start(port, GFP_ATOMIC);
476 	usb_serial_port_softint(port);
477 }
478 EXPORT_SYMBOL_GPL(usb_serial_generic_write_bulk_callback);
479 
480 void usb_serial_generic_throttle(struct tty_struct *tty)
481 {
482 	struct usb_serial_port *port = tty->driver_data;
483 
484 	set_bit(USB_SERIAL_THROTTLED, &port->flags);
485 }
486 EXPORT_SYMBOL_GPL(usb_serial_generic_throttle);
487 
488 void usb_serial_generic_unthrottle(struct tty_struct *tty)
489 {
490 	struct usb_serial_port *port = tty->driver_data;
491 
492 	clear_bit(USB_SERIAL_THROTTLED, &port->flags);
493 
494 	/*
495 	 * Matches the smp_mb__after_atomic() in
496 	 * usb_serial_generic_read_bulk_callback().
497 	 */
498 	smp_mb__after_atomic();
499 
500 	usb_serial_generic_submit_read_urbs(port, GFP_KERNEL);
501 }
502 EXPORT_SYMBOL_GPL(usb_serial_generic_unthrottle);
503 
504 static bool usb_serial_generic_msr_changed(struct tty_struct *tty,
505 				unsigned long arg, struct async_icount *cprev)
506 {
507 	struct usb_serial_port *port = tty->driver_data;
508 	struct async_icount cnow;
509 	unsigned long flags;
510 	bool ret;
511 
512 	/*
513 	 * Use tty-port initialised flag to detect all hangups including the
514 	 * one generated at USB-device disconnect.
515 	 */
516 	if (!tty_port_initialized(&port->port))
517 		return true;
518 
519 	spin_lock_irqsave(&port->lock, flags);
520 	cnow = port->icount;				/* atomic copy*/
521 	spin_unlock_irqrestore(&port->lock, flags);
522 
523 	ret =	((arg & TIOCM_RNG) && (cnow.rng != cprev->rng)) ||
524 		((arg & TIOCM_DSR) && (cnow.dsr != cprev->dsr)) ||
525 		((arg & TIOCM_CD)  && (cnow.dcd != cprev->dcd)) ||
526 		((arg & TIOCM_CTS) && (cnow.cts != cprev->cts));
527 
528 	*cprev = cnow;
529 
530 	return ret;
531 }
532 
533 int usb_serial_generic_tiocmiwait(struct tty_struct *tty, unsigned long arg)
534 {
535 	struct usb_serial_port *port = tty->driver_data;
536 	struct async_icount cnow;
537 	unsigned long flags;
538 	int ret;
539 
540 	spin_lock_irqsave(&port->lock, flags);
541 	cnow = port->icount;				/* atomic copy */
542 	spin_unlock_irqrestore(&port->lock, flags);
543 
544 	ret = wait_event_interruptible(port->port.delta_msr_wait,
545 			usb_serial_generic_msr_changed(tty, arg, &cnow));
546 	if (!ret && !tty_port_initialized(&port->port))
547 		ret = -EIO;
548 
549 	return ret;
550 }
551 EXPORT_SYMBOL_GPL(usb_serial_generic_tiocmiwait);
552 
553 int usb_serial_generic_get_icount(struct tty_struct *tty,
554 					struct serial_icounter_struct *icount)
555 {
556 	struct usb_serial_port *port = tty->driver_data;
557 	struct async_icount cnow;
558 	unsigned long flags;
559 
560 	spin_lock_irqsave(&port->lock, flags);
561 	cnow = port->icount;				/* atomic copy */
562 	spin_unlock_irqrestore(&port->lock, flags);
563 
564 	icount->cts = cnow.cts;
565 	icount->dsr = cnow.dsr;
566 	icount->rng = cnow.rng;
567 	icount->dcd = cnow.dcd;
568 	icount->tx = cnow.tx;
569 	icount->rx = cnow.rx;
570 	icount->frame = cnow.frame;
571 	icount->parity = cnow.parity;
572 	icount->overrun = cnow.overrun;
573 	icount->brk = cnow.brk;
574 	icount->buf_overrun = cnow.buf_overrun;
575 
576 	return 0;
577 }
578 EXPORT_SYMBOL_GPL(usb_serial_generic_get_icount);
579 
580 #if defined(CONFIG_USB_SERIAL_CONSOLE) && defined(CONFIG_MAGIC_SYSRQ)
581 int usb_serial_handle_sysrq_char(struct usb_serial_port *port, unsigned int ch)
582 {
583 	if (port->sysrq) {
584 		if (ch && time_before(jiffies, port->sysrq)) {
585 			handle_sysrq(ch);
586 			port->sysrq = 0;
587 			return 1;
588 		}
589 		port->sysrq = 0;
590 	}
591 	return 0;
592 }
593 EXPORT_SYMBOL_GPL(usb_serial_handle_sysrq_char);
594 
595 int usb_serial_handle_break(struct usb_serial_port *port)
596 {
597 	if (!port->port.console)
598 		return 0;
599 
600 	if (!port->sysrq) {
601 		port->sysrq = jiffies + HZ*5;
602 		return 1;
603 	}
604 	port->sysrq = 0;
605 	return 0;
606 }
607 EXPORT_SYMBOL_GPL(usb_serial_handle_break);
608 #endif
609 
610 /**
611  * usb_serial_handle_dcd_change - handle a change of carrier detect state
612  * @port: usb-serial port
613  * @tty: tty for the port
614  * @status: new carrier detect status, nonzero if active
615  */
616 void usb_serial_handle_dcd_change(struct usb_serial_port *port,
617 				struct tty_struct *tty, unsigned int status)
618 {
619 	dev_dbg(&port->dev, "%s - status %d\n", __func__, status);
620 
621 	if (tty) {
622 		struct tty_ldisc *ld = tty_ldisc_ref(tty);
623 
624 		if (ld) {
625 			if (ld->ops->dcd_change)
626 				ld->ops->dcd_change(tty, status);
627 			tty_ldisc_deref(ld);
628 		}
629 	}
630 
631 	if (status)
632 		wake_up_interruptible(&port->port.open_wait);
633 	else if (tty && !C_CLOCAL(tty))
634 		tty_hangup(tty);
635 }
636 EXPORT_SYMBOL_GPL(usb_serial_handle_dcd_change);
637 
638 int usb_serial_generic_resume(struct usb_serial *serial)
639 {
640 	struct usb_serial_port *port;
641 	int i, c = 0, r;
642 
643 	for (i = 0; i < serial->num_ports; i++) {
644 		port = serial->port[i];
645 		if (!tty_port_initialized(&port->port))
646 			continue;
647 
648 		if (port->bulk_in_size) {
649 			r = usb_serial_generic_submit_read_urbs(port,
650 								GFP_NOIO);
651 			if (r < 0)
652 				c++;
653 		}
654 
655 		if (port->bulk_out_size) {
656 			r = usb_serial_generic_write_start(port, GFP_NOIO);
657 			if (r < 0)
658 				c++;
659 		}
660 	}
661 
662 	return c ? -EIO : 0;
663 }
664 EXPORT_SYMBOL_GPL(usb_serial_generic_resume);
665