Home | History | Annotate | Line # | Download | only in usb
uftdi.c revision 1.74.6.1
      1 /*	$NetBSD: uftdi.c,v 1.74.6.1 2021/03/22 02:01:02 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 (at) 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.74.6.1 2021/03/22 02:01:02 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/usbdevs.h>
     51 
     52 #include <dev/usb/ucomvar.h>
     53 
     54 #include <dev/usb/uftdireg.h>
     55 
     56 #ifdef UFTDI_DEBUG
     57 #define DPRINTF(x)	if (uftdidebug) printf x
     58 #define DPRINTFN(n,x)	if (uftdidebug>(n)) printf x
     59 int uftdidebug = 0;
     60 #else
     61 #define DPRINTF(x)
     62 #define DPRINTFN(n,x)
     63 #endif
     64 
     65 #define UFTDI_CONFIG_NO		1
     66 
     67 /*
     68  * These are the default number of bytes transferred per frame if the
     69  * endpoint doesn't tell us.  The output buffer size is a hard limit
     70  * for devices that use a 6-bit size encoding.
     71  */
     72 #define UFTDIIBUFSIZE 64
     73 #define UFTDIOBUFSIZE 64
     74 
     75 /*
     76  * Magic constants!  Where do these come from?  They're what Linux uses...
     77  */
     78 #define	UFTDI_MAX_IBUFSIZE	512
     79 #define	UFTDI_MAX_OBUFSIZE	256
     80 
     81 struct uftdi_softc {
     82 	device_t		sc_dev;		/* base device */
     83 	struct usbd_device *	sc_udev;	/* device */
     84 	struct usbd_interface *	sc_iface;	/* interface */
     85 	int			sc_iface_no;
     86 
     87 	enum uftdi_type		sc_type;
     88 	u_int			sc_flags;
     89 #define FLAGS_BAUDCLK_12M	0x00000001
     90 #define FLAGS_ROUNDOFF_232A	0x00000002
     91 #define FLAGS_BAUDBITS_HINDEX	0x00000004
     92 	u_int			sc_hdrlen;
     93 	u_int			sc_chiptype;
     94 
     95 	u_char			sc_msr;
     96 	u_char			sc_lsr;
     97 
     98 	device_t		sc_subdev;
     99 
    100 	bool			sc_dying;
    101 
    102 	u_int			last_lcr;
    103 };
    104 
    105 static void	uftdi_get_status(void *, int, u_char *, u_char *);
    106 static void	uftdi_set(void *, int, int, int);
    107 static int	uftdi_param(void *, int, struct termios *);
    108 static int	uftdi_open(void *, int);
    109 static void	uftdi_read(void *, int, u_char **, uint32_t *);
    110 static void	uftdi_write(void *, int, u_char *, u_char *, uint32_t *);
    111 static void	uftdi_break(void *, int, int);
    112 
    113 static const struct ucom_methods uftdi_methods = {
    114 	.ucom_get_status = uftdi_get_status,
    115 	.ucom_set = uftdi_set,
    116 	.ucom_param = uftdi_param,
    117 	.ucom_open = uftdi_open,
    118 	.ucom_read = uftdi_read,
    119 	.ucom_write = uftdi_write,
    120 };
    121 
    122 /*
    123  * The devices default to UFTDI_TYPE_8U232AM.
    124  * Remember to update uftdi_attach() if it should be UFTDI_TYPE_SIO instead
    125  */
    126 static const struct usb_devno uftdi_devs[] = {
    127 	{ USB_VENDOR_BBELECTRONICS, USB_PRODUCT_BBELECTRONICS_USOTL4 },
    128 	{ USB_VENDOR_FALCOM, USB_PRODUCT_FALCOM_TWIST },
    129 	{ USB_VENDOR_FALCOM, USB_PRODUCT_FALCOM_SAMBA },
    130 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_230X },
    131 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_232H },
    132 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_232RL },
    133 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_2232C },
    134 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_4232H },
    135 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_8U100AX },
    136 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SERIAL_8U232AM },
    137 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_KW },
    138 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_YS },
    139 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_Y6 },
    140 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_Y8 },
    141 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_IC },
    142 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_DB9 },
    143 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_RS232 },
    144 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MHAM_Y9 },
    145 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_COASTAL_TNCX },
    146 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_CTI_485_MINI },
    147 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_CTI_NANO_485 },
    148 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_SEMC_DSS20 },
    149 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_LK202_24_USB },
    150 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_LK204_24_USB },
    151 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_MX200_USB },
    152 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_MX4_MX5_USB },
    153 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_CFA_631 },
    154 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_CFA_632 },
    155 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_CFA_633 },
    156 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_CFA_634 },
    157 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_LCD_CFA_635 },
    158 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_OPENRD_JTAGKEY },
    159 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_BEAGLEBONE },
    160 	{ USB_VENDOR_FTDI, USB_PRODUCT_FTDI_MAXSTREAM_PKG_U },
    161 	{ USB_VENDOR_xxFTDI, USB_PRODUCT_xxFTDI_SHEEVAPLUG_JTAG },
    162 	{ USB_VENDOR_INTREPIDCS, USB_PRODUCT_INTREPIDCS_VALUECAN },
    163 	{ USB_VENDOR_INTREPIDCS, USB_PRODUCT_INTREPIDCS_NEOVI },
    164 	{ USB_VENDOR_MELCO, USB_PRODUCT_MELCO_PCOPRS1 },
    165 	{ USB_VENDOR_RATOC, USB_PRODUCT_RATOC_REXUSB60F },
    166 	{ USB_VENDOR_RTSYS, USB_PRODUCT_RTSYS_CT57A },
    167 	{ USB_VENDOR_RTSYS, USB_PRODUCT_RTSYS_RTS03 },
    168 	{ USB_VENDOR_SEALEVEL, USB_PRODUCT_SEALEVEL_USBSERIAL },
    169 	{ USB_VENDOR_SEALEVEL, USB_PRODUCT_SEALEVEL_SEAPORT4P1 },
    170 	{ USB_VENDOR_SEALEVEL, USB_PRODUCT_SEALEVEL_SEAPORT4P2 },
    171 	{ USB_VENDOR_SEALEVEL, USB_PRODUCT_SEALEVEL_SEAPORT4P3 },
    172 	{ USB_VENDOR_SEALEVEL, USB_PRODUCT_SEALEVEL_SEAPORT4P4 },
    173 	{ USB_VENDOR_SIIG2, USB_PRODUCT_SIIG2_US2308 },
    174 	{ USB_VENDOR_MISC, USB_PRODUCT_MISC_TELLSTICK },
    175 	{ USB_VENDOR_MISC, USB_PRODUCT_MISC_TELLSTICK_DUO },
    176 };
    177 #define uftdi_lookup(v, p) usb_lookup(uftdi_devs, v, p)
    178 
    179 static int	uftdi_match(device_t, cfdata_t, void *);
    180 static void	uftdi_attach(device_t, device_t, void *);
    181 static void	uftdi_childdet(device_t, device_t);
    182 static int	uftdi_detach(device_t, int);
    183 
    184 CFATTACH_DECL2_NEW(uftdi, sizeof(struct uftdi_softc), uftdi_match,
    185     uftdi_attach, uftdi_detach, NULL, NULL, uftdi_childdet);
    186 
    187 static int
    188 uftdi_match(device_t parent, cfdata_t match, void *aux)
    189 {
    190 	struct usbif_attach_arg *uiaa = aux;
    191 
    192 	DPRINTFN(20,("uftdi: vendor=%#x, product=%#x\n",
    193 		     uiaa->uiaa_vendor, uiaa->uiaa_product));
    194 
    195 	if (uiaa->uiaa_configno != UFTDI_CONFIG_NO)
    196 		return UMATCH_NONE;
    197 
    198 	return uftdi_lookup(uiaa->uiaa_vendor, uiaa->uiaa_product) != NULL ?
    199 		UMATCH_VENDOR_PRODUCT_CONF_IFACE : UMATCH_NONE;
    200 }
    201 
    202 static void
    203 uftdi_attach(device_t parent, device_t self, void *aux)
    204 {
    205 	struct uftdi_softc *sc = device_private(self);
    206 	struct usbif_attach_arg *uiaa = aux;
    207 	struct usbd_device *dev = uiaa->uiaa_device;
    208 	struct usbd_interface *iface = uiaa->uiaa_iface;
    209 	usb_device_descriptor_t *ddesc;
    210 	usb_interface_descriptor_t *id;
    211 	usb_endpoint_descriptor_t *ed;
    212 	char *devinfop;
    213 	int i;
    214 	struct ucom_attach_args ucaa;
    215 
    216 	DPRINTFN(10,("\nuftdi_attach: sc=%p\n", sc));
    217 
    218 	aprint_naive("\n");
    219 	aprint_normal("\n");
    220 
    221 	devinfop = usbd_devinfo_alloc(dev, 0);
    222 	aprint_normal_dev(self, "%s\n", devinfop);
    223 	usbd_devinfo_free(devinfop);
    224 
    225 	sc->sc_dev = self;
    226 	sc->sc_udev = dev;
    227 	sc->sc_dying = false;
    228 	sc->sc_iface_no = uiaa->uiaa_ifaceno;
    229 	sc->sc_type = UFTDI_TYPE_8U232AM; /* most devices are post-8U232AM */
    230 	sc->sc_hdrlen = 0;
    231 
    232 	ddesc = usbd_get_device_descriptor(dev);
    233 	sc->sc_chiptype = UGETW(ddesc->bcdDevice);
    234 
    235 	switch (sc->sc_chiptype) {
    236 	case 0x0200:
    237 		if (ddesc->iSerialNumber != 0)
    238 			sc->sc_flags |= FLAGS_ROUNDOFF_232A;
    239 		ucaa.ucaa_portno = 0;
    240 		break;
    241 	case 0x0400:
    242 		ucaa.ucaa_portno = 0;
    243 		break;
    244 	case 0x0500:
    245 		sc->sc_flags |= FLAGS_BAUDBITS_HINDEX;
    246 		ucaa.ucaa_portno = FTDI_PIT_SIOA + sc->sc_iface_no;
    247 		break;
    248 	case 0x0600:
    249 		ucaa.ucaa_portno = 0;
    250 		break;
    251 	case 0x0700:
    252 	case 0x0800:
    253 	case 0x0900:
    254 		sc->sc_flags |= FLAGS_BAUDCLK_12M;
    255 		sc->sc_flags |= FLAGS_BAUDBITS_HINDEX;
    256 		ucaa.ucaa_portno = FTDI_PIT_SIOA + sc->sc_iface_no;
    257 		break;
    258 	case 0x1000:
    259 		sc->sc_flags |= FLAGS_BAUDBITS_HINDEX;
    260 		ucaa.ucaa_portno = FTDI_PIT_SIOA + sc->sc_iface_no;
    261 		break;
    262 	default:
    263 		if (sc->sc_chiptype < 0x0200) {
    264 			sc->sc_type = UFTDI_TYPE_SIO;
    265 			sc->sc_hdrlen = 1;
    266 		}
    267 		ucaa.ucaa_portno = 0;
    268 		break;
    269 	}
    270 
    271 	id = usbd_get_interface_descriptor(iface);
    272 
    273 	sc->sc_iface = iface;
    274 
    275 	ucaa.ucaa_bulkin = ucaa.ucaa_bulkout = -1;
    276 	ucaa.ucaa_ibufsize = ucaa.ucaa_obufsize = 0;
    277 	for (i = 0; i < id->bNumEndpoints; i++) {
    278 		int addr, dir, attr;
    279 		ed = usbd_interface2endpoint_descriptor(iface, i);
    280 		if (ed == NULL) {
    281 			aprint_error_dev(self,
    282 			    "could not read endpoint descriptor\n");
    283 			goto bad;
    284 		}
    285 
    286 		addr = ed->bEndpointAddress;
    287 		dir = UE_GET_DIR(ed->bEndpointAddress);
    288 		attr = ed->bmAttributes & UE_XFERTYPE;
    289 		if (dir == UE_DIR_IN && attr == UE_BULK) {
    290 			ucaa.ucaa_bulkin = addr;
    291 			ucaa.ucaa_ibufsize = UGETW(ed->wMaxPacketSize);
    292 			if (ucaa.ucaa_ibufsize >= UFTDI_MAX_IBUFSIZE)
    293 				ucaa.ucaa_ibufsize = UFTDI_MAX_IBUFSIZE;
    294 		} else if (dir == UE_DIR_OUT && attr == UE_BULK) {
    295 			ucaa.ucaa_bulkout = addr;
    296 			ucaa.ucaa_obufsize = UGETW(ed->wMaxPacketSize)
    297 			    - sc->sc_hdrlen;
    298 			if (ucaa.ucaa_obufsize >= UFTDI_MAX_OBUFSIZE)
    299 				ucaa.ucaa_obufsize = UFTDI_MAX_OBUFSIZE;
    300 			/* Limit length if we have a 6-bit header.  */
    301 			if ((sc->sc_hdrlen > 0) &&
    302 			    (ucaa.ucaa_obufsize > UFTDIOBUFSIZE))
    303 				ucaa.ucaa_obufsize = UFTDIOBUFSIZE;
    304 		} else {
    305 			aprint_error_dev(self, "unexpected endpoint\n");
    306 			goto bad;
    307 		}
    308 	}
    309 	if (ucaa.ucaa_bulkin == -1) {
    310 		aprint_error_dev(self, "Could not find data bulk in\n");
    311 		goto bad;
    312 	}
    313 	if (ucaa.ucaa_bulkout == -1) {
    314 		aprint_error_dev(self, "Could not find data bulk out\n");
    315 		goto bad;
    316 	}
    317 
    318 	/* ucaa_bulkin, ucaa_bulkout set above */
    319 	if (ucaa.ucaa_ibufsize == 0)
    320 		ucaa.ucaa_ibufsize = UFTDIIBUFSIZE;
    321 	ucaa.ucaa_ibufsizepad = ucaa.ucaa_ibufsize;
    322 	if (ucaa.ucaa_obufsize == 0)
    323 		ucaa.ucaa_obufsize = UFTDIOBUFSIZE - sc->sc_hdrlen;
    324 	ucaa.ucaa_opkthdrlen = sc->sc_hdrlen;
    325 	ucaa.ucaa_device = dev;
    326 	ucaa.ucaa_iface = iface;
    327 	ucaa.ucaa_methods = &uftdi_methods;
    328 	ucaa.ucaa_arg = sc;
    329 	ucaa.ucaa_info = NULL;
    330 
    331 	DPRINTF(("uftdi: in=%#x out=%#x isize=%#x osize=%#x\n",
    332 		ucaa.ucaa_bulkin, ucaa.ucaa_bulkout,
    333 		ucaa.ucaa_ibufsize, ucaa.ucaa_obufsize));
    334 	sc->sc_subdev = config_found(self, &ucaa, ucomprint,
    335 				     CFARG_SUBMATCH, ucomsubmatch,
    336 				     CFARG_IATTR, "ucombus",
    337 				     CFARG_EOL);
    338 
    339 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev, sc->sc_dev);
    340 
    341 	if (!pmf_device_register(self, NULL, NULL))
    342 		aprint_error_dev(self, "couldn't establish power handler\n");
    343 
    344 	return;
    345 
    346 bad:
    347 	DPRINTF(("uftdi_attach: ATTACH ERROR\n"));
    348 	sc->sc_dying = true;
    349 	return;
    350 }
    351 
    352 static void
    353 uftdi_childdet(device_t self, device_t child)
    354 {
    355 	struct uftdi_softc *sc = device_private(self);
    356 
    357 	KASSERT(child == sc->sc_subdev);
    358 	sc->sc_subdev = NULL;
    359 }
    360 
    361 static int
    362 uftdi_detach(device_t self, int flags)
    363 {
    364 	struct uftdi_softc *sc = device_private(self);
    365 	int rv = 0;
    366 
    367 	DPRINTF(("uftdi_detach: sc=%p flags=%d\n", sc, flags));
    368 
    369 	sc->sc_dying = true;
    370 
    371 	if (sc->sc_subdev != NULL) {
    372 		rv = config_detach(sc->sc_subdev, flags);
    373 		sc->sc_subdev = NULL;
    374 	}
    375 
    376 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev, sc->sc_dev);
    377 
    378 	return rv;
    379 }
    380 
    381 static int
    382 uftdi_open(void *vsc, int portno)
    383 {
    384 	struct uftdi_softc *sc = vsc;
    385 	usb_device_request_t req;
    386 	usbd_status err;
    387 	struct termios t;
    388 
    389 	DPRINTF(("uftdi_open: sc=%p\n", sc));
    390 
    391 	if (sc->sc_dying)
    392 		return EIO;
    393 
    394 	/* Perform a full reset on the device */
    395 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
    396 	req.bRequest = FTDI_SIO_RESET;
    397 	USETW(req.wValue, FTDI_SIO_RESET_SIO);
    398 	USETW(req.wIndex, portno);
    399 	USETW(req.wLength, 0);
    400 	err = usbd_do_request(sc->sc_udev, &req, NULL);
    401 	if (err)
    402 		return EIO;
    403 
    404 	/* Set 9600 baud, 2 stop bits, no parity, 8 bits */
    405 	t.c_ospeed = 9600;
    406 	t.c_cflag = CSTOPB | CS8;
    407 	(void)uftdi_param(sc, portno, &t);
    408 
    409 	/* Turn on RTS/CTS flow control */
    410 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
    411 	req.bRequest = FTDI_SIO_SET_FLOW_CTRL;
    412 	USETW(req.wValue, 0);
    413 	USETW2(req.wIndex, FTDI_SIO_RTS_CTS_HS, portno);
    414 	USETW(req.wLength, 0);
    415 	err = usbd_do_request(sc->sc_udev, &req, NULL);
    416 	if (err)
    417 		return EIO;
    418 
    419 	return 0;
    420 }
    421 
    422 static void
    423 uftdi_read(void *vsc, int portno, u_char **ptr, uint32_t *count)
    424 {
    425 	struct uftdi_softc *sc = vsc;
    426 	u_char msr, lsr;
    427 
    428 	DPRINTFN(15,("uftdi_read: sc=%p, port=%d count=%d\n", sc, portno,
    429 		     *count));
    430 
    431 	msr = FTDI_GET_MSR(*ptr);
    432 	lsr = FTDI_GET_LSR(*ptr);
    433 
    434 #ifdef UFTDI_DEBUG
    435 	if (*count != 2)
    436 		DPRINTFN(10,("uftdi_read: sc=%p, port=%d count=%d data[0]="
    437 			    "0x%02x\n", sc, portno, *count, (*ptr)[2]));
    438 #endif
    439 
    440 	if (sc->sc_msr != msr ||
    441 	    (sc->sc_lsr & FTDI_LSR_MASK) != (lsr & FTDI_LSR_MASK)) {
    442 		DPRINTF(("uftdi_read: status change msr=0x%02x(0x%02x) "
    443 			 "lsr=0x%02x(0x%02x)\n", msr, sc->sc_msr,
    444 			 lsr, sc->sc_lsr));
    445 		sc->sc_msr = msr;
    446 		sc->sc_lsr = lsr;
    447 		ucom_status_change(device_private(sc->sc_subdev));
    448 	}
    449 
    450 	/* Adjust buffer pointer to skip status prefix */
    451 	*ptr += 2;
    452 }
    453 
    454 static void
    455 uftdi_write(void *vsc, int portno, u_char *to, u_char *from, uint32_t *count)
    456 {
    457 	struct uftdi_softc *sc = vsc;
    458 
    459 	DPRINTFN(10,("uftdi_write: sc=%p, port=%d count=%u data[0]=0x%02x\n",
    460 		     vsc, portno, *count, from[0]));
    461 
    462 	/* Make length tag and copy data */
    463 	if (sc->sc_hdrlen > 0)
    464 		*to = FTDI_OUT_TAG(*count, portno);
    465 
    466 	memcpy(to + sc->sc_hdrlen, from, *count);
    467 	*count += sc->sc_hdrlen;
    468 }
    469 
    470 static void
    471 uftdi_set(void *vsc, int portno, int reg, int onoff)
    472 {
    473 	struct uftdi_softc *sc = vsc;
    474 	usb_device_request_t req;
    475 	int ctl;
    476 
    477 	DPRINTF(("uftdi_set: sc=%p, port=%d reg=%d onoff=%d\n", vsc, portno,
    478 		 reg, onoff));
    479 
    480 	if (sc->sc_dying)
    481 		return;
    482 
    483 	switch (reg) {
    484 	case UCOM_SET_DTR:
    485 		ctl = onoff ? FTDI_SIO_SET_DTR_HIGH : FTDI_SIO_SET_DTR_LOW;
    486 		break;
    487 	case UCOM_SET_RTS:
    488 		ctl = onoff ? FTDI_SIO_SET_RTS_HIGH : FTDI_SIO_SET_RTS_LOW;
    489 		break;
    490 	case UCOM_SET_BREAK:
    491 		uftdi_break(sc, portno, onoff);
    492 		return;
    493 	default:
    494 		return;
    495 	}
    496 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
    497 	req.bRequest = FTDI_SIO_MODEM_CTRL;
    498 	USETW(req.wValue, ctl);
    499 	USETW(req.wIndex, portno);
    500 	USETW(req.wLength, 0);
    501 	DPRINTFN(2,("uftdi_set: reqtype=0x%02x req=0x%02x value=0x%04x "
    502 		    "index=0x%04x len=%d\n", req.bmRequestType, req.bRequest,
    503 		    UGETW(req.wValue), UGETW(req.wIndex), UGETW(req.wLength)));
    504 	(void)usbd_do_request(sc->sc_udev, &req, NULL);
    505 }
    506 
    507 /*
    508  * Return true if the given speed is within operational tolerance of the target
    509  * speed.  FTDI recommends that the hardware speed be within 3% of nominal.
    510  */
    511 static inline bool
    512 uftdi_baud_within_tolerance(uint64_t speed, uint64_t target)
    513 {
    514 	return ((speed >= (target * 100) / 103) &&
    515 	    (speed <= (target * 100) / 97));
    516 }
    517 
    518 static int
    519 uftdi_encode_baudrate(struct uftdi_softc *sc, int speed, int *rate, int *ratehi)
    520 {
    521 	static const uint8_t encoded_fraction[8] = {
    522 	    0, 3, 2, 4, 1, 5, 6, 7
    523 	};
    524 	static const uint8_t roundoff_232a[16] = {
    525 	    0,  1,  0,  1,  0, -1,  2,  1,
    526 	    0, -1, -2, -3,  4,  3,  2,  1,
    527 	};
    528 	uint32_t clk, divisor, fastclk_flag, frac, hwspeed;
    529 
    530 	/*
    531 	 * If this chip has the fast clock capability and the speed is within
    532 	 * range, use the 12MHz clock, otherwise the standard clock is 3MHz.
    533 	 */
    534 	if ((sc->sc_flags & FLAGS_BAUDCLK_12M) && speed >= 1200) {
    535 		clk = 12000000;
    536 		fastclk_flag = (1 << 17);
    537 	} else {
    538 		clk = 3000000;
    539 		fastclk_flag = 0;
    540 	}
    541 
    542 	/*
    543 	 * Make sure the requested speed is reachable with the available clock
    544 	 * and a 14-bit divisor.
    545 	 */
    546 	if (speed < (clk >> 14) || speed > clk)
    547 		return -1;
    548 
    549 	/*
    550 	 * Calculate the divisor, initially yielding a fixed point number with a
    551 	 * 4-bit (1/16ths) fraction, then round it to the nearest fraction the
    552 	 * hardware can handle.  When the integral part of the divisor is
    553 	 * greater than one, the fractional part is in 1/8ths of the base clock.
    554 	 * The FT8U232AM chips can handle only 0.125, 0.250, and 0.5 fractions.
    555 	 * Later chips can handle all 1/8th fractions.
    556 	 *
    557 	 * If the integral part of the divisor is 1, a special rule applies: the
    558 	 * fractional part can only be .0 or .5 (this is a limitation of the
    559 	 * hardware).  We handle this by truncating the fraction rather than
    560 	 * rounding, because this only applies to the two fastest speeds the
    561 	 * chip can achieve and rounding doesn't matter, either you've asked for
    562 	 * that exact speed or you've asked for something the chip can't do.
    563 	 *
    564 	 * For the FT8U232AM chips, use a roundoff table to adjust the result
    565 	 * to the nearest 1/8th fraction that is supported by the hardware,
    566 	 * leaving a fixed-point number with a 3-bit fraction which exactly
    567 	 * represents the math the hardware divider will do.  For later-series
    568 	 * chips that support all 8 fractional divisors, just round 16ths to
    569 	 * 8ths by adding 1 and dividing by 2.
    570 	 */
    571 	divisor = (clk << 4) / speed;
    572 	if ((divisor & 0xf) == 1)
    573 		divisor &= 0xfffffff8;
    574 	else if (sc->sc_flags & FLAGS_ROUNDOFF_232A)
    575 		divisor += roundoff_232a[divisor & 0x0f];
    576 	else
    577 		divisor += 1;  /* Rounds odd 16ths up to next 8th. */
    578 	divisor >>= 1;
    579 
    580 	/*
    581 	 * Ensure the resulting hardware speed will be within operational
    582 	 * tolerance (within 3% of nominal).
    583 	 */
    584 	hwspeed = (clk << 3) / divisor;
    585 	if (!uftdi_baud_within_tolerance(hwspeed, speed))
    586 		return -1;
    587 
    588 	/*
    589 	 * Re-pack the divisor into hardware format. The lower 14-bits hold the
    590 	 * integral part, while the upper bits specify the fraction by indexing
    591 	 * a table of fractions within the hardware which is laid out as:
    592 	 *    {0.0, 0.5, 0.25, 0.125, 0.325, 0.625, 0.725, 0.875}
    593 	 * The A-series chips only have the first four table entries; the
    594 	 * roundoff table logic above ensures that the fractional part for those
    595 	 * chips will be one of the first four values.
    596 	 *
    597 	 * When the divisor is 1 a special encoding applies:  1.0 is encoded as
    598 	 * 0.0, and 1.5 is encoded as 1.0.  The rounding logic above has already
    599 	 * ensured that the fraction is either .0 or .5 if the integral is 1.
    600 	 */
    601 	frac = divisor & 0x07;
    602 	divisor >>= 3;
    603 	if (divisor == 1) {
    604 		if (frac == 0)
    605 			divisor = 0;	/* 1.0 becomes 0.0 */
    606 		else
    607 			frac = 0;	/* 1.5 becomes 1.0 */
    608 	}
    609 	divisor |= (encoded_fraction[frac] << 14) | fastclk_flag;
    610 
    611 	*rate = (uint16_t)divisor;
    612 	*ratehi = (uint16_t)(divisor >> 16);
    613 
    614 	/*
    615 	 * If this chip requires the baud bits to be in the high byte of the
    616 	 * index word, move the bits up to that location.
    617 	 */
    618 	if (sc->sc_flags & FLAGS_BAUDBITS_HINDEX)
    619 		*ratehi <<= 8;
    620 
    621 	return 0;
    622 }
    623 
    624 static int
    625 uftdi_param(void *vsc, int portno, struct termios *t)
    626 {
    627 	struct uftdi_softc *sc = vsc;
    628 	usb_device_request_t req;
    629 	usbd_status err;
    630 	int rate, ratehi, rerr, data, flow;
    631 
    632 	DPRINTF(("uftdi_param: sc=%p\n", sc));
    633 
    634 	if (sc->sc_dying)
    635 		return EIO;
    636 
    637 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
    638 	req.bRequest = FTDI_SIO_SET_BITMODE;
    639 	USETW(req.wValue, FTDI_BITMODE_RESET << 8 | 0x00);
    640 	USETW(req.wIndex, portno);
    641 	USETW(req.wLength, 0);
    642 	err = usbd_do_request(sc->sc_udev, &req, NULL);
    643 	if (err)
    644 		return EIO;
    645 
    646 	switch (sc->sc_type) {
    647 	case UFTDI_TYPE_SIO:
    648 		switch (t->c_ospeed) {
    649 		case 300: rate = ftdi_sio_b300; break;
    650 		case 600: rate = ftdi_sio_b600; break;
    651 		case 1200: rate = ftdi_sio_b1200; break;
    652 		case 2400: rate = ftdi_sio_b2400; break;
    653 		case 4800: rate = ftdi_sio_b4800; break;
    654 		case 9600: rate = ftdi_sio_b9600; break;
    655 		case 19200: rate = ftdi_sio_b19200; break;
    656 		case 38400: rate = ftdi_sio_b38400; break;
    657 		case 57600: rate = ftdi_sio_b57600; break;
    658 		case 115200: rate = ftdi_sio_b115200; break;
    659 		default:
    660 			return EINVAL;
    661 		}
    662 		ratehi = 0;
    663 		break;
    664 	case UFTDI_TYPE_8U232AM:
    665 		rerr = uftdi_encode_baudrate(sc, t->c_ospeed, &rate, &ratehi);
    666 		if (rerr != 0)
    667 			return EINVAL;
    668 		break;
    669 	default:
    670 		return EINVAL;
    671 	}
    672 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
    673 	req.bRequest = FTDI_SIO_SET_BAUD_RATE;
    674 	USETW(req.wValue, rate);
    675 	USETW(req.wIndex, portno | ratehi);
    676 	USETW(req.wLength, 0);
    677 	DPRINTFN(2,("uftdi_param: reqtype=0x%02x req=0x%02x value=0x%04x "
    678 		    "index=0x%04x len=%d\n", req.bmRequestType, req.bRequest,
    679 		    UGETW(req.wValue), UGETW(req.wIndex), UGETW(req.wLength)));
    680 	err = usbd_do_request(sc->sc_udev, &req, NULL);
    681 	if (err)
    682 		return EIO;
    683 
    684 	if (ISSET(t->c_cflag, CSTOPB))
    685 		data = FTDI_SIO_SET_DATA_STOP_BITS_2;
    686 	else
    687 		data = FTDI_SIO_SET_DATA_STOP_BITS_1;
    688 	if (ISSET(t->c_cflag, PARENB)) {
    689 		if (ISSET(t->c_cflag, PARODD))
    690 			data |= FTDI_SIO_SET_DATA_PARITY_ODD;
    691 		else
    692 			data |= FTDI_SIO_SET_DATA_PARITY_EVEN;
    693 	} else
    694 		data |= FTDI_SIO_SET_DATA_PARITY_NONE;
    695 	switch (ISSET(t->c_cflag, CSIZE)) {
    696 	case CS5:
    697 		data |= FTDI_SIO_SET_DATA_BITS(5);
    698 		break;
    699 	case CS6:
    700 		data |= FTDI_SIO_SET_DATA_BITS(6);
    701 		break;
    702 	case CS7:
    703 		data |= FTDI_SIO_SET_DATA_BITS(7);
    704 		break;
    705 	case CS8:
    706 		data |= FTDI_SIO_SET_DATA_BITS(8);
    707 		break;
    708 	}
    709 	sc->last_lcr = data;
    710 
    711 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
    712 	req.bRequest = FTDI_SIO_SET_DATA;
    713 	USETW(req.wValue, data);
    714 	USETW(req.wIndex, portno);
    715 	USETW(req.wLength, 0);
    716 	DPRINTFN(2,("uftdi_param: reqtype=0x%02x req=0x%02x value=0x%04x "
    717 		    "index=0x%04x len=%d\n", req.bmRequestType, req.bRequest,
    718 		    UGETW(req.wValue), UGETW(req.wIndex), UGETW(req.wLength)));
    719 	err = usbd_do_request(sc->sc_udev, &req, NULL);
    720 	if (err)
    721 		return EIO;
    722 
    723 	if (ISSET(t->c_cflag, CRTSCTS)) {
    724 		flow = FTDI_SIO_RTS_CTS_HS;
    725 		USETW(req.wValue, 0);
    726 	} else if (ISSET(t->c_iflag, IXON) && ISSET(t->c_iflag, IXOFF)) {
    727 		flow = FTDI_SIO_XON_XOFF_HS;
    728 		USETW2(req.wValue, t->c_cc[VSTOP], t->c_cc[VSTART]);
    729 	} else {
    730 		flow = FTDI_SIO_DISABLE_FLOW_CTRL;
    731 		USETW(req.wValue, 0);
    732 	}
    733 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
    734 	req.bRequest = FTDI_SIO_SET_FLOW_CTRL;
    735 	USETW2(req.wIndex, flow, portno);
    736 	USETW(req.wLength, 0);
    737 	err = usbd_do_request(sc->sc_udev, &req, NULL);
    738 	if (err)
    739 		return EIO;
    740 
    741 	return 0;
    742 }
    743 
    744 static void
    745 uftdi_get_status(void *vsc, int portno, u_char *lsr, u_char *msr)
    746 {
    747 	struct uftdi_softc *sc = vsc;
    748 
    749 	DPRINTF(("uftdi_status: msr=0x%02x lsr=0x%02x\n",
    750 		 sc->sc_msr, sc->sc_lsr));
    751 
    752 	if (sc->sc_dying)
    753 		return;
    754 
    755 	*msr = sc->sc_msr;
    756 	*lsr = sc->sc_lsr;
    757 }
    758 
    759 static void
    760 uftdi_break(void *vsc, int portno, int onoff)
    761 {
    762 	struct uftdi_softc *sc = vsc;
    763 	usb_device_request_t req;
    764 	int data;
    765 
    766 	DPRINTF(("uftdi_break: sc=%p, port=%d onoff=%d\n", vsc, portno,
    767 		  onoff));
    768 
    769 	if (onoff) {
    770 		data = sc->last_lcr | FTDI_SIO_SET_BREAK;
    771 	} else {
    772 		data = sc->last_lcr;
    773 	}
    774 
    775 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
    776 	req.bRequest = FTDI_SIO_SET_DATA;
    777 	USETW(req.wValue, data);
    778 	USETW(req.wIndex, portno);
    779 	USETW(req.wLength, 0);
    780 	(void)usbd_do_request(sc->sc_udev, &req, NULL);
    781 }
    782