xref: /netbsd-src/sys/dev/usb/uchcom.c (revision 82d56013d7b633d116a93943de88e08335357a7c)
1 /*	$NetBSD: uchcom.c,v 1.37 2021/04/24 23:36:59 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@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.37 2021/04/24 23:36:59 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_EOL);
279 
280 	return;
281 
282 failed:
283 	sc->sc_dying = true;
284 	return;
285 }
286 
287 static void
288 uchcom_childdet(device_t self, device_t child)
289 {
290 	struct uchcom_softc *sc = device_private(self);
291 
292 	KASSERT(sc->sc_subdev == child);
293 	sc->sc_subdev = NULL;
294 }
295 
296 static int
297 uchcom_detach(device_t self, int flags)
298 {
299 	struct uchcom_softc *sc = device_private(self);
300 	int rv = 0;
301 
302 	DPRINTF(("uchcom_detach: sc=%p flags=%d\n", sc, flags));
303 
304 	close_intr_pipe(sc);
305 
306 	sc->sc_dying = true;
307 
308 	if (sc->sc_subdev != NULL) {
309 		rv = config_detach(sc->sc_subdev, flags);
310 		sc->sc_subdev = NULL;
311 	}
312 
313 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev, sc->sc_dev);
314 
315 	return rv;
316 }
317 
318 static int
319 set_config(struct uchcom_softc *sc)
320 {
321 	usbd_status err;
322 
323 	err = usbd_set_config_index(sc->sc_udev, UCHCOM_CONFIG_INDEX, 1);
324 	if (err) {
325 		aprint_error_dev(sc->sc_dev,
326 		    "failed to set configuration: %s\n", usbd_errstr(err));
327 		return -1;
328 	}
329 
330 	return 0;
331 }
332 
333 static int
334 find_ifaces(struct uchcom_softc *sc, struct usbd_interface **riface)
335 {
336 	usbd_status err;
337 
338 	err = usbd_device2interface_handle(sc->sc_udev, UCHCOM_IFACE_INDEX,
339 					   riface);
340 	if (err) {
341 		aprint_error("\n%s: failed to get interface: %s\n",
342 			device_xname(sc->sc_dev), usbd_errstr(err));
343 		return -1;
344 	}
345 
346 	return 0;
347 }
348 
349 static int
350 find_endpoints(struct uchcom_softc *sc, struct uchcom_endpoints *endpoints)
351 {
352 	int i, bin=-1, bout=-1, intr=-1, isize=0;
353 	usb_interface_descriptor_t *id;
354 	usb_endpoint_descriptor_t *ed;
355 
356 	id = usbd_get_interface_descriptor(sc->sc_iface);
357 
358 	for (i = 0; i < id->bNumEndpoints; i++) {
359 		ed = usbd_interface2endpoint_descriptor(sc->sc_iface, i);
360 		if (ed == NULL) {
361 			aprint_error_dev(sc->sc_dev,
362 			    "no endpoint descriptor for %d\n", i);
363 			return -1;
364 		}
365 
366 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
367 		    UE_GET_XFERTYPE(ed->bmAttributes) == UE_INTERRUPT) {
368 			intr = ed->bEndpointAddress;
369 			isize = UGETW(ed->wMaxPacketSize);
370 		} else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
371 			   UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
372 			bin = ed->bEndpointAddress;
373 		} else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT &&
374 			   UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
375 			bout = ed->bEndpointAddress;
376 		}
377 	}
378 
379 	if (intr == -1 || bin == -1 || bout == -1) {
380 		if (intr == -1) {
381 			aprint_error_dev(sc->sc_dev,
382 			    "no interrupt end point\n");
383 		}
384 		if (bin == -1) {
385 			aprint_error_dev(sc->sc_dev,
386 			    "no data bulk in end point\n");
387 		}
388 		if (bout == -1) {
389 			aprint_error_dev(sc->sc_dev,
390 			    "no data bulk out end point\n");
391 		}
392 		return -1;
393 	}
394 	if (isize < UCHCOM_INTR_LEAST) {
395 		aprint_error_dev(sc->sc_dev, "intr pipe is too short\n");
396 		return -1;
397 	}
398 
399 	DPRINTF(("%s: bulkin=%d, bulkout=%d, intr=%d, isize=%d\n",
400 		 device_xname(sc->sc_dev), bin, bout, intr, isize));
401 
402 	endpoints->ep_intr = intr;
403 	endpoints->ep_intr_size = isize;
404 	endpoints->ep_bulkin = bin;
405 	endpoints->ep_bulkout = bout;
406 
407 	return 0;
408 }
409 
410 
411 /* ----------------------------------------------------------------------
412  * low level i/o
413  */
414 
415 static __inline usbd_status
416 generic_control_out(struct uchcom_softc *sc, uint8_t reqno,
417 		    uint16_t value, uint16_t index)
418 {
419 	usb_device_request_t req;
420 
421 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
422 	req.bRequest = reqno;
423 	USETW(req.wValue, value);
424 	USETW(req.wIndex, index);
425 	USETW(req.wLength, 0);
426 
427 	return usbd_do_request(sc->sc_udev, &req, 0);
428 }
429 
430 static __inline usbd_status
431 generic_control_in(struct uchcom_softc *sc, uint8_t reqno,
432 		   uint16_t value, uint16_t index, void *buf, int buflen,
433 		   int *actlen)
434 {
435 	usb_device_request_t req;
436 
437 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
438 	req.bRequest = reqno;
439 	USETW(req.wValue, value);
440 	USETW(req.wIndex, index);
441 	USETW(req.wLength, (uint16_t)buflen);
442 
443 	return usbd_do_request_flags(sc->sc_udev, &req, buf,
444 				     USBD_SHORT_XFER_OK, actlen,
445 				     USBD_DEFAULT_TIMEOUT);
446 }
447 
448 static __inline usbd_status
449 write_reg(struct uchcom_softc *sc,
450 	  uint8_t reg1, uint8_t val1, uint8_t reg2, uint8_t val2)
451 {
452 	DPRINTF(("%s: write reg 0x%02X<-0x%02X, 0x%02X<-0x%02X\n",
453 		 device_xname(sc->sc_dev),
454 		 (unsigned)reg1, (unsigned)val1,
455 		 (unsigned)reg2, (unsigned)val2));
456 	return generic_control_out(
457 		sc, UCHCOM_REQ_WRITE_REG,
458 		reg1|((uint16_t)reg2<<8), val1|((uint16_t)val2<<8));
459 }
460 
461 static __inline usbd_status
462 read_reg(struct uchcom_softc *sc,
463 	 uint8_t reg1, uint8_t *rval1, uint8_t reg2, uint8_t *rval2)
464 {
465 	uint8_t buf[UCHCOM_INPUT_BUF_SIZE];
466 	usbd_status err;
467 	int actin;
468 
469 	err = generic_control_in(
470 		sc, UCHCOM_REQ_READ_REG,
471 		reg1|((uint16_t)reg2<<8), 0, buf, sizeof(buf), &actin);
472 	if (err)
473 		return err;
474 
475 	DPRINTF(("%s: read reg 0x%02X->0x%02X, 0x%02X->0x%02X\n",
476 		 device_xname(sc->sc_dev),
477 		 (unsigned)reg1, (unsigned)buf[0],
478 		 (unsigned)reg2, (unsigned)buf[1]));
479 
480 	if (rval1) *rval1 = buf[0];
481 	if (rval2) *rval2 = buf[1];
482 
483 	return USBD_NORMAL_COMPLETION;
484 }
485 
486 static __inline usbd_status
487 get_version(struct uchcom_softc *sc, uint8_t *rver)
488 {
489 	uint8_t buf[UCHCOM_INPUT_BUF_SIZE];
490 	usbd_status err;
491 	int actin;
492 
493 	err = generic_control_in(
494 		sc, UCHCOM_REQ_GET_VERSION, 0, 0, buf, sizeof(buf), &actin);
495 	if (err)
496 		return err;
497 
498 	if (rver) *rver = buf[0];
499 
500 	return USBD_NORMAL_COMPLETION;
501 }
502 
503 static __inline usbd_status
504 get_status(struct uchcom_softc *sc, uint8_t *rval)
505 {
506 	return read_reg(sc, UCHCOM_REG_STAT1, rval, UCHCOM_REG_STAT2, NULL);
507 }
508 
509 static __inline usbd_status
510 set_dtrrts_10(struct uchcom_softc *sc, uint8_t val)
511 {
512 	return write_reg(sc, UCHCOM_REG_STAT1, val, UCHCOM_REG_STAT1, val);
513 }
514 
515 static __inline usbd_status
516 set_dtrrts_20(struct uchcom_softc *sc, uint8_t val)
517 {
518 	return generic_control_out(sc, UCHCOM_REQ_SET_DTRRTS, val, 0);
519 }
520 
521 
522 /* ----------------------------------------------------------------------
523  * middle layer
524  */
525 
526 static int
527 update_version(struct uchcom_softc *sc)
528 {
529 	usbd_status err;
530 
531 	err = get_version(sc, &sc->sc_version);
532 	if (err) {
533 		device_printf(sc->sc_dev, "cannot get version: %s\n",
534 		    usbd_errstr(err));
535 		return EIO;
536 	}
537 	DPRINTF(("%s: update_version %d\n", device_xname(sc->sc_dev), sc->sc_version));
538 
539 	return 0;
540 }
541 
542 static void
543 convert_status(struct uchcom_softc *sc, uint8_t cur)
544 {
545 	sc->sc_dtr = !(cur & UCHCOM_DTR_MASK);
546 	sc->sc_rts = !(cur & UCHCOM_RTS_MASK);
547 
548 	cur = ~cur & 0x0F;
549 	sc->sc_msr = (cur << 4) | ((sc->sc_msr >> 4) ^ cur);
550 }
551 
552 static int
553 update_status(struct uchcom_softc *sc)
554 {
555 	usbd_status err;
556 	uint8_t cur;
557 
558 	err = get_status(sc, &cur);
559 	if (err) {
560 		device_printf(sc->sc_dev,
561 		    "cannot update status: %s\n", usbd_errstr(err));
562 		return EIO;
563 	}
564 	convert_status(sc, cur);
565 
566 	return 0;
567 }
568 
569 
570 static int
571 set_dtrrts(struct uchcom_softc *sc, int dtr, int rts)
572 {
573 	usbd_status err;
574 	uint8_t val = 0;
575 
576 	if (dtr) val |= UCHCOM_DTR_MASK;
577 	if (rts) val |= UCHCOM_RTS_MASK;
578 
579 	if (sc->sc_version < UCHCOM_VER_20)
580 		err = set_dtrrts_10(sc, ~val);
581 	else
582 		err = set_dtrrts_20(sc, ~val);
583 
584 	if (err) {
585 		device_printf(sc->sc_dev, "cannot set DTR/RTS: %s\n",
586 		    usbd_errstr(err));
587 		return EIO;
588 	}
589 
590 	return 0;
591 }
592 
593 static int
594 set_break(struct uchcom_softc *sc, int onoff)
595 {
596 	usbd_status err;
597 	uint8_t brk, lcr;
598 
599 	err = read_reg(sc, UCHCOM_REG_BREAK, &brk, UCHCOM_REG_LCR, &lcr);
600 	if (err)
601 		return EIO;
602 	if (onoff) {
603 		/* on - clear bits */
604 		brk &= ~UCHCOM_BREAK_MASK;
605 		lcr &= ~UCHCOM_LCR_TXE;
606 	} else {
607 		/* off - set bits */
608 		brk |= UCHCOM_BREAK_MASK;
609 		lcr |= UCHCOM_LCR_TXE;
610 	}
611 	err = write_reg(sc, UCHCOM_REG_BREAK, brk, UCHCOM_REG_LCR, lcr);
612 	if (err)
613 		return EIO;
614 
615 	return 0;
616 }
617 
618 static int
619 calc_divider_settings(struct uchcom_divider *dp, uint32_t rate)
620 {
621 	size_t i;
622 	uint32_t best, div, pre;
623 	const uint32_t rate4x = rate * 4U;
624 
625 	if (rate == 0 || rate > 3000000)
626 		return -1;
627 
628 	pre = __arraycount(rates4x);
629 	best = UINT32_MAX;
630 
631 	for (i = 0; i < __arraycount(rates4x); i++) {
632 		uint32_t score, try;
633 		try = rates4x[i] * 2 / rate4x;
634 		try = (try / 2) + (try & 1);
635 		if (try < 2)
636 			continue;
637 		if (try > 255)
638 			try = 255;
639 		score = abs((int)rate4x - rates4x[i] / try);
640 		if (score < best) {
641 			best = score;
642 			pre = i;
643 			div = try;
644 		}
645 	}
646 
647 	if (pre >= __arraycount(rates4x))
648 		return -1;
649 	if ((rates4x[pre] / div / 4) < (rate * 99 / 100))
650 		return -1;
651 	if ((rates4x[pre] / div / 4) > (rate * 101 / 100))
652 		return -1;
653 
654 	dp->dv_prescaler = pre;
655 	dp->dv_div = (uint8_t)-div;
656 
657 	return 0;
658 }
659 
660 static int
661 set_dte_rate(struct uchcom_softc *sc, uint32_t rate)
662 {
663 	usbd_status err;
664 	struct uchcom_divider dv;
665 
666 	if (calc_divider_settings(&dv, rate))
667 		return EINVAL;
668 
669 	if ((err = write_reg(sc,
670 			     UCHCOM_REG_BPS_PRE,
671 			     dv.dv_prescaler | UCHCOM_BPS_PRE_IMM,
672 			     UCHCOM_REG_BPS_DIV, dv.dv_div))) {
673 		device_printf(sc->sc_dev, "cannot set DTE rate: %s\n",
674 		    usbd_errstr(err));
675 		return EIO;
676 	}
677 
678 	return 0;
679 }
680 
681 static int
682 set_line_control(struct uchcom_softc *sc, tcflag_t cflag)
683 {
684 	usbd_status err;
685 	uint8_t lcr = 0, lcr2 = 0;
686 
687 	err = read_reg(sc, UCHCOM_REG_LCR, &lcr, UCHCOM_REG_LCR2, &lcr2);
688 	if (err) {
689 		device_printf(sc->sc_dev, "cannot get LCR: %s\n",
690 		    usbd_errstr(err));
691 		return EIO;
692 	}
693 
694 	lcr = UCHCOM_LCR_RXE | UCHCOM_LCR_TXE;
695 
696 	switch (ISSET(cflag, CSIZE)) {
697 	case CS5:
698 		lcr |= UCHCOM_LCR_CS5;
699 		break;
700 	case CS6:
701 		lcr |= UCHCOM_LCR_CS6;
702 		break;
703 	case CS7:
704 		lcr |= UCHCOM_LCR_CS7;
705 		break;
706 	case CS8:
707 		lcr |= UCHCOM_LCR_CS8;
708 		break;
709 	}
710 
711 	if (ISSET(cflag, PARENB)) {
712 		lcr |= UCHCOM_LCR_PARENB;
713 		if (!ISSET(cflag, PARODD))
714 			lcr |= UCHCOM_LCR_PAREVEN;
715 	}
716 
717 	if (ISSET(cflag, CSTOPB)) {
718 		lcr |= UCHCOM_LCR_STOPB;
719 	}
720 
721 	err = write_reg(sc, UCHCOM_REG_LCR, lcr, UCHCOM_REG_LCR2, lcr2);
722 	if (err) {
723 		device_printf(sc->sc_dev, "cannot set LCR: %s\n",
724 		    usbd_errstr(err));
725 		return EIO;
726 	}
727 
728 	return 0;
729 }
730 
731 static int
732 clear_chip(struct uchcom_softc *sc)
733 {
734 	usbd_status err;
735 
736 	DPRINTF(("%s: clear\n", device_xname(sc->sc_dev)));
737 	err = generic_control_out(sc, UCHCOM_REQ_RESET, 0, 0);
738 	if (err) {
739 		device_printf(sc->sc_dev, "cannot clear: %s\n",
740 		    usbd_errstr(err));
741 		return EIO;
742 	}
743 
744 	return 0;
745 }
746 
747 static int
748 reset_chip(struct uchcom_softc *sc)
749 {
750 	usbd_status err;
751 
752 	err = generic_control_out(sc, UCHCOM_REQ_RESET,
753 	    UCHCOM_RESET_VALUE, UCHCOM_RESET_INDEX);
754 	if (err)
755 		goto failed;
756 
757 	return 0;
758 
759 failed:
760 	printf("%s: cannot reset: %s\n",
761 	       device_xname(sc->sc_dev), usbd_errstr(err));
762 	return EIO;
763 }
764 
765 static int
766 setup_comm(struct uchcom_softc *sc)
767 {
768 	int ret;
769 
770 	ret = update_version(sc);
771 	if (ret)
772 		return ret;
773 
774 	ret = clear_chip(sc);
775 	if (ret)
776 		return ret;
777 
778 	ret = set_dte_rate(sc, TTYDEF_SPEED);
779 	if (ret)
780 		return ret;
781 
782 	ret = set_line_control(sc, CS8);
783 	if (ret)
784 		return ret;
785 
786 	ret = update_status(sc);
787 	if (ret)
788 		return ret;
789 
790 	ret = reset_chip(sc);
791 	if (ret)
792 		return ret;
793 
794 	ret = set_dte_rate(sc, TTYDEF_SPEED); /* XXX */
795 	if (ret)
796 		return ret;
797 
798 	sc->sc_dtr = sc->sc_rts = 1;
799 	ret = set_dtrrts(sc, sc->sc_dtr, sc->sc_rts);
800 	if (ret)
801 		return ret;
802 
803 	return 0;
804 }
805 
806 static int
807 setup_intr_pipe(struct uchcom_softc *sc)
808 {
809 	usbd_status err;
810 
811 	if (sc->sc_intr_endpoint != -1 && sc->sc_intr_pipe == NULL) {
812 		sc->sc_intr_buf = kmem_alloc(sc->sc_intr_size, KM_SLEEP);
813 		err = usbd_open_pipe_intr(sc->sc_iface,
814 					  sc->sc_intr_endpoint,
815 					  USBD_SHORT_XFER_OK,
816 					  &sc->sc_intr_pipe, sc,
817 					  sc->sc_intr_buf,
818 					  sc->sc_intr_size,
819 					  uchcom_intr, USBD_DEFAULT_INTERVAL);
820 		if (err) {
821 			device_printf(sc->sc_dev,
822 			    "cannot open interrupt pipe: %s\n",
823 			    usbd_errstr(err));
824 			return EIO;
825 		}
826 	}
827 	return 0;
828 }
829 
830 static void
831 close_intr_pipe(struct uchcom_softc *sc)
832 {
833 
834 	if (sc->sc_intr_pipe != NULL) {
835 		usbd_abort_pipe(sc->sc_intr_pipe);
836 		usbd_close_pipe(sc->sc_intr_pipe);
837 		sc->sc_intr_pipe = NULL;
838 	}
839 	if (sc->sc_intr_buf != NULL) {
840 		kmem_free(sc->sc_intr_buf, sc->sc_intr_size);
841 		sc->sc_intr_buf = NULL;
842 	}
843 }
844 
845 
846 /* ----------------------------------------------------------------------
847  * methods for ucom
848  */
849 static void
850 uchcom_get_status(void *arg, int portno, u_char *rlsr, u_char *rmsr)
851 {
852 	struct uchcom_softc *sc = arg;
853 
854 	if (sc->sc_dying)
855 		return;
856 
857 	*rlsr = sc->sc_lsr;
858 	*rmsr = sc->sc_msr;
859 }
860 
861 static void
862 uchcom_set(void *arg, int portno, int reg, int onoff)
863 {
864 	struct uchcom_softc *sc = arg;
865 
866 	if (sc->sc_dying)
867 		return;
868 
869 	switch (reg) {
870 	case UCOM_SET_DTR:
871 		sc->sc_dtr = !!onoff;
872 		set_dtrrts(sc, sc->sc_dtr, sc->sc_rts);
873 		break;
874 	case UCOM_SET_RTS:
875 		sc->sc_rts = !!onoff;
876 		set_dtrrts(sc, sc->sc_dtr, sc->sc_rts);
877 		break;
878 	case UCOM_SET_BREAK:
879 		set_break(sc, onoff);
880 		break;
881 	}
882 }
883 
884 static int
885 uchcom_param(void *arg, int portno, struct termios *t)
886 {
887 	struct uchcom_softc *sc = arg;
888 	int ret;
889 
890 	if (sc->sc_dying)
891 		return EIO;
892 
893 	ret = set_line_control(sc, t->c_cflag);
894 	if (ret)
895 		return ret;
896 
897 	ret = set_dte_rate(sc, t->c_ospeed);
898 	if (ret)
899 		return ret;
900 
901 	return 0;
902 }
903 
904 static int
905 uchcom_open(void *arg, int portno)
906 {
907 	int ret;
908 	struct uchcom_softc *sc = arg;
909 
910 	if (sc->sc_dying)
911 		return EIO;
912 
913 	ret = setup_intr_pipe(sc);
914 	if (ret)
915 		return ret;
916 
917 	ret = setup_comm(sc);
918 	if (ret)
919 		return ret;
920 
921 	return 0;
922 }
923 
924 static void
925 uchcom_close(void *arg, int portno)
926 {
927 	struct uchcom_softc *sc = arg;
928 
929 	if (sc->sc_dying)
930 		return;
931 
932 	close_intr_pipe(sc);
933 }
934 
935 
936 /* ----------------------------------------------------------------------
937  * callback when the modem status is changed.
938  */
939 static void
940 uchcom_intr(struct usbd_xfer *xfer, void * priv,
941 	    usbd_status status)
942 {
943 	struct uchcom_softc *sc = priv;
944 	u_char *buf = sc->sc_intr_buf;
945 
946 	if (sc->sc_dying)
947 		return;
948 
949 	if (status != USBD_NORMAL_COMPLETION) {
950 		if (status == USBD_NOT_STARTED || status == USBD_CANCELLED)
951 			return;
952 
953 		DPRINTF(("%s: abnormal status: %s\n",
954 			 device_xname(sc->sc_dev), usbd_errstr(status)));
955 		usbd_clear_endpoint_stall_async(sc->sc_intr_pipe);
956 		return;
957 	}
958 	DPRINTF(("%s: intr: 0x%02X 0x%02X 0x%02X 0x%02X "
959 		 "0x%02X 0x%02X 0x%02X 0x%02X\n",
960 		 device_xname(sc->sc_dev),
961 		 (unsigned)buf[0], (unsigned)buf[1],
962 		 (unsigned)buf[2], (unsigned)buf[3],
963 		 (unsigned)buf[4], (unsigned)buf[5],
964 		 (unsigned)buf[6], (unsigned)buf[7]));
965 
966 	convert_status(sc, buf[UCHCOM_INTR_STAT1]);
967 	ucom_status_change(device_private(sc->sc_subdev));
968 }
969