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