1/*	$NetBSD: uftdi.c,v 1.79 2024/04/25 01:33:03 thorpej Exp $	*/
2
3/*
4 * Copyright (c) 2000 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Lennart Augustsson (lennart@augustsson.net).
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#include <sys/cdefs.h>
33__KERNEL_RCSID(0, "$NetBSD: uftdi.c,v 1.79 2024/04/25 01:33:03 thorpej Exp $");
34
35#ifdef _KERNEL_OPT
36#include "opt_usb.h"
37#endif
38
39#include <sys/param.h>
40#include <sys/systm.h>
41#include <sys/kernel.h>
42#include <sys/device.h>
43#include <sys/conf.h>
44#include <sys/tty.h>
45
46#include <dev/usb/usb.h>
47
48#include <dev/usb/usbdi.h>
49#include <dev/usb/usbdi_util.h>
50#include <dev/usb/usbdivar.h>
51#include <dev/usb/usbdevs.h>
52
53#include <dev/usb/ucomvar.h>
54
55#include <dev/usb/uftdireg.h>
56
57#ifdef UFTDI_DEBUG
58#define DPRINTF(x)	if (uftdidebug) printf x
59#define DPRINTFN(n,x)	if (uftdidebug>(n)) printf x
60int uftdidebug = 0;
61#else
62#define DPRINTF(x)
63#define DPRINTFN(n,x)
64#endif
65
66#define UFTDI_CONFIG_NO		1
67
68/*
69 * These are the default number of bytes transferred per frame if the
70 * endpoint doesn't tell us.  The output buffer size is a hard limit
71 * for devices that use a 6-bit size encoding.
72 */
73#define UFTDIIBUFSIZE 64
74#define UFTDIOBUFSIZE 64
75
76/*
77 * Magic constants!  Where do these come from?  They're what Linux uses...
78 */
79#define	UFTDI_MAX_IBUFSIZE	512
80#define	UFTDI_MAX_OBUFSIZE	256
81
82struct uftdi_softc {
83	device_t		sc_dev;		/* base device */
84	struct usbd_device *	sc_udev;	/* device */
85	struct usbd_interface *	sc_iface;	/* interface */
86	int			sc_iface_no;
87
88	enum uftdi_type		sc_type;
89	u_int			sc_flags;
90#define FLAGS_BAUDCLK_12M	0x00000001
91#define FLAGS_ROUNDOFF_232A	0x00000002
92#define FLAGS_BAUDBITS_HINDEX	0x00000004
93	u_int			sc_hdrlen;
94	u_int			sc_chiptype;
95
96	u_char			sc_msr;
97	u_char			sc_lsr;
98
99	device_t		sc_subdev;
100
101	bool			sc_dying;
102
103	u_int			last_lcr;
104};
105
106static void	uftdi_get_status(void *, int, u_char *, u_char *);
107static void	uftdi_set(void *, int, int, int);
108static int	uftdi_param(void *, int, struct termios *);
109static int	uftdi_open(void *, int);
110static void	uftdi_read(void *, int, u_char **, uint32_t *);
111static void	uftdi_write(void *, int, u_char *, u_char *, uint32_t *);
112static void	uftdi_break(void *, int, int);
113
114static const struct ucom_methods uftdi_methods = {
115	.ucom_get_status = uftdi_get_status,
116	.ucom_set = uftdi_set,
117	.ucom_param = uftdi_param,
118	.ucom_open = uftdi_open,
119	.ucom_read = uftdi_read,
120	.ucom_write = uftdi_write,
121};
122
123/*
124 * The devices default to UFTDI_TYPE_8U232AM.
125 * Remember to update uftdi_attach() if it should be UFTDI_TYPE_SIO instead
126 */
127static const struct usb_devno uftdi_devs[] = {
128	{ USB_VENDOR_BBELECTRONICS, USB_PRODUCT_BBELECTRONICS_USOTL4 },
129	{ USB_VENDOR_BRAINBOXES, USB_PRODUCT_BRAINBOXES_US101 },
130	{ USB_VENDOR_BRAINBOXES, USB_PRODUCT_BRAINBOXES_US159 },
131	{ USB_VENDOR_BRAINBOXES, USB_PRODUCT_BRAINBOXES_US235 },
132	{ USB_VENDOR_BRAINBOXES, USB_PRODUCT_BRAINBOXES_US257 },
133	{ USB_VENDOR_BRAINBOXES, USB_PRODUCT_BRAINBOXES_US279_12 },
134	{ USB_VENDOR_BRAINBOXES, USB_PRODUCT_BRAINBOXES_US279_34 },
135	{ USB_VENDOR_BRAINBOXES, USB_PRODUCT_BRAINBOXES_US279_56 },
136	{ USB_VENDOR_BRAINBOXES, USB_PRODUCT_BRAINBOXES_US279_78 },
137	{ USB_VENDOR_BRAINBOXES, USB_PRODUCT_BRAINBOXES_US313 },
138	{ USB_VENDOR_BRAINBOXES, USB_PRODUCT_BRAINBOXES_US320 },
139	{ USB_VENDOR_BRAINBOXES, USB_PRODUCT_BRAINBOXES_US324 },
140	{ USB_VENDOR_BRAINBOXES, USB_PRODUCT_BRAINBOXES_US346_12 },
141	{ USB_VENDOR_BRAINBOXES, USB_PRODUCT_BRAINBOXES_US346_34 },
142	{ USB_VENDOR_BRAINBOXES, USB_PRODUCT_BRAINBOXES_US701_12 },
143	{ USB_VENDOR_BRAINBOXES, USB_PRODUCT_BRAINBOXES_US701_34 },
144	{ USB_VENDOR_BRAINBOXES, USB_PRODUCT_BRAINBOXES_US842_12 },
145	{ USB_VENDOR_BRAINBOXES, USB_PRODUCT_BRAINBOXES_US842_34 },
146	{ USB_VENDOR_BRAINBOXES, USB_PRODUCT_BRAINBOXES_US842_56 },
147	{ USB_VENDOR_BRAINBOXES, USB_PRODUCT_BRAINBOXES_US842_78 },
148	{ USB_VENDOR_FALCOM, USB_PRODUCT_FALCOM_TWIST },
149	{ USB_VENDOR_FALCOM, USB_PRODUCT_FALCOM_SAMBA },
150	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_230X },
151	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_232H },
152	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_232RL },
153	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_2232C },
154	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_4232H },
155	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_8U100AX },
156	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_8U232AM },
157	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_KW },
158	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_YS },
159	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_Y6 },
160	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_Y8 },
161	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_IC },
162	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_DB9 },
163	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_RS232 },
164	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_Y9 },
165	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_COASTAL_TNCX },
166	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_CTI_485_MINI },
167	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_CTI_NANO_485 },
168	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SEMC_DSS20 },
169	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_LK202_24_USB },
170	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_LK204_24_USB },
171	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_MX200_USB },
172	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_MX4_MX5_USB },
173	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_CFA_631 },
174	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_CFA_632 },
175	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_CFA_633 },
176	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_CFA_634 },
177	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_CFA_635 },
178	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_OPENRD_JTAGKEY },
179	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_BEAGLEBONE },
180	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MAXSTREAM_PKG_U },
181	{ USB_VENDOR_xxFTDI, USB_PRODUCT_xxFTDI_SHEEVAPLUG_JTAG },
182	{ USB_VENDOR_INTREPIDCS, USB_PRODUCT_INTREPIDCS_VALUECAN },
183	{ USB_VENDOR_INTREPIDCS, USB_PRODUCT_INTREPIDCS_NEOVI },
184	{ USB_VENDOR_MELCO, USB_PRODUCT_MELCO_PCOPRS1 },
185	{ USB_VENDOR_RATOC, USB_PRODUCT_RATOC_REXUSB60F },
186	{ USB_VENDOR_RTSYS, USB_PRODUCT_RTSYS_CT57A },
187	{ USB_VENDOR_RTSYS, USB_PRODUCT_RTSYS_RTS03 },
188	{ USB_VENDOR_SEALEVEL, USB_PRODUCT_SEALEVEL_USBSERIAL },
189	{ USB_VENDOR_SEALEVEL, USB_PRODUCT_SEALEVEL_SEAPORT4P1 },
190	{ USB_VENDOR_SEALEVEL, USB_PRODUCT_SEALEVEL_SEAPORT4P2 },
191	{ USB_VENDOR_SEALEVEL, USB_PRODUCT_SEALEVEL_SEAPORT4P3 },
192	{ USB_VENDOR_SEALEVEL, USB_PRODUCT_SEALEVEL_SEAPORT4P4 },
193	{ USB_VENDOR_SIIG2, USB_PRODUCT_SIIG2_US2308 },
194	{ USB_VENDOR_MISC, USB_PRODUCT_MISC_TELLSTICK },
195	{ USB_VENDOR_MISC, USB_PRODUCT_MISC_TELLSTICK_DUO },
196};
197#define uftdi_lookup(v, p) usb_lookup(uftdi_devs, v, p)
198
199static int	uftdi_match(device_t, cfdata_t, void *);
200static void	uftdi_attach(device_t, device_t, void *);
201static void	uftdi_childdet(device_t, device_t);
202static int	uftdi_detach(device_t, int);
203
204CFATTACH_DECL2_NEW(uftdi, sizeof(struct uftdi_softc), uftdi_match,
205    uftdi_attach, uftdi_detach, NULL, NULL, uftdi_childdet);
206
207struct uftdi_match_quirk_entry {
208	uint16_t	vendor_id;
209	uint16_t	product_id;
210	int		iface_no;
211	const char *	vendor_str;
212	const char *	product_str;
213	int		match_ret;
214};
215
216static const struct uftdi_match_quirk_entry uftdi_match_quirks[] = {
217	/*
218	 * The Tigard board (https://github.com/tigard-tools/tigard)
219	 * has two interfaces, one of which is meant to act as a
220	 * regular USB serial port (interface 0), the other of which
221	 * is meant for other protocols (SWD, JTAG, etc.).  We must
222	 * reject interface 1 so that ugenif matches, thus allowing
223	 * full user-space control of that port.
224	 */
225	{
226	  .vendor_id	= USB_VENDOR_FTDI,
227	  .product_id	= USB_PRODUCT_FTDI_SERIAL_2232C,
228	  .iface_no	= 1,
229	  .vendor_str	= "SecuringHardware.com",
230	  .product_str	= "Tigard V1.1",
231	  .match_ret	= UMATCH_NONE,
232	},
233	/*
234	 * The SiPEED Tang Nano 9K (and other SiPEED Tang FPGA development
235	 * boards) have an FT2232 on-board, wired up only for JTAG.
236	 */
237	{
238	  .vendor_id	= USB_VENDOR_FTDI,
239	  .product_id	= USB_PRODUCT_FTDI_SERIAL_2232C,
240	  .iface_no	= -1,
241	  .vendor_str	= "SIPEED",
242	  .product_str	= "JTAG Debugger",
243	  .match_ret	= UMATCH_NONE,
244	},
245};
246
247static int
248uftdi_quirk_match(struct usbif_attach_arg *uiaa, int rv)
249{
250	struct usbd_device *dev = uiaa->uiaa_device;
251	const struct uftdi_match_quirk_entry *q;
252	int i;
253
254	for (i = 0; i < __arraycount(uftdi_match_quirks); i++) {
255		q = &uftdi_match_quirks[i];
256		if (uiaa->uiaa_vendor != q->vendor_id ||
257		    uiaa->uiaa_product != q->product_id ||
258		    (q->iface_no != -1 && uiaa->uiaa_ifaceno != q->iface_no)) {
259			continue;
260		}
261		if (q->vendor_str != NULL &&
262		    (dev->ud_vendor == NULL ||
263		     strcmp(dev->ud_vendor, q->vendor_str) != 0)) {
264			continue;
265		}
266		if (q->product_str != NULL &&
267		    (dev->ud_product == NULL ||
268		     strcmp(dev->ud_product, q->product_str) != 0)) {
269			continue;
270		}
271		/*
272		 * Got a match!
273		 */
274		rv = q->match_ret;
275		break;
276	}
277	return rv;
278}
279
280static int
281uftdi_match(device_t parent, cfdata_t match, void *aux)
282{
283	struct usbif_attach_arg *uiaa = aux;
284	int rv;
285
286	DPRINTFN(20,("uftdi: vendor=%#x, product=%#x\n",
287		     uiaa->uiaa_vendor, uiaa->uiaa_product));
288
289	if (uiaa->uiaa_configno != UFTDI_CONFIG_NO)
290		return UMATCH_NONE;
291
292	rv = uftdi_lookup(uiaa->uiaa_vendor, uiaa->uiaa_product) != NULL ?
293		UMATCH_VENDOR_PRODUCT_CONF_IFACE : UMATCH_NONE;
294	if (rv != UMATCH_NONE) {
295		rv = uftdi_quirk_match(uiaa, rv);
296	}
297	return rv;
298}
299
300static void
301uftdi_attach(device_t parent, device_t self, void *aux)
302{
303	struct uftdi_softc *sc = device_private(self);
304	struct usbif_attach_arg *uiaa = aux;
305	struct usbd_device *dev = uiaa->uiaa_device;
306	struct usbd_interface *iface = uiaa->uiaa_iface;
307	usb_device_descriptor_t *ddesc;
308	usb_interface_descriptor_t *id;
309	usb_endpoint_descriptor_t *ed;
310	char *devinfop;
311	int i;
312	struct ucom_attach_args ucaa;
313
314	DPRINTFN(10,("\nuftdi_attach: sc=%p\n", sc));
315
316	aprint_naive("\n");
317	aprint_normal("\n");
318
319	devinfop = usbd_devinfo_alloc(dev, 0);
320	aprint_normal_dev(self, "%s\n", devinfop);
321	usbd_devinfo_free(devinfop);
322
323	sc->sc_dev = self;
324	sc->sc_udev = dev;
325	sc->sc_dying = false;
326	sc->sc_iface_no = uiaa->uiaa_ifaceno;
327	sc->sc_type = UFTDI_TYPE_8U232AM; /* most devices are post-8U232AM */
328	sc->sc_hdrlen = 0;
329
330	ddesc = usbd_get_device_descriptor(dev);
331	sc->sc_chiptype = UGETW(ddesc->bcdDevice);
332
333	switch (sc->sc_chiptype) {
334	case 0x0200:
335		if (ddesc->iSerialNumber != 0)
336			sc->sc_flags |= FLAGS_ROUNDOFF_232A;
337		ucaa.ucaa_portno = 0;
338		break;
339	case 0x0400:
340		ucaa.ucaa_portno = 0;
341		break;
342	case 0x0500:
343		sc->sc_flags |= FLAGS_BAUDBITS_HINDEX;
344		ucaa.ucaa_portno = FTDI_PIT_SIOA + sc->sc_iface_no;
345		break;
346	case 0x0600:
347		ucaa.ucaa_portno = 0;
348		break;
349	case 0x0700:
350	case 0x0800:
351	case 0x0900:
352		sc->sc_flags |= FLAGS_BAUDCLK_12M;
353		sc->sc_flags |= FLAGS_BAUDBITS_HINDEX;
354		ucaa.ucaa_portno = FTDI_PIT_SIOA + sc->sc_iface_no;
355		break;
356	case 0x1000:
357		sc->sc_flags |= FLAGS_BAUDBITS_HINDEX;
358		ucaa.ucaa_portno = FTDI_PIT_SIOA + sc->sc_iface_no;
359		break;
360	default:
361		if (sc->sc_chiptype < 0x0200) {
362			sc->sc_type = UFTDI_TYPE_SIO;
363			sc->sc_hdrlen = 1;
364		}
365		ucaa.ucaa_portno = 0;
366		break;
367	}
368
369	id = usbd_get_interface_descriptor(iface);
370
371	sc->sc_iface = iface;
372
373	ucaa.ucaa_bulkin = ucaa.ucaa_bulkout = -1;
374	ucaa.ucaa_ibufsize = ucaa.ucaa_obufsize = 0;
375	for (i = 0; i < id->bNumEndpoints; i++) {
376		int addr, dir, attr;
377		ed = usbd_interface2endpoint_descriptor(iface, i);
378		if (ed == NULL) {
379			aprint_error_dev(self,
380			    "could not read endpoint descriptor\n");
381			goto bad;
382		}
383
384		addr = ed->bEndpointAddress;
385		dir = UE_GET_DIR(ed->bEndpointAddress);
386		attr = ed->bmAttributes & UE_XFERTYPE;
387		if (dir == UE_DIR_IN && attr == UE_BULK) {
388			ucaa.ucaa_bulkin = addr;
389			ucaa.ucaa_ibufsize = UGETW(ed->wMaxPacketSize);
390			if (ucaa.ucaa_ibufsize >= UFTDI_MAX_IBUFSIZE)
391				ucaa.ucaa_ibufsize = UFTDI_MAX_IBUFSIZE;
392		} else if (dir == UE_DIR_OUT && attr == UE_BULK) {
393			ucaa.ucaa_bulkout = addr;
394			ucaa.ucaa_obufsize = UGETW(ed->wMaxPacketSize)
395			    - sc->sc_hdrlen;
396			if (ucaa.ucaa_obufsize >= UFTDI_MAX_OBUFSIZE)
397				ucaa.ucaa_obufsize = UFTDI_MAX_OBUFSIZE;
398			/* Limit length if we have a 6-bit header.  */
399			if ((sc->sc_hdrlen > 0) &&
400			    (ucaa.ucaa_obufsize > UFTDIOBUFSIZE))
401				ucaa.ucaa_obufsize = UFTDIOBUFSIZE;
402		} else {
403			aprint_error_dev(self, "unexpected endpoint\n");
404			goto bad;
405		}
406	}
407	if (ucaa.ucaa_bulkin == -1) {
408		aprint_error_dev(self, "Could not find data bulk in\n");
409		goto bad;
410	}
411	if (ucaa.ucaa_bulkout == -1) {
412		aprint_error_dev(self, "Could not find data bulk out\n");
413		goto bad;
414	}
415
416	/* ucaa_bulkin, ucaa_bulkout set above */
417	if (ucaa.ucaa_ibufsize == 0)
418		ucaa.ucaa_ibufsize = UFTDIIBUFSIZE;
419	ucaa.ucaa_ibufsizepad = ucaa.ucaa_ibufsize;
420	if (ucaa.ucaa_obufsize == 0)
421		ucaa.ucaa_obufsize = UFTDIOBUFSIZE - sc->sc_hdrlen;
422	ucaa.ucaa_opkthdrlen = sc->sc_hdrlen;
423	ucaa.ucaa_device = dev;
424	ucaa.ucaa_iface = iface;
425	ucaa.ucaa_methods = &uftdi_methods;
426	ucaa.ucaa_arg = sc;
427	ucaa.ucaa_info = NULL;
428
429	DPRINTF(("uftdi: in=%#x out=%#x isize=%#x osize=%#x\n",
430		ucaa.ucaa_bulkin, ucaa.ucaa_bulkout,
431		ucaa.ucaa_ibufsize, ucaa.ucaa_obufsize));
432	sc->sc_subdev = config_found(self, &ucaa, ucomprint,
433	    CFARGS(.submatch = ucomsubmatch));
434
435	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev, sc->sc_dev);
436
437	if (!pmf_device_register(self, NULL, NULL))
438		aprint_error_dev(self, "couldn't establish power handler\n");
439
440	return;
441
442bad:
443	DPRINTF(("uftdi_attach: ATTACH ERROR\n"));
444	sc->sc_dying = true;
445	return;
446}
447
448static void
449uftdi_childdet(device_t self, device_t child)
450{
451	struct uftdi_softc *sc = device_private(self);
452
453	KASSERT(child == sc->sc_subdev);
454	sc->sc_subdev = NULL;
455}
456
457static int
458uftdi_detach(device_t self, int flags)
459{
460	struct uftdi_softc *sc = device_private(self);
461	int rv = 0;
462
463	DPRINTF(("uftdi_detach: sc=%p flags=%d\n", sc, flags));
464
465	sc->sc_dying = true;
466
467	if (sc->sc_subdev != NULL) {
468		rv = config_detach(sc->sc_subdev, flags);
469		sc->sc_subdev = NULL;
470	}
471
472	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev, sc->sc_dev);
473
474	return rv;
475}
476
477static int
478uftdi_open(void *vsc, int portno)
479{
480	struct uftdi_softc *sc = vsc;
481	usb_device_request_t req;
482	usbd_status err;
483	struct termios t;
484
485	DPRINTF(("uftdi_open: sc=%p\n", sc));
486
487	if (sc->sc_dying)
488		return EIO;
489
490	/* Perform a full reset on the device */
491	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
492	req.bRequest = FTDI_SIO_RESET;
493	USETW(req.wValue, FTDI_SIO_RESET_SIO);
494	USETW(req.wIndex, portno);
495	USETW(req.wLength, 0);
496	err = usbd_do_request(sc->sc_udev, &req, NULL);
497	if (err)
498		return EIO;
499
500	/* Set 9600 baud, 2 stop bits, no parity, 8 bits */
501	t.c_ospeed = 9600;
502	t.c_cflag = CSTOPB | CS8;
503	(void)uftdi_param(sc, portno, &t);
504
505	/* Turn on RTS/CTS flow control */
506	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
507	req.bRequest = FTDI_SIO_SET_FLOW_CTRL;
508	USETW(req.wValue, 0);
509	USETW2(req.wIndex, FTDI_SIO_RTS_CTS_HS, portno);
510	USETW(req.wLength, 0);
511	err = usbd_do_request(sc->sc_udev, &req, NULL);
512	if (err)
513		return EIO;
514
515	return 0;
516}
517
518static void
519uftdi_read(void *vsc, int portno, u_char **ptr, uint32_t *count)
520{
521	struct uftdi_softc *sc = vsc;
522	u_char msr, lsr;
523
524	DPRINTFN(15,("uftdi_read: sc=%p, port=%d count=%d\n", sc, portno,
525		     *count));
526
527	msr = FTDI_GET_MSR(*ptr);
528	lsr = FTDI_GET_LSR(*ptr);
529
530#ifdef UFTDI_DEBUG
531	if (*count != 2)
532		DPRINTFN(10,("uftdi_read: sc=%p, port=%d count=%d data[0]="
533			    "0x%02x\n", sc, portno, *count, (*ptr)[2]));
534#endif
535
536	if (sc->sc_msr != msr ||
537	    (sc->sc_lsr & FTDI_LSR_MASK) != (lsr & FTDI_LSR_MASK)) {
538		DPRINTF(("uftdi_read: status change msr=0x%02x(0x%02x) "
539			 "lsr=0x%02x(0x%02x)\n", msr, sc->sc_msr,
540			 lsr, sc->sc_lsr));
541		sc->sc_msr = msr;
542		sc->sc_lsr = lsr;
543		ucom_status_change(device_private(sc->sc_subdev));
544	}
545
546	/* Adjust buffer pointer to skip status prefix */
547	*ptr += 2;
548}
549
550static void
551uftdi_write(void *vsc, int portno, u_char *to, u_char *from, uint32_t *count)
552{
553	struct uftdi_softc *sc = vsc;
554
555	DPRINTFN(10,("uftdi_write: sc=%p, port=%d count=%u data[0]=0x%02x\n",
556		     vsc, portno, *count, from[0]));
557
558	/* Make length tag and copy data */
559	if (sc->sc_hdrlen > 0)
560		*to = FTDI_OUT_TAG(*count, portno);
561
562	memcpy(to + sc->sc_hdrlen, from, *count);
563	*count += sc->sc_hdrlen;
564}
565
566static void
567uftdi_set(void *vsc, int portno, int reg, int onoff)
568{
569	struct uftdi_softc *sc = vsc;
570	usb_device_request_t req;
571	int ctl;
572
573	DPRINTF(("uftdi_set: sc=%p, port=%d reg=%d onoff=%d\n", vsc, portno,
574		 reg, onoff));
575
576	if (sc->sc_dying)
577		return;
578
579	switch (reg) {
580	case UCOM_SET_DTR:
581		ctl = onoff ? FTDI_SIO_SET_DTR_HIGH : FTDI_SIO_SET_DTR_LOW;
582		break;
583	case UCOM_SET_RTS:
584		ctl = onoff ? FTDI_SIO_SET_RTS_HIGH : FTDI_SIO_SET_RTS_LOW;
585		break;
586	case UCOM_SET_BREAK:
587		uftdi_break(sc, portno, onoff);
588		return;
589	default:
590		return;
591	}
592	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
593	req.bRequest = FTDI_SIO_MODEM_CTRL;
594	USETW(req.wValue, ctl);
595	USETW(req.wIndex, portno);
596	USETW(req.wLength, 0);
597	DPRINTFN(2,("uftdi_set: reqtype=0x%02x req=0x%02x value=0x%04x "
598		    "index=0x%04x len=%d\n", req.bmRequestType, req.bRequest,
599		    UGETW(req.wValue), UGETW(req.wIndex), UGETW(req.wLength)));
600	(void)usbd_do_request(sc->sc_udev, &req, NULL);
601}
602
603/*
604 * Return true if the given speed is within operational tolerance of the target
605 * speed.  FTDI recommends that the hardware speed be within 3% of nominal.
606 */
607static inline bool
608uftdi_baud_within_tolerance(uint64_t speed, uint64_t target)
609{
610	return ((speed >= (target * 100) / 103) &&
611	    (speed <= (target * 100) / 97));
612}
613
614static int
615uftdi_encode_baudrate(struct uftdi_softc *sc, int speed, int *rate, int *ratehi)
616{
617	static const uint8_t encoded_fraction[8] = {
618	    0, 3, 2, 4, 1, 5, 6, 7
619	};
620	static const uint8_t roundoff_232a[16] = {
621	    0,  1,  0,  1,  0, -1,  2,  1,
622	    0, -1, -2, -3,  4,  3,  2,  1,
623	};
624	uint32_t clk, divisor, fastclk_flag, frac, hwspeed;
625
626	/*
627	 * If this chip has the fast clock capability and the speed is within
628	 * range, use the 12MHz clock, otherwise the standard clock is 3MHz.
629	 */
630	if ((sc->sc_flags & FLAGS_BAUDCLK_12M) && speed >= 1200) {
631		clk = 12000000;
632		fastclk_flag = (1 << 17);
633	} else {
634		clk = 3000000;
635		fastclk_flag = 0;
636	}
637
638	/*
639	 * Make sure the requested speed is reachable with the available clock
640	 * and a 14-bit divisor.
641	 */
642	if (speed < (clk >> 14) || speed > clk)
643		return -1;
644
645	/*
646	 * Calculate the divisor, initially yielding a fixed point number with a
647	 * 4-bit (1/16ths) fraction, then round it to the nearest fraction the
648	 * hardware can handle.  When the integral part of the divisor is
649	 * greater than one, the fractional part is in 1/8ths of the base clock.
650	 * The FT8U232AM chips can handle only 0.125, 0.250, and 0.5 fractions.
651	 * Later chips can handle all 1/8th fractions.
652	 *
653	 * If the integral part of the divisor is 1, a special rule applies: the
654	 * fractional part can only be .0 or .5 (this is a limitation of the
655	 * hardware).  We handle this by truncating the fraction rather than
656	 * rounding, because this only applies to the two fastest speeds the
657	 * chip can achieve and rounding doesn't matter, either you've asked for
658	 * that exact speed or you've asked for something the chip can't do.
659	 *
660	 * For the FT8U232AM chips, use a roundoff table to adjust the result
661	 * to the nearest 1/8th fraction that is supported by the hardware,
662	 * leaving a fixed-point number with a 3-bit fraction which exactly
663	 * represents the math the hardware divider will do.  For later-series
664	 * chips that support all 8 fractional divisors, just round 16ths to
665	 * 8ths by adding 1 and dividing by 2.
666	 */
667	divisor = (clk << 4) / speed;
668	if ((divisor & 0xf) == 1)
669		divisor &= 0xfffffff8;
670	else if (sc->sc_flags & FLAGS_ROUNDOFF_232A)
671		divisor += roundoff_232a[divisor & 0x0f];
672	else
673		divisor += 1;  /* Rounds odd 16ths up to next 8th. */
674	divisor >>= 1;
675
676	/*
677	 * Ensure the resulting hardware speed will be within operational
678	 * tolerance (within 3% of nominal).
679	 */
680	hwspeed = (clk << 3) / divisor;
681	if (!uftdi_baud_within_tolerance(hwspeed, speed))
682		return -1;
683
684	/*
685	 * Re-pack the divisor into hardware format. The lower 14-bits hold the
686	 * integral part, while the upper bits specify the fraction by indexing
687	 * a table of fractions within the hardware which is laid out as:
688	 *    {0.0, 0.5, 0.25, 0.125, 0.325, 0.625, 0.725, 0.875}
689	 * The A-series chips only have the first four table entries; the
690	 * roundoff table logic above ensures that the fractional part for those
691	 * chips will be one of the first four values.
692	 *
693	 * When the divisor is 1 a special encoding applies:  1.0 is encoded as
694	 * 0.0, and 1.5 is encoded as 1.0.  The rounding logic above has already
695	 * ensured that the fraction is either .0 or .5 if the integral is 1.
696	 */
697	frac = divisor & 0x07;
698	divisor >>= 3;
699	if (divisor == 1) {
700		if (frac == 0)
701			divisor = 0;	/* 1.0 becomes 0.0 */
702		else
703			frac = 0;	/* 1.5 becomes 1.0 */
704	}
705	divisor |= (encoded_fraction[frac] << 14) | fastclk_flag;
706
707	*rate = (uint16_t)divisor;
708	*ratehi = (uint16_t)(divisor >> 16);
709
710	/*
711	 * If this chip requires the baud bits to be in the high byte of the
712	 * index word, move the bits up to that location.
713	 */
714	if (sc->sc_flags & FLAGS_BAUDBITS_HINDEX)
715		*ratehi <<= 8;
716
717	return 0;
718}
719
720static int
721uftdi_param(void *vsc, int portno, struct termios *t)
722{
723	struct uftdi_softc *sc = vsc;
724	usb_device_request_t req;
725	usbd_status err;
726	int rate, ratehi, rerr, data, flow;
727
728	DPRINTF(("uftdi_param: sc=%p\n", sc));
729
730	if (sc->sc_dying)
731		return EIO;
732
733	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
734	req.bRequest = FTDI_SIO_SET_BITMODE;
735	USETW(req.wValue, FTDI_BITMODE_RESET << 8 | 0x00);
736	USETW(req.wIndex, portno);
737	USETW(req.wLength, 0);
738	err = usbd_do_request(sc->sc_udev, &req, NULL);
739	if (err)
740		return EIO;
741
742	switch (sc->sc_type) {
743	case UFTDI_TYPE_SIO:
744		switch (t->c_ospeed) {
745		case 300: rate = ftdi_sio_b300; break;
746		case 600: rate = ftdi_sio_b600; break;
747		case 1200: rate = ftdi_sio_b1200; break;
748		case 2400: rate = ftdi_sio_b2400; break;
749		case 4800: rate = ftdi_sio_b4800; break;
750		case 9600: rate = ftdi_sio_b9600; break;
751		case 19200: rate = ftdi_sio_b19200; break;
752		case 38400: rate = ftdi_sio_b38400; break;
753		case 57600: rate = ftdi_sio_b57600; break;
754		case 115200: rate = ftdi_sio_b115200; break;
755		default:
756			return EINVAL;
757		}
758		ratehi = 0;
759		break;
760	case UFTDI_TYPE_8U232AM:
761		rerr = uftdi_encode_baudrate(sc, t->c_ospeed, &rate, &ratehi);
762		if (rerr != 0)
763			return EINVAL;
764		break;
765	default:
766		return EINVAL;
767	}
768	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
769	req.bRequest = FTDI_SIO_SET_BAUD_RATE;
770	USETW(req.wValue, rate);
771	USETW(req.wIndex, portno | ratehi);
772	USETW(req.wLength, 0);
773	DPRINTFN(2,("uftdi_param: reqtype=0x%02x req=0x%02x value=0x%04x "
774		    "index=0x%04x len=%d\n", req.bmRequestType, req.bRequest,
775		    UGETW(req.wValue), UGETW(req.wIndex), UGETW(req.wLength)));
776	err = usbd_do_request(sc->sc_udev, &req, NULL);
777	if (err)
778		return EIO;
779
780	if (ISSET(t->c_cflag, CSTOPB))
781		data = FTDI_SIO_SET_DATA_STOP_BITS_2;
782	else
783		data = FTDI_SIO_SET_DATA_STOP_BITS_1;
784	if (ISSET(t->c_cflag, PARENB)) {
785		if (ISSET(t->c_cflag, PARODD))
786			data |= FTDI_SIO_SET_DATA_PARITY_ODD;
787		else
788			data |= FTDI_SIO_SET_DATA_PARITY_EVEN;
789	} else
790		data |= FTDI_SIO_SET_DATA_PARITY_NONE;
791	switch (ISSET(t->c_cflag, CSIZE)) {
792	case CS5:
793		data |= FTDI_SIO_SET_DATA_BITS(5);
794		break;
795	case CS6:
796		data |= FTDI_SIO_SET_DATA_BITS(6);
797		break;
798	case CS7:
799		data |= FTDI_SIO_SET_DATA_BITS(7);
800		break;
801	case CS8:
802		data |= FTDI_SIO_SET_DATA_BITS(8);
803		break;
804	}
805	sc->last_lcr = data;
806
807	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
808	req.bRequest = FTDI_SIO_SET_DATA;
809	USETW(req.wValue, data);
810	USETW(req.wIndex, portno);
811	USETW(req.wLength, 0);
812	DPRINTFN(2,("uftdi_param: reqtype=0x%02x req=0x%02x value=0x%04x "
813		    "index=0x%04x len=%d\n", req.bmRequestType, req.bRequest,
814		    UGETW(req.wValue), UGETW(req.wIndex), UGETW(req.wLength)));
815	err = usbd_do_request(sc->sc_udev, &req, NULL);
816	if (err)
817		return EIO;
818
819	if (ISSET(t->c_cflag, CRTSCTS)) {
820		flow = FTDI_SIO_RTS_CTS_HS;
821		USETW(req.wValue, 0);
822	} else if (ISSET(t->c_iflag, IXON) && ISSET(t->c_iflag, IXOFF)) {
823		flow = FTDI_SIO_XON_XOFF_HS;
824		USETW2(req.wValue, t->c_cc[VSTOP], t->c_cc[VSTART]);
825	} else {
826		flow = FTDI_SIO_DISABLE_FLOW_CTRL;
827		USETW(req.wValue, 0);
828	}
829	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
830	req.bRequest = FTDI_SIO_SET_FLOW_CTRL;
831	USETW2(req.wIndex, flow, portno);
832	USETW(req.wLength, 0);
833	err = usbd_do_request(sc->sc_udev, &req, NULL);
834	if (err)
835		return EIO;
836
837	return 0;
838}
839
840static void
841uftdi_get_status(void *vsc, int portno, u_char *lsr, u_char *msr)
842{
843	struct uftdi_softc *sc = vsc;
844
845	DPRINTF(("uftdi_status: msr=0x%02x lsr=0x%02x\n",
846		 sc->sc_msr, sc->sc_lsr));
847
848	if (sc->sc_dying)
849		return;
850
851	*msr = sc->sc_msr;
852	*lsr = sc->sc_lsr;
853}
854
855static void
856uftdi_break(void *vsc, int portno, int onoff)
857{
858	struct uftdi_softc *sc = vsc;
859	usb_device_request_t req;
860	int data;
861
862	DPRINTF(("uftdi_break: sc=%p, port=%d onoff=%d\n", vsc, portno,
863		  onoff));
864
865	if (onoff) {
866		data = sc->last_lcr | FTDI_SIO_SET_BREAK;
867	} else {
868		data = sc->last_lcr;
869	}
870
871	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
872	req.bRequest = FTDI_SIO_SET_DATA;
873	USETW(req.wValue, data);
874	USETW(req.wIndex, portno);
875	USETW(req.wLength, 0);
876	(void)usbd_do_request(sc->sc_udev, &req, NULL);
877}
878