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