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