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