Home | History | Annotate | Line # | Download | only in usb
      1 /*	$NetBSD: uchcom.c,v 1.40 2021/08/07 16:19:17 thorpej Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2007 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Takuya SHIOZAKI (tshiozak (at) netbsd.org).
      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: uchcom.c,v 1.40 2021/08/07 16:19:17 thorpej Exp $");
     34 
     35 #ifdef _KERNEL_OPT
     36 #include "opt_usb.h"
     37 #endif
     38 
     39 /*
     40  * driver for WinChipHead CH341/340, the worst USB-serial chip in the world.
     41  */
     42 
     43 #include <sys/param.h>
     44 #include <sys/systm.h>
     45 #include <sys/kernel.h>
     46 #include <sys/kmem.h>
     47 #include <sys/ioctl.h>
     48 #include <sys/conf.h>
     49 #include <sys/tty.h>
     50 #include <sys/file.h>
     51 #include <sys/select.h>
     52 #include <sys/proc.h>
     53 #include <sys/device.h>
     54 #include <sys/poll.h>
     55 
     56 #include <dev/usb/usb.h>
     57 
     58 #include <dev/usb/usbdi.h>
     59 #include <dev/usb/usbdi_util.h>
     60 #include <dev/usb/usbdevs.h>
     61 
     62 #include <dev/usb/ucomvar.h>
     63 
     64 #ifdef UCHCOM_DEBUG
     65 #define DPRINTFN(n, x)  if (uchcomdebug > (n)) printf x
     66 int	uchcomdebug = 0;
     67 #else
     68 #define DPRINTFN(n, x)
     69 #endif
     70 #define DPRINTF(x) DPRINTFN(0, x)
     71 
     72 #define	UCHCOM_IFACE_INDEX	0
     73 #define	UCHCOM_CONFIG_INDEX	0
     74 
     75 #define UCHCOM_INPUT_BUF_SIZE	8
     76 
     77 #define UCHCOM_REQ_GET_VERSION	0x5F
     78 #define UCHCOM_REQ_READ_REG	0x95
     79 #define UCHCOM_REQ_WRITE_REG	0x9A
     80 #define UCHCOM_REQ_RESET	0xA1
     81 #define UCHCOM_REQ_SET_DTRRTS	0xA4
     82 
     83 #define UCHCOM_REG_STAT1	0x06
     84 #define UCHCOM_REG_STAT2	0x07
     85 #define UCHCOM_REG_BPS_PRE	0x12
     86 #define UCHCOM_REG_BPS_DIV	0x13
     87 #define UCHCOM_REG_BREAK	0x05
     88 #define UCHCOM_REG_LCR		0x18
     89 #define UCHCOM_REG_LCR2		0x25
     90 
     91 #define UCHCOM_VER_20		0x20
     92 #define UCHCOM_VER_30		0x30
     93 
     94 #define UCHCOM_BPS_PRE_IMM	0x80	/* CH341: immediate RX forwarding */
     95 
     96 #define UCHCOM_DTR_MASK		0x20
     97 #define UCHCOM_RTS_MASK		0x40
     98 
     99 #define UCHCOM_BREAK_MASK	0x01
    100 
    101 #define UCHCOM_LCR_CS5		0x00
    102 #define UCHCOM_LCR_CS6		0x01
    103 #define UCHCOM_LCR_CS7		0x02
    104 #define UCHCOM_LCR_CS8		0x03
    105 #define UCHCOM_LCR_STOPB	0x04
    106 #define UCHCOM_LCR_PARENB	0x08
    107 #define UCHCOM_LCR_PARODD	0x00
    108 #define UCHCOM_LCR_PAREVEN	0x10
    109 #define UCHCOM_LCR_PARMARK	0x20
    110 #define UCHCOM_LCR_PARSPACE	0x30
    111 #define UCHCOM_LCR_TXE		0x40
    112 #define UCHCOM_LCR_RXE		0x80
    113 
    114 #define UCHCOM_INTR_STAT1	0x02
    115 #define UCHCOM_INTR_STAT2	0x03
    116 #define UCHCOM_INTR_LEAST	4
    117 
    118 #define UCHCOMIBUFSIZE 256
    119 #define UCHCOMOBUFSIZE 256
    120 
    121 struct uchcom_softc
    122 {
    123 	device_t		sc_dev;
    124 	struct usbd_device *	sc_udev;
    125 	device_t		sc_subdev;
    126 	struct usbd_interface *	sc_iface;
    127 	bool			sc_dying;
    128 	/* */
    129 	int			sc_intr_endpoint;
    130 	int			sc_intr_size;
    131 	struct usbd_pipe *	sc_intr_pipe;
    132 	u_char			*sc_intr_buf;
    133 	/* */
    134 	uint8_t			sc_version;
    135 	int			sc_dtr;
    136 	int			sc_rts;
    137 	u_char			sc_lsr;
    138 	u_char			sc_msr;
    139 };
    140 
    141 struct uchcom_endpoints
    142 {
    143 	int		ep_bulkin;
    144 	int		ep_bulkout;
    145 	int		ep_intr;
    146 	int		ep_intr_size;
    147 };
    148 
    149 struct uchcom_divider
    150 {
    151 	uint8_t		dv_prescaler;
    152 	uint8_t		dv_div;
    153 };
    154 
    155 /* 0,1,2,3,7 are prescale factors for given 4x 12000000 clock formula */
    156 static const uint32_t rates4x[8] = {
    157 	[0] = 4 * 12000000 / 1024,
    158 	[1] = 4 * 12000000 / 128,
    159 	[2] = 4 * 12000000 / 16,
    160 	[3] = 4 * 12000000 / 2,
    161 	[7] = 4 * 12000000,
    162 };
    163 
    164 static const struct usb_devno uchcom_devs[] = {
    165 	{ USB_VENDOR_QINHENG2, USB_PRODUCT_QINHENG2_CH341SER },
    166 	{ USB_VENDOR_QINHENG, USB_PRODUCT_QINHENG_CH340 },
    167 	{ USB_VENDOR_QINHENG, USB_PRODUCT_QINHENG_CH341_ASP },
    168 };
    169 #define uchcom_lookup(v, p)	usb_lookup(uchcom_devs, v, p)
    170 
    171 static void	uchcom_get_status(void *, int, u_char *, u_char *);
    172 static void	uchcom_set(void *, int, int, int);
    173 static int	uchcom_param(void *, int, struct termios *);
    174 static int	uchcom_open(void *, int);
    175 static void	uchcom_close(void *, int);
    176 static void	uchcom_intr(struct usbd_xfer *, void *,
    177 			    usbd_status);
    178 
    179 static int	set_config(struct uchcom_softc *);
    180 static int	find_ifaces(struct uchcom_softc *, struct usbd_interface **);
    181 static int	find_endpoints(struct uchcom_softc *,
    182 			       struct uchcom_endpoints *);
    183 static void	close_intr_pipe(struct uchcom_softc *);
    184 
    185 
    186 static const struct	ucom_methods uchcom_methods = {
    187 	.ucom_get_status	= uchcom_get_status,
    188 	.ucom_set		= uchcom_set,
    189 	.ucom_param		= uchcom_param,
    190 	.ucom_open		= uchcom_open,
    191 	.ucom_close		= uchcom_close,
    192 };
    193 
    194 static int	uchcom_match(device_t, cfdata_t, void *);
    195 static void	uchcom_attach(device_t, device_t, void *);
    196 static void	uchcom_childdet(device_t, device_t);
    197 static int	uchcom_detach(device_t, int);
    198 
    199 CFATTACH_DECL2_NEW(uchcom,
    200     sizeof(struct uchcom_softc),
    201     uchcom_match,
    202     uchcom_attach,
    203     uchcom_detach,
    204     NULL,
    205     NULL,
    206     uchcom_childdet);
    207 
    208 /* ----------------------------------------------------------------------
    209  * driver entry points
    210  */
    211 
    212 static int
    213 uchcom_match(device_t parent, cfdata_t match, void *aux)
    214 {
    215 	struct usb_attach_arg *uaa = aux;
    216 
    217 	return (uchcom_lookup(uaa->uaa_vendor, uaa->uaa_product) != NULL ?
    218 		UMATCH_VENDOR_PRODUCT : UMATCH_NONE);
    219 }
    220 
    221 static void
    222 uchcom_attach(device_t parent, device_t self, void *aux)
    223 {
    224 	struct uchcom_softc *sc = device_private(self);
    225 	struct usb_attach_arg *uaa = aux;
    226 	struct usbd_device *dev = uaa->uaa_device;
    227 	char *devinfop;
    228 	struct uchcom_endpoints endpoints;
    229 	struct ucom_attach_args ucaa;
    230 
    231 	aprint_naive("\n");
    232 	aprint_normal("\n");
    233 
    234 	devinfop = usbd_devinfo_alloc(dev, 0);
    235 	aprint_normal_dev(self, "%s\n", devinfop);
    236 	usbd_devinfo_free(devinfop);
    237 
    238 	sc->sc_dev = self;
    239 	sc->sc_udev = dev;
    240 	sc->sc_dying = false;
    241 	sc->sc_dtr = sc->sc_rts = -1;
    242 	sc->sc_lsr = sc->sc_msr = 0;
    243 
    244 	DPRINTF(("\n\nuchcom attach: sc=%p\n", sc));
    245 
    246 	if (set_config(sc))
    247 		goto failed;
    248 
    249 	if (find_ifaces(sc, &sc->sc_iface))
    250 		goto failed;
    251 
    252 	if (find_endpoints(sc, &endpoints))
    253 		goto failed;
    254 
    255 	sc->sc_intr_endpoint = endpoints.ep_intr;
    256 	sc->sc_intr_size = endpoints.ep_intr_size;
    257 
    258 	/* setup ucom layer */
    259 	ucaa.ucaa_portno = UCOM_UNK_PORTNO;
    260 	ucaa.ucaa_bulkin = endpoints.ep_bulkin;
    261 	ucaa.ucaa_bulkout = endpoints.ep_bulkout;
    262 	ucaa.ucaa_ibufsize = UCHCOMIBUFSIZE;
    263 	ucaa.ucaa_obufsize = UCHCOMOBUFSIZE;
    264 	ucaa.ucaa_ibufsizepad = UCHCOMIBUFSIZE;
    265 	ucaa.ucaa_opkthdrlen = 0;
    266 	ucaa.ucaa_device = dev;
    267 	ucaa.ucaa_iface = sc->sc_iface;
    268 	ucaa.ucaa_methods = &uchcom_methods;
    269 	ucaa.ucaa_arg = sc;
    270 	ucaa.ucaa_info = NULL;
    271 
    272 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev, sc->sc_dev);
    273 
    274 	sc->sc_subdev = config_found(self, &ucaa, ucomprint,
    275 	    CFARGS(.submatch = ucomsubmatch));
    276 
    277 	return;
    278 
    279 failed:
    280 	sc->sc_dying = true;
    281 	return;
    282 }
    283 
    284 static void
    285 uchcom_childdet(device_t self, device_t child)
    286 {
    287 	struct uchcom_softc *sc = device_private(self);
    288 
    289 	KASSERT(sc->sc_subdev == child);
    290 	sc->sc_subdev = NULL;
    291 }
    292 
    293 static int
    294 uchcom_detach(device_t self, int flags)
    295 {
    296 	struct uchcom_softc *sc = device_private(self);
    297 	int rv = 0;
    298 
    299 	DPRINTF(("uchcom_detach: sc=%p flags=%d\n", sc, flags));
    300 
    301 	close_intr_pipe(sc);
    302 
    303 	sc->sc_dying = true;
    304 
    305 	if (sc->sc_subdev != NULL) {
    306 		rv = config_detach(sc->sc_subdev, flags);
    307 		sc->sc_subdev = NULL;
    308 	}
    309 
    310 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev, sc->sc_dev);
    311 
    312 	return rv;
    313 }
    314 
    315 static int
    316 set_config(struct uchcom_softc *sc)
    317 {
    318 	usbd_status err;
    319 
    320 	err = usbd_set_config_index(sc->sc_udev, UCHCOM_CONFIG_INDEX, 1);
    321 	if (err) {
    322 		aprint_error_dev(sc->sc_dev,
    323 		    "failed to set configuration: %s\n", usbd_errstr(err));
    324 		return -1;
    325 	}
    326 
    327 	return 0;
    328 }
    329 
    330 static int
    331 find_ifaces(struct uchcom_softc *sc, struct usbd_interface **riface)
    332 {
    333 	usbd_status err;
    334 
    335 	err = usbd_device2interface_handle(sc->sc_udev, UCHCOM_IFACE_INDEX,
    336 					   riface);
    337 	if (err) {
    338 		aprint_error("\n%s: failed to get interface: %s\n",
    339 			device_xname(sc->sc_dev), usbd_errstr(err));
    340 		return -1;
    341 	}
    342 
    343 	return 0;
    344 }
    345 
    346 static int
    347 find_endpoints(struct uchcom_softc *sc, struct uchcom_endpoints *endpoints)
    348 {
    349 	int i, bin=-1, bout=-1, intr=-1, isize=0;
    350 	usb_interface_descriptor_t *id;
    351 	usb_endpoint_descriptor_t *ed;
    352 
    353 	id = usbd_get_interface_descriptor(sc->sc_iface);
    354 
    355 	for (i = 0; i < id->bNumEndpoints; i++) {
    356 		ed = usbd_interface2endpoint_descriptor(sc->sc_iface, i);
    357 		if (ed == NULL) {
    358 			aprint_error_dev(sc->sc_dev,
    359 			    "no endpoint descriptor for %d\n", i);
    360 			return -1;
    361 		}
    362 
    363 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
    364 		    UE_GET_XFERTYPE(ed->bmAttributes) == UE_INTERRUPT) {
    365 			intr = ed->bEndpointAddress;
    366 			isize = UGETW(ed->wMaxPacketSize);
    367 		} else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
    368 			   UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
    369 			bin = ed->bEndpointAddress;
    370 		} else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT &&
    371 			   UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
    372 			bout = ed->bEndpointAddress;
    373 		}
    374 	}
    375 
    376 	if (intr == -1 || bin == -1 || bout == -1) {
    377 		if (intr == -1) {
    378 			aprint_error_dev(sc->sc_dev,
    379 			    "no interrupt end point\n");
    380 		}
    381 		if (bin == -1) {
    382 			aprint_error_dev(sc->sc_dev,
    383 			    "no data bulk in end point\n");
    384 		}
    385 		if (bout == -1) {
    386 			aprint_error_dev(sc->sc_dev,
    387 			    "no data bulk out end point\n");
    388 		}
    389 		return -1;
    390 	}
    391 	if (isize < UCHCOM_INTR_LEAST) {
    392 		aprint_error_dev(sc->sc_dev, "intr pipe is too short\n");
    393 		return -1;
    394 	}
    395 
    396 	DPRINTF(("%s: bulkin=%d, bulkout=%d, intr=%d, isize=%d\n",
    397 		 device_xname(sc->sc_dev), bin, bout, intr, isize));
    398 
    399 	endpoints->ep_intr = intr;
    400 	endpoints->ep_intr_size = isize;
    401 	endpoints->ep_bulkin = bin;
    402 	endpoints->ep_bulkout = bout;
    403 
    404 	return 0;
    405 }
    406 
    407 
    408 /* ----------------------------------------------------------------------
    409  * low level i/o
    410  */
    411 
    412 static __inline usbd_status
    413 generic_control_out(struct uchcom_softc *sc, uint8_t reqno,
    414 		    uint16_t value, uint16_t index)
    415 {
    416 	usb_device_request_t req;
    417 
    418 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
    419 	req.bRequest = reqno;
    420 	USETW(req.wValue, value);
    421 	USETW(req.wIndex, index);
    422 	USETW(req.wLength, 0);
    423 
    424 	return usbd_do_request(sc->sc_udev, &req, 0);
    425 }
    426 
    427 static __inline usbd_status
    428 generic_control_in(struct uchcom_softc *sc, uint8_t reqno,
    429 		   uint16_t value, uint16_t index, void *buf, int buflen,
    430 		   int *actlen)
    431 {
    432 	usb_device_request_t req;
    433 
    434 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
    435 	req.bRequest = reqno;
    436 	USETW(req.wValue, value);
    437 	USETW(req.wIndex, index);
    438 	USETW(req.wLength, (uint16_t)buflen);
    439 
    440 	return usbd_do_request_flags(sc->sc_udev, &req, buf,
    441 				     USBD_SHORT_XFER_OK, actlen,
    442 				     USBD_DEFAULT_TIMEOUT);
    443 }
    444 
    445 static __inline usbd_status
    446 write_reg(struct uchcom_softc *sc,
    447 	  uint8_t reg1, uint8_t val1, uint8_t reg2, uint8_t val2)
    448 {
    449 	DPRINTF(("%s: write reg 0x%02X<-0x%02X, 0x%02X<-0x%02X\n",
    450 		 device_xname(sc->sc_dev),
    451 		 (unsigned)reg1, (unsigned)val1,
    452 		 (unsigned)reg2, (unsigned)val2));
    453 	return generic_control_out(
    454 		sc, UCHCOM_REQ_WRITE_REG,
    455 		reg1|((uint16_t)reg2<<8), val1|((uint16_t)val2<<8));
    456 }
    457 
    458 static __inline usbd_status
    459 read_reg(struct uchcom_softc *sc,
    460 	 uint8_t reg1, uint8_t *rval1, uint8_t reg2, uint8_t *rval2)
    461 {
    462 	uint8_t buf[UCHCOM_INPUT_BUF_SIZE];
    463 	usbd_status err;
    464 	int actin;
    465 
    466 	err = generic_control_in(
    467 		sc, UCHCOM_REQ_READ_REG,
    468 		reg1|((uint16_t)reg2<<8), 0, buf, sizeof(buf), &actin);
    469 	if (err)
    470 		return err;
    471 
    472 	DPRINTF(("%s: read reg 0x%02X->0x%02X, 0x%02X->0x%02X\n",
    473 		 device_xname(sc->sc_dev),
    474 		 (unsigned)reg1, (unsigned)buf[0],
    475 		 (unsigned)reg2, (unsigned)buf[1]));
    476 
    477 	if (rval1) *rval1 = buf[0];
    478 	if (rval2) *rval2 = buf[1];
    479 
    480 	return USBD_NORMAL_COMPLETION;
    481 }
    482 
    483 static __inline usbd_status
    484 get_version(struct uchcom_softc *sc, uint8_t *rver)
    485 {
    486 	uint8_t buf[UCHCOM_INPUT_BUF_SIZE];
    487 	usbd_status err;
    488 	int actin;
    489 
    490 	err = generic_control_in(
    491 		sc, UCHCOM_REQ_GET_VERSION, 0, 0, buf, sizeof(buf), &actin);
    492 	if (err)
    493 		return err;
    494 
    495 	if (rver) *rver = buf[0];
    496 
    497 	return USBD_NORMAL_COMPLETION;
    498 }
    499 
    500 static __inline usbd_status
    501 get_status(struct uchcom_softc *sc, uint8_t *rval)
    502 {
    503 	return read_reg(sc, UCHCOM_REG_STAT1, rval, UCHCOM_REG_STAT2, NULL);
    504 }
    505 
    506 static __inline usbd_status
    507 set_dtrrts_10(struct uchcom_softc *sc, uint8_t val)
    508 {
    509 	return write_reg(sc, UCHCOM_REG_STAT1, val, UCHCOM_REG_STAT1, val);
    510 }
    511 
    512 static __inline usbd_status
    513 set_dtrrts_20(struct uchcom_softc *sc, uint8_t val)
    514 {
    515 	return generic_control_out(sc, UCHCOM_REQ_SET_DTRRTS, val, 0);
    516 }
    517 
    518 
    519 /* ----------------------------------------------------------------------
    520  * middle layer
    521  */
    522 
    523 static int
    524 update_version(struct uchcom_softc *sc)
    525 {
    526 	usbd_status err;
    527 
    528 	err = get_version(sc, &sc->sc_version);
    529 	if (err) {
    530 		device_printf(sc->sc_dev, "cannot get version: %s\n",
    531 		    usbd_errstr(err));
    532 		return EIO;
    533 	}
    534 	DPRINTF(("%s: update_version %d\n", device_xname(sc->sc_dev), sc->sc_version));
    535 
    536 	return 0;
    537 }
    538 
    539 static void
    540 convert_status(struct uchcom_softc *sc, uint8_t cur)
    541 {
    542 	sc->sc_dtr = !(cur & UCHCOM_DTR_MASK);
    543 	sc->sc_rts = !(cur & UCHCOM_RTS_MASK);
    544 
    545 	cur = ~cur & 0x0F;
    546 	sc->sc_msr = (cur << 4) | ((sc->sc_msr >> 4) ^ cur);
    547 }
    548 
    549 static int
    550 update_status(struct uchcom_softc *sc)
    551 {
    552 	usbd_status err;
    553 	uint8_t cur;
    554 
    555 	err = get_status(sc, &cur);
    556 	if (err) {
    557 		device_printf(sc->sc_dev,
    558 		    "cannot update status: %s\n", usbd_errstr(err));
    559 		return EIO;
    560 	}
    561 	convert_status(sc, cur);
    562 
    563 	return 0;
    564 }
    565 
    566 
    567 static int
    568 set_dtrrts(struct uchcom_softc *sc, int dtr, int rts)
    569 {
    570 	usbd_status err;
    571 	uint8_t val = 0;
    572 
    573 	if (dtr) val |= UCHCOM_DTR_MASK;
    574 	if (rts) val |= UCHCOM_RTS_MASK;
    575 
    576 	if (sc->sc_version < UCHCOM_VER_20)
    577 		err = set_dtrrts_10(sc, ~val);
    578 	else
    579 		err = set_dtrrts_20(sc, ~val);
    580 
    581 	if (err) {
    582 		device_printf(sc->sc_dev, "cannot set DTR/RTS: %s\n",
    583 		    usbd_errstr(err));
    584 		return EIO;
    585 	}
    586 
    587 	return 0;
    588 }
    589 
    590 static int
    591 set_break(struct uchcom_softc *sc, int onoff)
    592 {
    593 	usbd_status err;
    594 	uint8_t brk, lcr;
    595 
    596 	err = read_reg(sc, UCHCOM_REG_BREAK, &brk, UCHCOM_REG_LCR, &lcr);
    597 	if (err)
    598 		return EIO;
    599 	if (onoff) {
    600 		/* on - clear bits */
    601 		brk &= ~UCHCOM_BREAK_MASK;
    602 		lcr &= ~UCHCOM_LCR_TXE;
    603 	} else {
    604 		/* off - set bits */
    605 		brk |= UCHCOM_BREAK_MASK;
    606 		lcr |= UCHCOM_LCR_TXE;
    607 	}
    608 	err = write_reg(sc, UCHCOM_REG_BREAK, brk, UCHCOM_REG_LCR, lcr);
    609 	if (err)
    610 		return EIO;
    611 
    612 	return 0;
    613 }
    614 
    615 static int
    616 calc_divider_settings(struct uchcom_divider *dp, uint32_t rate)
    617 {
    618 /*
    619  * combined with rates4x[] defined above, this routine generates,
    620  *   1200: prescale = 1/0x1, divisor = 178/0xb2
    621  *   2400: prescale = 1/0x1, divisor = 217/0xd9
    622  *   4800: prescale = 2/0x2, divisor = 100/0x64
    623  *   9600: prescale = 2/0x2, divisor = 178/0xb2
    624  *  19200: prescale = 2/0x2, divisor = 217/0xd9
    625  *  38400: prescale = 3/0x3, divisor = 100/0x64
    626  *  57600: prescale = 2/0x2, divisor = 243/0xf3
    627  * 115200: prescale = 3/0x3, divisor = 204/0xcc
    628  * 921600: prescale = 7/0x7, divisor = 243/0xf3
    629  * 500000: prescale = 3/0x3, divisor = 244/0xf4
    630  * 1000000: prescale = 3/0x3, divisor = 250/0xfa
    631  * 1500000: prescale = 3/0x3, divisor = 252/0xfc
    632  * 2000000: prescale = 3/0x3, divisor = 253/0xfd
    633  * 2500000: unsupported
    634  * 3000000: prescale = 3/0x3, divisor = 254/0xfe
    635  */
    636 	size_t i;
    637 	uint32_t best, div, pre;
    638 	const uint32_t rate4x = rate * 4U;
    639 
    640 	if (rate == 0 || rate > 3000000)
    641 		return -1;
    642 
    643 	pre = __arraycount(rates4x);
    644 	best = UINT32_MAX;
    645 
    646 	for (i = 0; i < __arraycount(rates4x); i++) {
    647 		uint32_t score, try;
    648 		try = rates4x[i] * 2 / rate4x;
    649 		try = (try / 2) + (try & 1);
    650 		if (try < 2)
    651 			continue;
    652 		if (try > 255)
    653 			try = 255;
    654 		score = abs((int)rate4x - rates4x[i] / try);
    655 		if (score < best) {
    656 			best = score;
    657 			pre = i;
    658 			div = try;
    659 		}
    660 	}
    661 
    662 	if (pre >= __arraycount(rates4x))
    663 		return -1;
    664 	if ((rates4x[pre] / div / 4) < (rate * 99 / 100))
    665 		return -1;
    666 	if ((rates4x[pre] / div / 4) > (rate * 101 / 100))
    667 		return -1;
    668 
    669 	dp->dv_prescaler = pre;
    670 	dp->dv_div = 256 - div;
    671 
    672 	return 0;
    673 }
    674 
    675 static int
    676 set_dte_rate(struct uchcom_softc *sc, uint32_t rate)
    677 {
    678 	usbd_status err;
    679 	struct uchcom_divider dv;
    680 
    681 	if (calc_divider_settings(&dv, rate))
    682 		return EINVAL;
    683 
    684 	if ((err = write_reg(sc,
    685 			     UCHCOM_REG_BPS_PRE,
    686 			     dv.dv_prescaler | UCHCOM_BPS_PRE_IMM,
    687 			     UCHCOM_REG_BPS_DIV, dv.dv_div))) {
    688 		device_printf(sc->sc_dev, "cannot set DTE rate: %s\n",
    689 		    usbd_errstr(err));
    690 		return EIO;
    691 	}
    692 
    693 	return 0;
    694 }
    695 
    696 static int
    697 set_line_control(struct uchcom_softc *sc, tcflag_t cflag)
    698 {
    699 	usbd_status err;
    700 	uint8_t lcr = 0, lcr2 = 0;
    701 
    702 	err = read_reg(sc, UCHCOM_REG_LCR, &lcr, UCHCOM_REG_LCR2, &lcr2);
    703 	if (err) {
    704 		device_printf(sc->sc_dev, "cannot get LCR: %s\n",
    705 		    usbd_errstr(err));
    706 		return EIO;
    707 	}
    708 
    709 	lcr = UCHCOM_LCR_RXE | UCHCOM_LCR_TXE;
    710 
    711 	switch (ISSET(cflag, CSIZE)) {
    712 	case CS5:
    713 		lcr |= UCHCOM_LCR_CS5;
    714 		break;
    715 	case CS6:
    716 		lcr |= UCHCOM_LCR_CS6;
    717 		break;
    718 	case CS7:
    719 		lcr |= UCHCOM_LCR_CS7;
    720 		break;
    721 	case CS8:
    722 		lcr |= UCHCOM_LCR_CS8;
    723 		break;
    724 	}
    725 
    726 	if (ISSET(cflag, PARENB)) {
    727 		lcr |= UCHCOM_LCR_PARENB;
    728 		if (!ISSET(cflag, PARODD))
    729 			lcr |= UCHCOM_LCR_PAREVEN;
    730 	}
    731 
    732 	if (ISSET(cflag, CSTOPB)) {
    733 		lcr |= UCHCOM_LCR_STOPB;
    734 	}
    735 
    736 	err = write_reg(sc, UCHCOM_REG_LCR, lcr, UCHCOM_REG_LCR2, lcr2);
    737 	if (err) {
    738 		device_printf(sc->sc_dev, "cannot set LCR: %s\n",
    739 		    usbd_errstr(err));
    740 		return EIO;
    741 	}
    742 
    743 	return 0;
    744 }
    745 
    746 static int
    747 clear_chip(struct uchcom_softc *sc)
    748 {
    749 	usbd_status err;
    750 
    751 	DPRINTF(("%s: clear\n", device_xname(sc->sc_dev)));
    752 	err = generic_control_out(sc, UCHCOM_REQ_RESET, 0, 0);
    753 	if (err) {
    754 		device_printf(sc->sc_dev, "cannot clear: %s\n",
    755 		    usbd_errstr(err));
    756 		return EIO;
    757 	}
    758 	/*
    759 	 * this REQ_RESET call ends up with
    760 	 * LCR=0xc0 (8N1)
    761 	 * PRE=0x02, DIV=0xd9 (19200)
    762 	 */
    763 	return 0;
    764 }
    765 
    766 static int
    767 setup_comm(struct uchcom_softc *sc)
    768 {
    769 	int ret;
    770 
    771 	ret = update_version(sc);
    772 	if (ret)
    773 		return ret;
    774 
    775 	ret = clear_chip(sc);
    776 	if (ret)
    777 		return ret;
    778 
    779 	ret = set_dte_rate(sc, TTYDEF_SPEED);
    780 	if (ret)
    781 		return ret;
    782 
    783 	ret = set_line_control(sc, CS8);
    784 	if (ret)
    785 		return ret;
    786 
    787 	ret = update_status(sc);
    788 	if (ret)
    789 		return ret;
    790 
    791 	sc->sc_dtr = sc->sc_rts = 1;
    792 	ret = set_dtrrts(sc, sc->sc_dtr, sc->sc_rts);
    793 	if (ret)
    794 		return ret;
    795 
    796 	return 0;
    797 }
    798 
    799 static int
    800 setup_intr_pipe(struct uchcom_softc *sc)
    801 {
    802 	usbd_status err;
    803 
    804 	if (sc->sc_intr_endpoint != -1 && sc->sc_intr_pipe == NULL) {
    805 		sc->sc_intr_buf = kmem_alloc(sc->sc_intr_size, KM_SLEEP);
    806 		err = usbd_open_pipe_intr(sc->sc_iface,
    807 					  sc->sc_intr_endpoint,
    808 					  USBD_SHORT_XFER_OK,
    809 					  &sc->sc_intr_pipe, sc,
    810 					  sc->sc_intr_buf,
    811 					  sc->sc_intr_size,
    812 					  uchcom_intr, USBD_DEFAULT_INTERVAL);
    813 		if (err) {
    814 			device_printf(sc->sc_dev,
    815 			    "cannot open interrupt pipe: %s\n",
    816 			    usbd_errstr(err));
    817 			return EIO;
    818 		}
    819 	}
    820 	return 0;
    821 }
    822 
    823 static void
    824 close_intr_pipe(struct uchcom_softc *sc)
    825 {
    826 
    827 	if (sc->sc_intr_pipe != NULL) {
    828 		usbd_abort_pipe(sc->sc_intr_pipe);
    829 		usbd_close_pipe(sc->sc_intr_pipe);
    830 		sc->sc_intr_pipe = NULL;
    831 	}
    832 	if (sc->sc_intr_buf != NULL) {
    833 		kmem_free(sc->sc_intr_buf, sc->sc_intr_size);
    834 		sc->sc_intr_buf = NULL;
    835 	}
    836 }
    837 
    838 
    839 /* ----------------------------------------------------------------------
    840  * methods for ucom
    841  */
    842 static void
    843 uchcom_get_status(void *arg, int portno, u_char *rlsr, u_char *rmsr)
    844 {
    845 	struct uchcom_softc *sc = arg;
    846 
    847 	if (sc->sc_dying)
    848 		return;
    849 
    850 	*rlsr = sc->sc_lsr;
    851 	*rmsr = sc->sc_msr;
    852 }
    853 
    854 static void
    855 uchcom_set(void *arg, int portno, int reg, int onoff)
    856 {
    857 	struct uchcom_softc *sc = arg;
    858 
    859 	if (sc->sc_dying)
    860 		return;
    861 
    862 	switch (reg) {
    863 	case UCOM_SET_DTR:
    864 		sc->sc_dtr = !!onoff;
    865 		set_dtrrts(sc, sc->sc_dtr, sc->sc_rts);
    866 		break;
    867 	case UCOM_SET_RTS:
    868 		sc->sc_rts = !!onoff;
    869 		set_dtrrts(sc, sc->sc_dtr, sc->sc_rts);
    870 		break;
    871 	case UCOM_SET_BREAK:
    872 		set_break(sc, onoff);
    873 		break;
    874 	}
    875 }
    876 
    877 static int
    878 uchcom_param(void *arg, int portno, struct termios *t)
    879 {
    880 	struct uchcom_softc *sc = arg;
    881 	int ret;
    882 
    883 	if (sc->sc_dying)
    884 		return EIO;
    885 
    886 	ret = set_line_control(sc, t->c_cflag);
    887 	if (ret)
    888 		return ret;
    889 
    890 	ret = set_dte_rate(sc, t->c_ospeed);
    891 	if (ret)
    892 		return ret;
    893 
    894 	return 0;
    895 }
    896 
    897 static int
    898 uchcom_open(void *arg, int portno)
    899 {
    900 	int ret;
    901 	struct uchcom_softc *sc = arg;
    902 
    903 	if (sc->sc_dying)
    904 		return EIO;
    905 
    906 	ret = setup_intr_pipe(sc);
    907 	if (ret)
    908 		return ret;
    909 
    910 	ret = setup_comm(sc);
    911 	if (ret)
    912 		return ret;
    913 
    914 	return 0;
    915 }
    916 
    917 static void
    918 uchcom_close(void *arg, int portno)
    919 {
    920 	struct uchcom_softc *sc = arg;
    921 
    922 	if (sc->sc_dying)
    923 		return;
    924 
    925 	close_intr_pipe(sc);
    926 }
    927 
    928 
    929 /* ----------------------------------------------------------------------
    930  * callback when the modem status is changed.
    931  */
    932 static void
    933 uchcom_intr(struct usbd_xfer *xfer, void * priv,
    934 	    usbd_status status)
    935 {
    936 	struct uchcom_softc *sc = priv;
    937 	u_char *buf = sc->sc_intr_buf;
    938 
    939 	if (sc->sc_dying)
    940 		return;
    941 
    942 	if (status != USBD_NORMAL_COMPLETION) {
    943 		if (status == USBD_NOT_STARTED || status == USBD_CANCELLED)
    944 			return;
    945 
    946 		DPRINTF(("%s: abnormal status: %s\n",
    947 			 device_xname(sc->sc_dev), usbd_errstr(status)));
    948 		usbd_clear_endpoint_stall_async(sc->sc_intr_pipe);
    949 		return;
    950 	}
    951 	DPRINTF(("%s: intr: 0x%02X 0x%02X 0x%02X 0x%02X "
    952 		 "0x%02X 0x%02X 0x%02X 0x%02X\n",
    953 		 device_xname(sc->sc_dev),
    954 		 (unsigned)buf[0], (unsigned)buf[1],
    955 		 (unsigned)buf[2], (unsigned)buf[3],
    956 		 (unsigned)buf[4], (unsigned)buf[5],
    957 		 (unsigned)buf[6], (unsigned)buf[7]));
    958 
    959 	convert_status(sc, buf[UCHCOM_INTR_STAT1]);
    960 	ucom_status_change(device_private(sc->sc_subdev));
    961 }
    962