xref: /netbsd-src/sys/dev/usb/uchcom.c (revision c2f76ff004a2cb67efe5b12d97bd3ef7fe89e18d)
1 /*	$NetBSD: uchcom.c,v 1.10 2010/11/03 22:34:23 dyoung 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.10 2010/11/03 22:34:23 dyoung Exp $");
34 
35 /*
36  * driver for WinChipHead CH341/340, the worst USB-serial chip in the world.
37  */
38 
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
42 #include <sys/malloc.h>
43 #include <sys/ioctl.h>
44 #include <sys/conf.h>
45 #include <sys/tty.h>
46 #include <sys/file.h>
47 #include <sys/select.h>
48 #include <sys/proc.h>
49 #include <sys/device.h>
50 #include <sys/poll.h>
51 #include <sys/workqueue.h>
52 
53 #include <dev/usb/usb.h>
54 #include <dev/usb/usbcdc.h>
55 
56 #include <dev/usb/usbdi.h>
57 #include <dev/usb/usbdi_util.h>
58 #include <dev/usb/usbdevs.h>
59 #include <dev/usb/usb_quirks.h>
60 
61 #include <dev/usb/ucomvar.h>
62 
63 #ifdef UCHCOM_DEBUG
64 #define DPRINTFN(n, x)  if (uchcomdebug > (n)) printf x
65 int	uchcomdebug = 0;
66 #else
67 #define DPRINTFN(n, x)
68 #endif
69 #define DPRINTF(x) DPRINTFN(0, x)
70 
71 #define	UCHCOM_IFACE_INDEX	0
72 #define	UCHCOM_CONFIG_INDEX	0
73 
74 #define UCHCOM_REV_CH340	0x0250
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_BPS_MOD	0x14
88 #define UCHCOM_REG_BPS_PAD	0x0F
89 #define UCHCOM_REG_BREAK1	0x05
90 #define UCHCOM_REG_BREAK2	0x18
91 #define UCHCOM_REG_LCR1		0x18
92 #define UCHCOM_REG_LCR2		0x25
93 
94 #define UCHCOM_VER_20		0x20
95 
96 #define UCHCOM_BASE_UNKNOWN	0
97 #define UCHCOM_BPS_MOD_BASE	20000000
98 #define UCHCOM_BPS_MOD_BASE_OFS	1100
99 
100 #define UCHCOM_DTR_MASK		0x20
101 #define UCHCOM_RTS_MASK		0x40
102 
103 #define UCHCOM_BRK1_MASK	0x01
104 #define UCHCOM_BRK2_MASK	0x40
105 
106 #define UCHCOM_LCR1_MASK	0xAF
107 #define UCHCOM_LCR2_MASK	0x07
108 #define UCHCOM_LCR1_PARENB	0x80
109 #define UCHCOM_LCR2_PAREVEN	0x07
110 #define UCHCOM_LCR2_PARODD	0x06
111 #define UCHCOM_LCR2_PARMARK	0x05
112 #define UCHCOM_LCR2_PARSPACE	0x04
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 	usbd_device_handle	sc_udev;
125 	device_t		sc_subdev;
126 	usbd_interface_handle	sc_iface;
127 	int			sc_dying;
128 	/* */
129 	int			sc_intr_endpoint;
130 	int			sc_intr_size;
131 	usbd_pipe_handle	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 	int			sc_lcr1;
140 	int			sc_lcr2;
141 };
142 
143 struct uchcom_endpoints
144 {
145 	int		ep_bulkin;
146 	int		ep_bulkout;
147 	int		ep_intr;
148 	int		ep_intr_size;
149 };
150 
151 struct uchcom_divider
152 {
153 	uint8_t		dv_prescaler;
154 	uint8_t		dv_div;
155 	uint8_t		dv_mod;
156 };
157 
158 struct uchcom_divider_record
159 {
160 	uint32_t		dvr_high;
161 	uint32_t		dvr_low;
162 	uint32_t		dvr_base_clock;
163 	struct uchcom_divider	dvr_divider;
164 };
165 
166 static const struct uchcom_divider_record dividers[] =
167 {
168 	{  307200, 307200, UCHCOM_BASE_UNKNOWN, { 7, 0xD9, 0 } },
169 	{  921600, 921600, UCHCOM_BASE_UNKNOWN, { 7, 0xF3, 0 } },
170 	{ 2999999,  23530,             6000000, { 3,    0, 0 } },
171 	{   23529,   2942,              750000, { 2,    0, 0 } },
172 	{    2941,    368,               93750, { 1,    0, 0 } },
173 	{     367,      1,               11719, { 0,    0, 0 } },
174 };
175 #define NUM_DIVIDERS	(sizeof (dividers) / sizeof (dividers[0]))
176 
177 static const struct usb_devno uchcom_devs[] = {
178 	{ USB_VENDOR_WINCHIPHEAD, USB_PRODUCT_WINCHIPHEAD_CH341SER },
179 	{ USB_VENDOR_WINCHIPHEAD2, USB_PRODUCT_WINCHIPHEAD2_CH341 },
180 };
181 #define uchcom_lookup(v, p)	usb_lookup(uchcom_devs, v, p)
182 
183 Static void	uchcom_get_status(void *, int, u_char *, u_char *);
184 Static void	uchcom_set(void *, int, int, int);
185 Static int	uchcom_param(void *, int, struct termios *);
186 Static int	uchcom_open(void *, int);
187 Static void	uchcom_close(void *, int);
188 Static void	uchcom_intr(usbd_xfer_handle, usbd_private_handle,
189 			    usbd_status);
190 
191 static int	set_config(struct uchcom_softc *);
192 static int	find_ifaces(struct uchcom_softc *, usbd_interface_handle *);
193 static int	find_endpoints(struct uchcom_softc *,
194 			       struct uchcom_endpoints *);
195 static void	close_intr_pipe(struct uchcom_softc *);
196 
197 
198 struct	ucom_methods uchcom_methods = {
199 	.ucom_get_status	= uchcom_get_status,
200 	.ucom_set		= uchcom_set,
201 	.ucom_param		= uchcom_param,
202 	.ucom_ioctl		= NULL,
203 	.ucom_open		= uchcom_open,
204 	.ucom_close		= uchcom_close,
205 	.ucom_read		= NULL,
206 	.ucom_write		= NULL,
207 };
208 
209 int uchcom_match(device_t, cfdata_t, void *);
210 void uchcom_attach(device_t, device_t, void *);
211 void uchcom_childdet(device_t, device_t);
212 int uchcom_detach(device_t, int);
213 int uchcom_activate(device_t, enum devact);
214 
215 extern struct cfdriver uchcom_cd;
216 
217 CFATTACH_DECL2_NEW(uchcom,
218     sizeof(struct uchcom_softc),
219     uchcom_match,
220     uchcom_attach,
221     uchcom_detach,
222     uchcom_activate,
223     NULL,
224     uchcom_childdet);
225 
226 /* ----------------------------------------------------------------------
227  * driver entry points
228  */
229 
230 int
231 uchcom_match(device_t parent, cfdata_t match, void *aux)
232 {
233 	struct usb_attach_arg *uaa = aux;
234 
235 	return (uchcom_lookup(uaa->vendor, uaa->product) != NULL ?
236 		UMATCH_VENDOR_PRODUCT : UMATCH_NONE);
237 }
238 
239 void
240 uchcom_attach(device_t parent, device_t self, void *aux)
241 {
242 	struct uchcom_softc *sc = device_private(self);
243 	struct usb_attach_arg *uaa = aux;
244 	usbd_device_handle dev = uaa->device;
245 	char *devinfop;
246 	struct uchcom_endpoints endpoints;
247 	struct ucom_attach_args uca;
248 
249 	aprint_naive("\n");
250 	aprint_normal("\n");
251 
252 	devinfop = usbd_devinfo_alloc(dev, 0);
253 	aprint_normal_dev(self, "%s\n", devinfop);
254 	usbd_devinfo_free(devinfop);
255 
256 	sc->sc_dev = self;
257         sc->sc_udev = dev;
258 	sc->sc_dying = 0;
259 	sc->sc_dtr = sc->sc_rts = -1;
260 	sc->sc_lsr = sc->sc_msr = 0;
261 
262 	DPRINTF(("\n\nuchcom attach: sc=%p\n", sc));
263 
264 	if (set_config(sc))
265 		goto failed;
266 
267 	switch (uaa->release) {
268 	case UCHCOM_REV_CH340:
269 		aprint_normal_dev(self, "CH340 detected\n");
270 		break;
271 	default:
272 		aprint_normal_dev(self, "CH341 detected\n");
273 		break;
274 	}
275 
276 	if (find_ifaces(sc, &sc->sc_iface))
277 		goto failed;
278 
279 	if (find_endpoints(sc, &endpoints))
280 		goto failed;
281 
282 	sc->sc_intr_endpoint = endpoints.ep_intr;
283 	sc->sc_intr_size = endpoints.ep_intr_size;
284 
285 	/* setup ucom layer */
286 	uca.portno = UCOM_UNK_PORTNO;
287 	uca.bulkin = endpoints.ep_bulkin;
288 	uca.bulkout = endpoints.ep_bulkout;
289 	uca.ibufsize = UCHCOMIBUFSIZE;
290 	uca.obufsize = UCHCOMOBUFSIZE;
291 	uca.ibufsizepad = UCHCOMIBUFSIZE;
292 	uca.opkthdrlen = 0;
293 	uca.device = dev;
294 	uca.iface = sc->sc_iface;
295 	uca.methods = &uchcom_methods;
296 	uca.arg = sc;
297 	uca.info = NULL;
298 
299 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev,
300 			   sc->sc_dev);
301 
302 	sc->sc_subdev = config_found_sm_loc(self, "ucombus", NULL, &uca,
303 					    ucomprint, ucomsubmatch);
304 
305 	return;
306 
307 failed:
308 	sc->sc_dying = 1;
309 	return;
310 }
311 
312 void
313 uchcom_childdet(device_t self, device_t child)
314 {
315 	struct uchcom_softc *sc = device_private(self);
316 
317 	KASSERT(sc->sc_subdev == child);
318 	sc->sc_subdev = NULL;
319 }
320 
321 int
322 uchcom_detach(device_t self, int flags)
323 {
324 	struct uchcom_softc *sc = device_private(self);
325 	int rv = 0;
326 
327 	DPRINTF(("uchcom_detach: sc=%p flags=%d\n", sc, flags));
328 
329 	close_intr_pipe(sc);
330 
331 	sc->sc_dying = 1;
332 
333 	if (sc->sc_subdev != NULL)
334 		rv = config_detach(sc->sc_subdev, flags);
335 
336 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev,
337 			   sc->sc_dev);
338 
339 	return rv;
340 }
341 
342 int
343 uchcom_activate(device_t self, enum devact act)
344 {
345 	struct uchcom_softc *sc = device_private(self);
346 
347 	switch (act) {
348 	case DVACT_DEACTIVATE:
349 		close_intr_pipe(sc);
350 		sc->sc_dying = 1;
351 		return 0;
352 	default:
353 		return EOPNOTSUPP;
354 	}
355 }
356 
357 static int
358 set_config(struct uchcom_softc *sc)
359 {
360 	usbd_status err;
361 
362 	err = usbd_set_config_index(sc->sc_udev, UCHCOM_CONFIG_INDEX, 1);
363 	if (err) {
364 		aprint_error_dev(sc->sc_dev,
365 		    "failed to set configuration: %s\n", usbd_errstr(err));
366 		return -1;
367 	}
368 
369 	return 0;
370 }
371 
372 static int
373 find_ifaces(struct uchcom_softc *sc, usbd_interface_handle *riface)
374 {
375 	usbd_status err;
376 
377 	err = usbd_device2interface_handle(sc->sc_udev, UCHCOM_IFACE_INDEX,
378 					   riface);
379 	if (err) {
380 		aprint_error("\n%s: failed to get interface: %s\n",
381 			device_xname(sc->sc_dev), usbd_errstr(err));
382 		return -1;
383 	}
384 
385 	return 0;
386 }
387 
388 static int
389 find_endpoints(struct uchcom_softc *sc, struct uchcom_endpoints *endpoints)
390 {
391 	int i, bin=-1, bout=-1, intr=-1, isize=0;
392 	usb_interface_descriptor_t *id;
393 	usb_endpoint_descriptor_t *ed;
394 
395 	id = usbd_get_interface_descriptor(sc->sc_iface);
396 
397 	for (i = 0; i < id->bNumEndpoints; i++) {
398 		ed = usbd_interface2endpoint_descriptor(sc->sc_iface, i);
399 		if (ed == NULL) {
400 			aprint_error_dev(sc->sc_dev,
401 			    "no endpoint descriptor for %d\n", i);
402 			return -1;
403 		}
404 
405 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
406 		    UE_GET_XFERTYPE(ed->bmAttributes) == UE_INTERRUPT) {
407 			intr = ed->bEndpointAddress;
408 			isize = UGETW(ed->wMaxPacketSize);
409 		} else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
410 			   UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
411 			bin = ed->bEndpointAddress;
412 		} else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT &&
413 			   UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
414 			bout = ed->bEndpointAddress;
415 		}
416 	}
417 
418 	if (intr == -1 || bin == -1 || bout == -1) {
419 		if (intr == -1) {
420 			aprint_error_dev(sc->sc_dev,
421 			    "no interrupt end point\n");
422 		}
423 		if (bin == -1) {
424 			aprint_error_dev(sc->sc_dev,
425 			    "no data bulk in end point\n");
426 		}
427 		if (bout == -1) {
428 			aprint_error_dev(sc->sc_dev,
429 			    "no data bulk out end point\n");
430 		}
431 		return -1;
432 	}
433 	if (isize < UCHCOM_INTR_LEAST) {
434 		aprint_error_dev(sc->sc_dev, "intr pipe is too short\n");
435 		return -1;
436 	}
437 
438 	DPRINTF(("%s: bulkin=%d, bulkout=%d, intr=%d, isize=%d\n",
439 		 device_xname(sc->sc_dev), bin, bout, intr, isize));
440 
441 	endpoints->ep_intr = intr;
442 	endpoints->ep_intr_size = isize;
443 	endpoints->ep_bulkin = bin;
444 	endpoints->ep_bulkout = bout;
445 
446 	return 0;
447 }
448 
449 
450 /* ----------------------------------------------------------------------
451  * low level i/o
452  */
453 
454 static __inline usbd_status
455 generic_control_out(struct uchcom_softc *sc, uint8_t reqno,
456 		    uint16_t value, uint16_t index)
457 {
458 	usb_device_request_t req;
459 
460 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
461 	req.bRequest = reqno;
462 	USETW(req.wValue, value);
463 	USETW(req.wIndex, index);
464 	USETW(req.wLength, 0);
465 
466 	return usbd_do_request(sc->sc_udev, &req, 0);
467 }
468 
469 static __inline usbd_status
470 generic_control_in(struct uchcom_softc *sc, uint8_t reqno,
471 		   uint16_t value, uint16_t index, void *buf, int buflen,
472 		   int *actlen)
473 {
474 	usb_device_request_t req;
475 
476 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
477 	req.bRequest = reqno;
478 	USETW(req.wValue, value);
479 	USETW(req.wIndex, index);
480 	USETW(req.wLength, (uint16_t)buflen);
481 
482 	return usbd_do_request_flags(sc->sc_udev, &req, buf,
483 				     USBD_SHORT_XFER_OK, actlen,
484 				     USBD_DEFAULT_TIMEOUT);
485 }
486 
487 static __inline usbd_status
488 write_reg(struct uchcom_softc *sc,
489 	  uint8_t reg1, uint8_t val1, uint8_t reg2, uint8_t val2)
490 {
491 	DPRINTF(("uchcom: write reg 0x%02X<-0x%02X, 0x%02X<-0x%02X\n",
492 		 (unsigned)reg1, (unsigned)val1,
493 		 (unsigned)reg2, (unsigned)val2));
494 	return generic_control_out(
495 		sc, UCHCOM_REQ_WRITE_REG,
496 		reg1|((uint16_t)reg2<<8), val1|((uint16_t)val2<<8));
497 }
498 
499 static __inline usbd_status
500 read_reg(struct uchcom_softc *sc,
501 	 uint8_t reg1, uint8_t *rval1, uint8_t reg2, uint8_t *rval2)
502 {
503 	uint8_t buf[UCHCOM_INPUT_BUF_SIZE];
504 	usbd_status err;
505 	int actin;
506 
507 	err = generic_control_in(
508 		sc, UCHCOM_REQ_READ_REG,
509 		reg1|((uint16_t)reg2<<8), 0, buf, sizeof buf, &actin);
510 	if (err)
511 		return err;
512 
513 	DPRINTF(("uchcom: read reg 0x%02X->0x%02X, 0x%02X->0x%02X\n",
514 		 (unsigned)reg1, (unsigned)buf[0],
515 		 (unsigned)reg2, (unsigned)buf[1]));
516 
517 	if (rval1) *rval1 = buf[0];
518 	if (rval2) *rval2 = buf[1];
519 
520 	return USBD_NORMAL_COMPLETION;
521 }
522 
523 static __inline usbd_status
524 get_version(struct uchcom_softc *sc, uint8_t *rver)
525 {
526 	uint8_t buf[UCHCOM_INPUT_BUF_SIZE];
527 	usbd_status err;
528 	int actin;
529 
530 	err = generic_control_in(
531 		sc, UCHCOM_REQ_GET_VERSION, 0, 0, buf, sizeof buf, &actin);
532 	if (err)
533 		return err;
534 
535 	if (rver) *rver = buf[0];
536 
537 	return USBD_NORMAL_COMPLETION;
538 }
539 
540 static __inline usbd_status
541 get_status(struct uchcom_softc *sc, uint8_t *rval)
542 {
543 	return read_reg(sc, UCHCOM_REG_STAT1, rval, UCHCOM_REG_STAT2, NULL);
544 }
545 
546 static __inline usbd_status
547 set_dtrrts_10(struct uchcom_softc *sc, uint8_t val)
548 {
549 	return write_reg(sc, UCHCOM_REG_STAT1, val, UCHCOM_REG_STAT1, val);
550 }
551 
552 static __inline usbd_status
553 set_dtrrts_20(struct uchcom_softc *sc, uint8_t val)
554 {
555 	return generic_control_out(sc, UCHCOM_REQ_SET_DTRRTS, val, 0);
556 }
557 
558 
559 /* ----------------------------------------------------------------------
560  * middle layer
561  */
562 
563 static int
564 update_version(struct uchcom_softc *sc)
565 {
566 	usbd_status err;
567 
568 	err = get_version(sc, &sc->sc_version);
569 	if (err) {
570 		aprint_error_dev(sc->sc_dev, "cannot get version: %s\n",
571 		    usbd_errstr(err));
572 		return EIO;
573 	}
574 
575 	return 0;
576 }
577 
578 static void
579 convert_status(struct uchcom_softc *sc, uint8_t cur)
580 {
581 	sc->sc_dtr = !(cur & UCHCOM_DTR_MASK);
582 	sc->sc_rts = !(cur & UCHCOM_RTS_MASK);
583 
584 	cur = ~cur & 0x0F;
585 	sc->sc_msr = (cur << 4) | ((sc->sc_msr >> 4) ^ cur);
586 }
587 
588 static int
589 update_status(struct uchcom_softc *sc)
590 {
591 	usbd_status err;
592 	uint8_t cur;
593 
594 	err = get_status(sc, &cur);
595 	if (err) {
596 		aprint_error_dev(sc->sc_dev,
597 		    "cannot update status: %s\n", usbd_errstr(err));
598 		return EIO;
599 	}
600 	convert_status(sc, cur);
601 
602 	return 0;
603 }
604 
605 
606 static int
607 set_dtrrts(struct uchcom_softc *sc, int dtr, int rts)
608 {
609 	usbd_status err;
610 	uint8_t val = 0;
611 
612 	if (dtr) val |= UCHCOM_DTR_MASK;
613 	if (rts) val |= UCHCOM_RTS_MASK;
614 
615 	if (sc->sc_version < UCHCOM_VER_20)
616 		err = set_dtrrts_10(sc, ~val);
617 	else
618 		err = set_dtrrts_20(sc, ~val);
619 
620 	if (err) {
621 		aprint_error_dev(sc->sc_dev, "cannot set DTR/RTS: %s\n",
622 		    usbd_errstr(err));
623 		return EIO;
624 	}
625 
626 	return 0;
627 }
628 
629 static int
630 set_break(struct uchcom_softc *sc, int onoff)
631 {
632 	usbd_status err;
633 	uint8_t brk1, brk2;
634 
635 	err = read_reg(sc, UCHCOM_REG_BREAK1, &brk1, UCHCOM_REG_BREAK2, &brk2);
636 	if (err)
637 		return EIO;
638 	if (onoff) {
639 		/* on - clear bits */
640 		brk1 &= ~UCHCOM_BRK1_MASK;
641 		brk2 &= ~UCHCOM_BRK2_MASK;
642 	} else {
643 		/* off - set bits */
644 		brk1 |= UCHCOM_BRK1_MASK;
645 		brk2 |= UCHCOM_BRK2_MASK;
646 	}
647 	err = write_reg(sc, UCHCOM_REG_BREAK1, brk1, UCHCOM_REG_BREAK2, brk2);
648 	if (err)
649 		return EIO;
650 
651 	return 0;
652 }
653 
654 static int
655 calc_divider_settings(struct uchcom_divider *dp, uint32_t rate)
656 {
657 	int i;
658 	const struct uchcom_divider_record *rp;
659 	uint32_t div, rem, mod;
660 
661 	/* find record */
662 	for (i=0; i<NUM_DIVIDERS; i++) {
663 		if (dividers[i].dvr_high >= rate &&
664 		    dividers[i].dvr_low <= rate) {
665 			rp = &dividers[i];
666 			goto found;
667 		}
668 	}
669 	return -1;
670 
671 found:
672 	dp->dv_prescaler = rp->dvr_divider.dv_prescaler;
673 	if (rp->dvr_base_clock == UCHCOM_BASE_UNKNOWN)
674 		dp->dv_div = rp->dvr_divider.dv_div;
675 	else {
676 		div = rp->dvr_base_clock / rate;
677 		rem = rp->dvr_base_clock % rate;
678 		if (div==0 || div>=0xFF)
679 			return -1;
680 		if ((rem<<1) >= rate)
681 			div += 1;
682 		dp->dv_div = (uint8_t)-div;
683 	}
684 
685 	mod = UCHCOM_BPS_MOD_BASE/rate + UCHCOM_BPS_MOD_BASE_OFS;
686 	mod = mod + mod/2;
687 
688 	dp->dv_mod = mod / 0x100;
689 
690 	return 0;
691 }
692 
693 static int
694 set_dte_rate(struct uchcom_softc *sc, uint32_t rate)
695 {
696 	usbd_status err;
697 	struct uchcom_divider dv;
698 
699 	if (calc_divider_settings(&dv, rate))
700 		return EINVAL;
701 
702 	if ((err = write_reg(sc,
703 			     UCHCOM_REG_BPS_PRE, dv.dv_prescaler,
704 			     UCHCOM_REG_BPS_DIV, dv.dv_div)) ||
705 	    (err = write_reg(sc,
706 			     UCHCOM_REG_BPS_MOD, dv.dv_mod,
707 			     UCHCOM_REG_BPS_PAD, 0))) {
708 		aprint_error_dev(sc->sc_dev, "cannot set DTE rate: %s\n",
709 		    usbd_errstr(err));
710 		return EIO;
711 	}
712 
713 	return 0;
714 }
715 
716 static int
717 set_line_control(struct uchcom_softc *sc, tcflag_t cflag)
718 {
719 	usbd_status err;
720 	uint8_t lcr1val = 0, lcr2val = 0;
721 
722 	err = read_reg(sc, UCHCOM_REG_LCR1, &lcr1val, UCHCOM_REG_LCR2, &lcr2val);
723 	if (err) {
724 		aprint_error_dev(sc->sc_dev, "cannot get LCR: %s\n",
725 		    usbd_errstr(err));
726 		return EIO;
727 	}
728 
729 	lcr1val &= ~UCHCOM_LCR1_MASK;
730 	lcr2val &= ~UCHCOM_LCR2_MASK;
731 
732 	/*
733 	 * XXX: it is difficult to handle the line control appropriately:
734 	 *   - CS8, !CSTOPB and any parity mode seems ok, but
735 	 *   - the chip doesn't have the function to calculate parity
736 	 *     in !CS8 mode.
737 	 *   - it is unclear that the chip supports CS5,6 mode.
738 	 *   - it is unclear how to handle stop bits.
739 	 */
740 
741 	switch (ISSET(cflag, CSIZE)) {
742 	case CS5:
743 	case CS6:
744 	case CS7:
745 		return EINVAL;
746 	case CS8:
747 		break;
748 	}
749 
750 	if (ISSET(cflag, PARENB)) {
751 		lcr1val |= UCHCOM_LCR1_PARENB;
752 		if (ISSET(cflag, PARODD))
753 			lcr2val |= UCHCOM_LCR2_PARODD;
754 		else
755 			lcr2val |= UCHCOM_LCR2_PAREVEN;
756 	}
757 
758 	err = write_reg(sc, UCHCOM_REG_LCR1, lcr1val, UCHCOM_REG_LCR2, lcr2val);
759 	if (err) {
760 		aprint_error_dev(sc->sc_dev, "cannot set LCR: %s\n",
761 		    usbd_errstr(err));
762 		return EIO;
763 	}
764 
765 	return 0;
766 }
767 
768 static int
769 clear_chip(struct uchcom_softc *sc)
770 {
771 	usbd_status err;
772 
773 	DPRINTF(("%s: clear\n", device_xname(sc->sc_dev)));
774 	err = generic_control_out(sc, UCHCOM_REQ_RESET, 0, 0);
775 	if (err) {
776 		aprint_error_dev(sc->sc_dev, "cannot clear: %s\n",
777 		    usbd_errstr(err));
778 		return EIO;
779 	}
780 
781 	return 0;
782 }
783 
784 static int
785 reset_chip(struct uchcom_softc *sc)
786 {
787 	usbd_status err;
788 	uint8_t lcr1val, lcr2val, pre, div, mod;
789 	uint16_t val=0, idx=0;
790 
791 	err = read_reg(sc, UCHCOM_REG_LCR1, &lcr1val, UCHCOM_REG_LCR2, &lcr2val);
792 	if (err)
793 		goto failed;
794 
795 	err = read_reg(sc, UCHCOM_REG_BPS_PRE, &pre, UCHCOM_REG_BPS_DIV, &div);
796 	if (err)
797 		goto failed;
798 
799 	err = read_reg(sc, UCHCOM_REG_BPS_MOD, &mod, UCHCOM_REG_BPS_PAD, NULL);
800 	if (err)
801 		goto failed;
802 
803 	val |= (uint16_t)(lcr1val&0xF0) << 8;
804 	val |= 0x01;
805 	val |= (uint16_t)(lcr2val&0x0F) << 8;
806 	val |= 0x02;
807 	idx |= pre & 0x07;
808 	val |= 0x04;
809 	idx |= (uint16_t)div << 8;
810 	val |= 0x08;
811 	idx |= mod & 0xF8;
812 	val |= 0x10;
813 
814 	DPRINTF(("%s: reset v=0x%04X, i=0x%04X\n",
815 		 device_xname(sc->sc_dev), val, idx));
816 
817 	err = generic_control_out(sc, UCHCOM_REQ_RESET, val, idx);
818 	if (err)
819 		goto failed;
820 
821 	return 0;
822 
823 failed:
824 	printf("%s: cannot reset: %s\n",
825 	       device_xname(sc->sc_dev), usbd_errstr(err));
826 	return EIO;
827 }
828 
829 static int
830 setup_comm(struct uchcom_softc *sc)
831 {
832 	int ret;
833 
834 	ret = update_version(sc);
835 	if (ret)
836 		return ret;
837 
838 	ret = clear_chip(sc);
839 	if (ret)
840 		return ret;
841 
842 	ret = set_dte_rate(sc, TTYDEF_SPEED);
843 	if (ret)
844 		return ret;
845 
846 	ret = set_line_control(sc, CS8);
847 	if (ret)
848 		return ret;
849 
850 	ret = update_status(sc);
851 	if (ret)
852 		return ret;
853 
854 	ret = reset_chip(sc);
855 	if (ret)
856 		return ret;
857 
858 	ret = set_dte_rate(sc, TTYDEF_SPEED); /* XXX */
859 	if (ret)
860 		return ret;
861 
862 	sc->sc_dtr = sc->sc_rts = 1;
863 	ret = set_dtrrts(sc, sc->sc_dtr, sc->sc_rts);
864 	if (ret)
865 		return ret;
866 
867 	return 0;
868 }
869 
870 static int
871 setup_intr_pipe(struct uchcom_softc *sc)
872 {
873 	usbd_status err;
874 
875 	if (sc->sc_intr_endpoint != -1 && sc->sc_intr_pipe == NULL) {
876 		sc->sc_intr_buf = malloc(sc->sc_intr_size, M_USBDEV, M_WAITOK);
877 		err = usbd_open_pipe_intr(sc->sc_iface,
878 					  sc->sc_intr_endpoint,
879 					  USBD_SHORT_XFER_OK,
880 					  &sc->sc_intr_pipe, sc,
881 					  sc->sc_intr_buf,
882 					  sc->sc_intr_size,
883 					  uchcom_intr, USBD_DEFAULT_INTERVAL);
884 		if (err) {
885 			aprint_error_dev(sc->sc_dev,
886 			    "cannot open interrupt pipe: %s\n",
887 			    usbd_errstr(err));
888 			return EIO;
889 		}
890 	}
891 	return 0;
892 }
893 
894 static void
895 close_intr_pipe(struct uchcom_softc *sc)
896 {
897 	usbd_status err;
898 
899 	if (sc->sc_dying)
900 		return;
901 
902 	if (sc->sc_intr_pipe != NULL) {
903 		err = usbd_abort_pipe(sc->sc_intr_pipe);
904 		if (err)
905 			aprint_error_dev(sc->sc_dev,
906 			    "abort interrupt pipe failed: %s\n",
907 			    usbd_errstr(err));
908 		err = usbd_close_pipe(sc->sc_intr_pipe);
909 		if (err)
910 			aprint_error_dev(sc->sc_dev,
911 			    "close interrupt pipe failed: %s\n",
912 			    usbd_errstr(err));
913 		free(sc->sc_intr_buf, M_USBDEV);
914 		sc->sc_intr_pipe = NULL;
915 	}
916 }
917 
918 
919 /* ----------------------------------------------------------------------
920  * methods for ucom
921  */
922 void
923 uchcom_get_status(void *arg, int portno, u_char *rlsr, u_char *rmsr)
924 {
925 	struct uchcom_softc *sc = arg;
926 
927 	if (sc->sc_dying)
928 		return;
929 
930 	*rlsr = sc->sc_lsr;
931 	*rmsr = sc->sc_msr;
932 }
933 
934 void
935 uchcom_set(void *arg, int portno, int reg, int onoff)
936 {
937 	struct uchcom_softc *sc = arg;
938 
939 	if (sc->sc_dying)
940 		return;
941 
942 	switch (reg) {
943 	case UCOM_SET_DTR:
944 		sc->sc_dtr = !!onoff;
945 		set_dtrrts(sc, sc->sc_dtr, sc->sc_rts);
946 		break;
947 	case UCOM_SET_RTS:
948 		sc->sc_rts = !!onoff;
949 		set_dtrrts(sc, sc->sc_dtr, sc->sc_rts);
950 		break;
951 	case UCOM_SET_BREAK:
952 		set_break(sc, onoff);
953 		break;
954 	}
955 }
956 
957 int
958 uchcom_param(void *arg, int portno, struct termios *t)
959 {
960 	struct uchcom_softc *sc = arg;
961 	int ret;
962 
963 	if (sc->sc_dying)
964 		return 0;
965 
966 	ret = set_line_control(sc, t->c_cflag);
967 	if (ret)
968 		return ret;
969 
970 	ret = set_dte_rate(sc, t->c_ospeed);
971 	if (ret)
972 		return ret;
973 
974 	return 0;
975 }
976 
977 int
978 uchcom_open(void *arg, int portno)
979 {
980 	int ret;
981 	struct uchcom_softc *sc = arg;
982 
983 	if (sc->sc_dying)
984 		return EIO;
985 
986 	ret = setup_intr_pipe(sc);
987 	if (ret)
988 		return ret;
989 
990 	ret = setup_comm(sc);
991 	if (ret)
992 		return ret;
993 
994 	return 0;
995 }
996 
997 void
998 uchcom_close(void *arg, int portno)
999 {
1000 	struct uchcom_softc *sc = arg;
1001 
1002 	if (sc->sc_dying)
1003 		return;
1004 
1005 	close_intr_pipe(sc);
1006 }
1007 
1008 
1009 /* ----------------------------------------------------------------------
1010  * callback when the modem status is changed.
1011  */
1012 void
1013 uchcom_intr(usbd_xfer_handle xfer, usbd_private_handle priv,
1014 	    usbd_status status)
1015 {
1016 	struct uchcom_softc *sc = priv;
1017 	u_char *buf = sc->sc_intr_buf;
1018 
1019 	if (sc->sc_dying)
1020 		return;
1021 
1022 	if (status != USBD_NORMAL_COMPLETION) {
1023 		if (status == USBD_NOT_STARTED || status == USBD_CANCELLED)
1024 			return;
1025 
1026 		DPRINTF(("%s: abnormal status: %s\n",
1027 			 device_xname(sc->sc_dev), usbd_errstr(status)));
1028 		usbd_clear_endpoint_stall_async(sc->sc_intr_pipe);
1029 		return;
1030 	}
1031 	DPRINTF(("%s: intr: 0x%02X 0x%02X 0x%02X 0x%02X "
1032 		 "0x%02X 0x%02X 0x%02X 0x%02X\n",
1033 		 device_xname(sc->sc_dev),
1034 		 (unsigned)buf[0], (unsigned)buf[1],
1035 		 (unsigned)buf[2], (unsigned)buf[3],
1036 		 (unsigned)buf[4], (unsigned)buf[5],
1037 		 (unsigned)buf[6], (unsigned)buf[7]));
1038 
1039 	convert_status(sc, buf[UCHCOM_INTR_STAT1]);
1040 	ucom_status_change(device_private(sc->sc_subdev));
1041 }
1042