2101d7a09c3f36fdd74d4fcfd9bf7633d9602025
[dragonfly.git] / sys / bus / u4b / serial / usb_serial.c
1 /*      $NetBSD: ucom.c,v 1.40 2001/11/13 06:24:54 lukem Exp $  */
2
3 /*-
4  * Copyright (c) 2001-2003, 2005, 2008
5  *      Shunsuke Akiyama <akiyama@jp.FreeBSD.org>.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 /*-
31  * Copyright (c) 1998, 2000 The NetBSD Foundation, Inc.
32  * All rights reserved.
33  *
34  * This code is derived from software contributed to The NetBSD Foundation
35  * by Lennart Augustsson (lennart@augustsson.net) at
36  * Carlstedt Research & Technology.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. All advertising materials mentioning features or use of this software
47  *    must display the following acknowledgement:
48  *        This product includes software developed by the NetBSD
49  *        Foundation, Inc. and its contributors.
50  * 4. Neither the name of The NetBSD Foundation nor the names of its
51  *    contributors may be used to endorse or promote products derived
52  *    from this software without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
55  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
56  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
57  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
58  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
59  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
60  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
61  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
62  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
63  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
64  * POSSIBILITY OF SUCH DAMAGE.
65  */
66
67 /*
68  * XXX profmakx
69  * This is a Frankenstein of FreeBSD's usb4bsd ucom and Dragonfly's old ucom
70  * module. There might be bugs lurking everywhere still
71  *
72  * In particular serial console on ucom is completely untested and likely broken
73  * as well as anyting that requires the modem control lines.
74  */
75
76 #include <sys/stdint.h>
77 #include <sys/param.h>
78 #include <sys/queue.h>
79 #include <sys/types.h>
80 #include <sys/systm.h>
81 #include <sys/kernel.h>
82 #include <sys/bus.h>
83 #include <sys/module.h>
84 #include <sys/lock.h>
85 #include <sys/condvar.h>
86 #include <sys/sysctl.h>
87 #include <sys/unistd.h>
88 #include <sys/callout.h>
89 #include <sys/malloc.h>
90 #include <sys/priv.h>
91 #include <sys/cons.h>
92 #include <sys/serial.h>
93 #include <sys/thread2.h>
94 #include <sys/conf.h>
95 #include <sys/clist.h>
96
97 #include <bus/u4b/usb.h>
98 #include <bus/u4b/usbdi.h>
99 #include <bus/u4b/usbdi_util.h>
100
101 #define USB_DEBUG_VAR ucom_debug
102 #include <bus/u4b/usb_debug.h>
103 #include <bus/u4b/usb_busdma.h>
104 #include <bus/u4b/usb_process.h>
105
106 #include <bus/u4b/serial/usb_serial.h>
107
108 /* #include "opt_gdb.h" */
109
110 static SYSCTL_NODE(_hw_usb, OID_AUTO, ucom, CTLFLAG_RW, 0, "USB ucom");
111
112 static int ucom_pps_mode;
113
114 SYSCTL_INT(_hw_usb_ucom, OID_AUTO, pps_mode, CTLFLAG_RW,
115     &ucom_pps_mode, 0, "pulse capturing mode - 0/1/2 - disabled/CTS/DCD");
116 TUNABLE_INT("hw.usb.ucom.pss_mode", &ucom_pps_mode);
117
118
119 #ifdef USB_DEBUG
120 static int ucom_debug = 0;
121
122 SYSCTL_INT(_hw_usb_ucom, OID_AUTO, debug, CTLFLAG_RW,
123     &ucom_debug, 0, "ucom debug level");
124 #endif
125
126 #define UCOM_CONS_BUFSIZE 1024
127
128 static uint8_t ucom_cons_rx_buf[UCOM_CONS_BUFSIZE];
129 static uint8_t ucom_cons_tx_buf[UCOM_CONS_BUFSIZE];
130
131 static unsigned int ucom_cons_rx_low = 0;
132 static unsigned int ucom_cons_rx_high = 0;
133
134 static unsigned int ucom_cons_tx_low = 0;
135 static unsigned int ucom_cons_tx_high = 0;
136
137 static int ucom_cons_unit = -1;
138 static int ucom_cons_subunit = 0;
139 static int ucom_cons_baud = 9600;
140 static struct ucom_softc *ucom_cons_softc = NULL;
141
142 TUNABLE_INT("hw.usb.ucom.cons_unit", &ucom_cons_unit);
143 SYSCTL_INT(_hw_usb_ucom, OID_AUTO, cons_unit, CTLFLAG_RW,
144     &ucom_cons_unit, 0, "console unit number");
145 TUNABLE_INT("hw.usb.ucom.cons_subunit", &ucom_cons_subunit);
146 SYSCTL_INT(_hw_usb_ucom, OID_AUTO, cons_subunit, CTLFLAG_RW,
147     &ucom_cons_subunit, 0, "console subunit number");
148 TUNABLE_INT("hw.usb.ucom.cons_baud", &ucom_cons_baud);
149 SYSCTL_INT(_hw_usb_ucom, OID_AUTO, cons_baud, CTLFLAG_RW,
150     &ucom_cons_baud, 0, "console baud rate");
151
152 static usb_proc_callback_t ucom_cfg_start_transfers;
153 static usb_proc_callback_t ucom_cfg_open;
154 static usb_proc_callback_t ucom_cfg_close;
155 static usb_proc_callback_t ucom_cfg_line_state;
156 static usb_proc_callback_t ucom_cfg_status_change;
157 static usb_proc_callback_t ucom_cfg_param;
158
159 static int      ucom_unit_alloc(void);
160 static void     ucom_unit_free(int);
161 static int      ucom_attach_tty(struct ucom_super_softc *, struct ucom_softc *);
162 static void     ucom_detach_tty(struct ucom_super_softc *, struct ucom_softc *);
163 static void     ucom_queue_command(struct ucom_softc *,
164                     usb_proc_callback_t *, struct termios *pt,
165                     struct usb_proc_msg *t0, struct usb_proc_msg *t1);
166 static void     ucom_shutdown(struct ucom_softc *);
167 static void     ucom_ring(struct ucom_softc *, uint8_t);
168 static void     ucom_break(struct ucom_softc *, uint8_t);
169 static void     ucom_dtr(struct ucom_softc *, uint8_t);
170 static void     ucom_rts(struct ucom_softc *, uint8_t);
171
172 static int ucom_open(struct ucom_softc *sc);
173 static int ucom_close(struct ucom_softc *sc);
174 static void ucom_start(struct tty *tp);
175 static void ucom_stop(struct tty *tp, int);
176 static int ucom_param(struct tty *tp, struct termios *t);
177 static int ucom_modem(struct tty *tp, int sigon, int sigoff);
178
179 static int ucom_fromtio(int);
180 static int ucom_totio(int);
181
182 static void disc_optim(struct tty *, struct termios *, struct ucom_softc *);
183
184 static d_open_t ucom_dev_open;
185 static d_close_t ucom_dev_close;
186 static d_read_t ucom_dev_read;
187 static d_write_t ucom_dev_write;
188 static d_ioctl_t ucom_dev_ioctl;
189
190 static struct dev_ops ucom_ops = {
191   { "ucom", 0, D_MPSAFE | D_TTY },
192   .d_open =       ucom_dev_open,
193   .d_close =      ucom_dev_close,
194   .d_read =       ucom_dev_read,
195   .d_write =      ucom_dev_write,
196   .d_ioctl =      ucom_dev_ioctl,
197   .d_kqfilter =   ttykqfilter,
198   .d_revoke =     ttyrevoke
199 };
200
201 static moduledata_t ucom_mod = {
202         "ucom",
203         NULL,
204         NULL
205 };
206
207 DECLARE_MODULE(ucom, ucom_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
208 MODULE_DEPEND(ucom, usb, 1, 1, 1);
209 MODULE_VERSION(ucom, UCOM_MODVER);
210
211 /* XXXDF */
212 #define tty_gone(tp) ((tp->t_state) & (TS_ZOMBIE))
213
214 #define UCOM_UNIT_MAX           128     /* maximum number of units */
215 #define UCOM_TTY_PREFIX         "ucom"
216
217
218 #define CALLOUT_MASK            0x80
219 #define CONTROL_MASK            0x60
220 #define CONTROL_INIT_STATE      0x20
221 #define CONTROL_LOCK_STATE      0x40
222
223 static struct unrhdr *ucom_unrhdr;
224 static struct lock ucom_lock;
225 static int ucom_close_refs;
226
227 static void
228 ucom_init(void *arg)
229 {
230         DPRINTF("\n");
231         ucom_unrhdr = new_unrhdr(0, UCOM_UNIT_MAX - 1, NULL);
232         lockinit(&ucom_lock, "UCOM LOCK", 0, 0);
233 }
234 SYSINIT(ucom_init, SI_BOOT2_KLD - 1, SI_ORDER_ANY, ucom_init, NULL);
235
236 static void
237 ucom_uninit(void *arg)
238 {
239         struct unrhdr *hdr;
240         hdr = ucom_unrhdr;
241         ucom_unrhdr = NULL;
242
243         DPRINTF("\n");
244
245         if (hdr != NULL)
246                 delete_unrhdr(hdr);
247
248         lockuninit(&ucom_lock);
249 }
250 SYSUNINIT(ucom_uninit, SI_BOOT2_KLD - 2, SI_ORDER_ANY, ucom_uninit, NULL);
251
252 /*
253  * Mark a unit number (the X in cuaUX) as in use.
254  *
255  * Note that devices using a different naming scheme (see ucom_tty_name()
256  * callback) still use this unit allocation.
257  */
258 static int
259 ucom_unit_alloc(void)
260 {
261         int unit;
262
263         /* sanity checks */
264         if (ucom_unrhdr == NULL) {
265                 DPRINTF("ucom_unrhdr is NULL\n");
266                 return (-1);
267         }
268         unit = alloc_unr(ucom_unrhdr);
269         DPRINTF("unit %d is allocated\n", unit);
270         return (unit);
271 }
272
273 /*
274  * Mark the unit number as not in use.
275  */
276 static void
277 ucom_unit_free(int unit)
278 {
279         /* sanity checks */
280         if (unit < 0 || unit >= UCOM_UNIT_MAX || ucom_unrhdr == NULL) {
281                 DPRINTF("cannot free unit number\n");
282                 return;
283         }
284         DPRINTF("unit %d is freed\n", unit);
285         free_unr(ucom_unrhdr, unit);
286 }
287
288 /*
289  * Setup a group of one or more serial ports.
290  *
291  * The lock pointed to by "lock" is applied before all
292  * callbacks are called back. Also "lock" must be applied
293  * before calling into the ucom-layer!
294  */
295 int
296 ucom_attach(struct ucom_super_softc *ssc, struct ucom_softc *sc,
297     int subunits, void *parent,
298     const struct ucom_callback *callback, struct lock *lock)
299 {
300         int subunit;
301         int error = 0;
302
303         if ((sc == NULL) ||
304             (subunits <= 0) ||
305             (callback == NULL) ||
306             (lock == NULL)) {
307                 return (EINVAL);
308         }
309
310         /* XXX Do we want our own lock here maybe */
311         sc->sc_lock = lock;
312
313         /* allocate a uniq unit number */
314         ssc->sc_unit = ucom_unit_alloc();
315         if (ssc->sc_unit == -1)
316                 return (ENOMEM);
317
318         /* generate TTY name string */
319         ksnprintf(ssc->sc_ttyname, sizeof(ssc->sc_ttyname),
320             UCOM_TTY_PREFIX "%d", ssc->sc_unit);
321
322         /* create USB request handling process */
323         error = usb_proc_create(&ssc->sc_tq, lock, "ucom", USB_PRI_MED);
324         if (error) {
325                 ucom_unit_free(ssc->sc_unit);
326                 return (error);
327         }
328         ssc->sc_subunits = subunits;
329         ssc->sc_flag = UCOM_FLAG_ATTACHED |
330             UCOM_FLAG_FREE_UNIT;
331
332         if (callback->ucom_free == NULL)
333                 ssc->sc_flag |= UCOM_FLAG_WAIT_REFS;
334
335         /* increment reference count */
336         ucom_ref(ssc);
337
338         for (subunit = 0; subunit < ssc->sc_subunits; subunit++) {
339                 sc[subunit].sc_subunit = subunit;
340                 sc[subunit].sc_super = ssc;
341                 sc[subunit].sc_lock = lock;
342                 sc[subunit].sc_parent = parent;
343                 sc[subunit].sc_callback = callback;
344
345                 error = ucom_attach_tty(ssc, &sc[subunit]);
346                 if (error) {
347                         ucom_detach(ssc, &sc[0]);
348                         return (error);
349                 }
350                 /* increment reference count */
351                 ucom_ref(ssc);
352
353                 /* set subunit attached */
354                 sc[subunit].sc_flag |= UCOM_FLAG_ATTACHED;
355         }
356
357         DPRINTF("tp = %p, unit = %d, subunits = %d\n",
358                 sc->sc_tty, ssc->sc_unit, ssc->sc_subunits);
359
360         return (0);
361 }
362
363 /*
364  * The following function will do nothing if the structure pointed to
365  * by "ssc" and "sc" is zero or has already been detached.
366  */
367 void
368 ucom_detach(struct ucom_super_softc *ssc, struct ucom_softc *sc)
369 {
370         int subunit;
371
372         if (!(ssc->sc_flag & UCOM_FLAG_ATTACHED))
373                 return;         /* not initialized */
374
375         destroy_dev(sc->sc_cdev);
376         destroy_dev(sc->sc_cdev_init);
377         destroy_dev(sc->sc_cdev_lock);
378         destroy_dev(sc->sc_cdev2);
379         destroy_dev(sc->sc_cdev2_init);
380         destroy_dev(sc->sc_cdev2_lock);
381
382         if (sc->sc_tty)
383                 lwkt_gettoken(&sc->sc_tty->t_token);
384
385         if (ssc->sc_sysctl_ttyname != NULL) {
386                 sysctl_remove_oid(ssc->sc_sysctl_ttyname, 1, 0);
387                 ssc->sc_sysctl_ttyname = NULL;
388         }
389
390         if (ssc->sc_sysctl_ttyports != NULL) {
391                 sysctl_remove_oid(ssc->sc_sysctl_ttyports, 1, 0);
392                 ssc->sc_sysctl_ttyports = NULL;
393         }
394
395         usb_proc_drain(&ssc->sc_tq);
396
397         for (subunit = 0; subunit < ssc->sc_subunits; subunit++) {
398                 if (sc[subunit].sc_flag & UCOM_FLAG_ATTACHED) {
399
400                         ucom_detach_tty(ssc, &sc[subunit]);
401
402                         /* avoid duplicate detach */
403                         sc[subunit].sc_flag &= ~UCOM_FLAG_ATTACHED;
404                 }
405         }
406         usb_proc_free(&ssc->sc_tq);
407
408         ucom_unref(ssc);
409
410         if (ssc->sc_flag & UCOM_FLAG_WAIT_REFS)
411                 ucom_drain(ssc);
412
413         /* make sure we don't detach twice */
414         ssc->sc_flag &= ~UCOM_FLAG_ATTACHED;
415
416         if (sc->sc_tty)
417                 lwkt_reltoken(&sc->sc_tty->t_token);
418 }
419
420 void
421 ucom_drain(struct ucom_super_softc *ssc)
422 {
423         lockmgr(&ucom_lock, LK_EXCLUSIVE);
424         while (ssc->sc_refs > 0) {
425                 kprintf("ucom: Waiting for a TTY device to close.\n");
426                 usb_pause_mtx(&ucom_lock, hz);
427         }
428         lockmgr(&ucom_lock, LK_RELEASE);
429 }
430
431 void
432 ucom_drain_all(void *arg)
433 {
434         lockmgr(&ucom_lock, LK_EXCLUSIVE);
435         while (ucom_close_refs > 0) {
436                 kprintf("ucom: Waiting for all detached TTY "
437                     "devices to have open fds closed.\n");
438                 usb_pause_mtx(&ucom_lock, hz);
439         }
440         lockmgr(&ucom_lock, LK_RELEASE);
441 }
442
443 static int
444 ucom_attach_tty(struct ucom_super_softc *ssc, struct ucom_softc *sc)
445 {
446         struct tty *tp;
447         char buf[32];                   /* temporary TTY device name buffer */
448
449         tp = ttymalloc(&sc->sc_tty);
450
451         lwkt_gettoken(&tp->t_token);
452
453         tp->t_sc = (void *)sc;
454
455         tp->t_oproc = ucom_start;
456         tp->t_param = ucom_param;
457         tp->t_stop = ucom_stop;
458
459         /* Check if the client has a custom TTY name */
460         buf[0] = '\0';
461         if (sc->sc_callback->ucom_tty_name) {
462                 sc->sc_callback->ucom_tty_name(sc, buf,
463                     sizeof(buf), ssc->sc_unit, sc->sc_subunit);
464         }
465         if (buf[0] == 0) {
466                 /* Use default TTY name */
467                 if (ssc->sc_subunits > 1) {
468                         /* multiple modems in one */
469                         ksnprintf(buf, sizeof(buf), "%u.%u",
470                             ssc->sc_unit, sc->sc_subunit);
471                 } else {
472                         /* single modem */
473                         ksnprintf(buf, sizeof(buf), "%u",
474                             ssc->sc_unit);
475                 }
476         }
477
478         sc->sc_cdev = make_dev(&ucom_ops, ssc->sc_unit,
479                         UID_ROOT, GID_WHEEL, 0600, "ttyU%s", buf);
480         sc->sc_cdev_init = make_dev(&ucom_ops, ssc->sc_unit | CONTROL_INIT_STATE,
481                         UID_ROOT, GID_WHEEL, 0600, "ttyiU%s", buf);
482         sc->sc_cdev_lock = make_dev(&ucom_ops, ssc->sc_unit | CONTROL_LOCK_STATE,
483                         UID_ROOT, GID_WHEEL, 0600, "ttylU%s", buf);
484         sc->sc_cdev2 = make_dev(&ucom_ops, ssc->sc_unit | CALLOUT_MASK,
485                         UID_UUCP, GID_DIALER, 0660, "cuaU%s", buf);
486         sc->sc_cdev2_init = make_dev(&ucom_ops, ssc->sc_unit | CALLOUT_MASK | CONTROL_INIT_STATE,
487                         UID_UUCP, GID_DIALER, 0660, "cuaiU%s", buf);
488         sc->sc_cdev2_lock = make_dev(&ucom_ops, ssc->sc_unit | CALLOUT_MASK | CONTROL_LOCK_STATE,
489                         UID_UUCP, GID_DIALER, 0660, "cualU%s", buf);
490
491         sc->sc_cdev->si_tty = tp;
492         sc->sc_cdev_init->si_tty = tp;
493         sc->sc_cdev_lock->si_tty = tp;
494
495         sc->sc_cdev->si_drv1 = sc;
496         sc->sc_cdev_init->si_drv1 = sc;
497         sc->sc_cdev_lock->si_drv1 = sc;
498
499         sc->sc_cdev2->si_tty = tp;
500         sc->sc_cdev2_init->si_tty = tp;
501         sc->sc_cdev2_lock->si_tty = tp;
502
503         sc->sc_cdev2->si_drv1 = sc;
504         sc->sc_cdev2_init->si_drv1 = sc;
505         sc->sc_cdev2_lock->si_drv1 = sc;
506
507         sc->sc_tty = tp;
508
509         DPRINTF("ttycreate: %s\n", buf);
510
511         /* Check if this device should be a console */
512         if ((ucom_cons_softc == NULL) && 
513             (ssc->sc_unit == ucom_cons_unit) &&
514             (sc->sc_subunit == ucom_cons_subunit)) {
515
516                 DPRINTF("unit %d subunit %d is console",
517                     ssc->sc_unit, sc->sc_subunit);
518
519                 ucom_cons_softc = sc;
520
521 #if 0 /* XXXDF */
522                 tty_init_console(tp, ucom_cons_baud);
523 #endif
524                 tp->t_termios.c_ispeed = ucom_cons_baud;
525                 tp->t_termios.c_ospeed = ucom_cons_baud;
526
527                 UCOM_MTX_LOCK(ucom_cons_softc);
528                 ucom_cons_rx_low = 0;
529                 ucom_cons_rx_high = 0;
530                 ucom_cons_tx_low = 0;
531                 ucom_cons_tx_high = 0;
532                 sc->sc_flag |= UCOM_FLAG_CONSOLE;
533                 ucom_open(ucom_cons_softc);
534                 ucom_param(tp, &tp->t_termios);
535                 UCOM_MTX_UNLOCK(ucom_cons_softc);
536         }
537
538         lwkt_reltoken(&tp->t_token);
539
540         return (0);
541 }
542
543 static void
544 ucom_detach_tty(struct ucom_super_softc *ssc, struct ucom_softc *sc)
545 {
546         struct tty *tp = sc->sc_tty;
547
548         DPRINTF("sc = %p, tp = %p\n", sc, sc->sc_tty);
549
550         if (sc->sc_flag & UCOM_FLAG_CONSOLE) {
551                 UCOM_MTX_LOCK(ucom_cons_softc);
552                 ucom_close(ucom_cons_softc);
553                 sc->sc_flag &= ~UCOM_FLAG_CONSOLE;
554                 UCOM_MTX_UNLOCK(ucom_cons_softc);
555                 ucom_cons_softc = NULL;
556         }
557
558         /* the config thread has been stopped when we get here */
559
560         UCOM_MTX_LOCK(sc);
561         sc->sc_flag |= UCOM_FLAG_GONE;
562         sc->sc_flag &= ~(UCOM_FLAG_HL_READY | UCOM_FLAG_LL_READY);
563         UCOM_MTX_UNLOCK(sc);
564
565         if (tp != NULL) {
566                 lwkt_gettoken(&tp->t_token);
567                 ucom_close_refs++;
568
569                 UCOM_MTX_LOCK(sc);
570                 if (tp->t_state & TS_ISOPEN) {
571                         kprintf("device still open, forcing close\n");
572                         (*linesw[tp->t_line].l_close)(tp, 0);
573                         ttyclose(tp);
574                 }
575                 ucom_close(sc); /* close, if any */
576
577                 /*
578                  * make sure that read and write transfers are stopped
579                  */
580                 if (sc->sc_callback->ucom_stop_read) {
581                         (sc->sc_callback->ucom_stop_read) (sc);
582                 }
583                 if (sc->sc_callback->ucom_stop_write) {
584                         (sc->sc_callback->ucom_stop_write) (sc);
585                 }
586                 UCOM_MTX_UNLOCK(sc);
587                 lwkt_reltoken(&tp->t_token);
588         } else {
589                 DPRINTF("no tty\n");
590         }
591
592         dev_ops_remove_minor(&ucom_ops,ssc->sc_unit);
593
594         ucom_unref(ssc);
595 }
596
597 void
598 ucom_set_pnpinfo_usb(struct ucom_super_softc *ssc, device_t dev)
599 {
600         char buf[64];
601         uint8_t iface_index;
602         struct usb_attach_arg *uaa;
603
604         ksnprintf(buf, sizeof(buf), "ttyname=" UCOM_TTY_PREFIX
605             "%d ttyports=%d", ssc->sc_unit, ssc->sc_subunits);
606
607         /* Store the PNP info in the first interface for the device */
608         uaa = device_get_ivars(dev);
609         iface_index = uaa->info.bIfaceIndex;
610
611         if (usbd_set_pnpinfo(uaa->device, iface_index, buf) != 0)
612                 device_printf(dev, "Could not set PNP info\n");
613
614         /*
615          * The following information is also replicated in the PNP-info
616          * string which is registered above:
617          */
618         if (ssc->sc_sysctl_ttyname == NULL) {
619                 /*
620                 ssc->sc_sysctl_ttyname = SYSCTL_ADD_STRING(NULL,
621                     SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
622                     OID_AUTO, "ttyname", CTLFLAG_RD, ssc->sc_ttyname, 0,
623                     "TTY device basename");
624                 */
625         }
626         if (ssc->sc_sysctl_ttyports == NULL) {
627                 /*
628                 ssc->sc_sysctl_ttyports = SYSCTL_ADD_INT(NULL,
629                     SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
630                     OID_AUTO, "ttyports", CTLFLAG_RD,
631                     NULL, ssc->sc_subunits, "Number of ports");
632                 */
633         }
634 }
635
636 static void
637 ucom_queue_command(struct ucom_softc *sc,
638     usb_proc_callback_t *fn, struct termios *pt,
639     struct usb_proc_msg *t0, struct usb_proc_msg *t1)
640 {
641         struct ucom_super_softc *ssc = sc->sc_super;
642         struct ucom_param_task *task;
643
644         UCOM_MTX_ASSERT(sc, MA_OWNED);
645
646         if (usb_proc_is_gone(&ssc->sc_tq)) {
647                 DPRINTF("proc is gone\n");
648                 return;         /* nothing to do */
649         }
650         /* 
651          * NOTE: The task cannot get executed before we drop the
652          * "sc_lock" lock. It is safe to update fields in the message
653          * structure after that the message got queued.
654          */
655         task = (struct ucom_param_task *)
656           usb_proc_msignal(&ssc->sc_tq, t0, t1);
657
658         /* Setup callback and softc pointers */
659         task->hdr.pm_callback = fn;
660         task->sc = sc;
661
662         /* 
663          * Make a copy of the termios. This field is only present if
664          * the "pt" field is not NULL.
665          */
666         if (pt != NULL)
667                 task->termios_copy = *pt;
668
669         /*
670          * Closing the device should be synchronous.
671          */
672         if (fn == ucom_cfg_close)
673                 usb_proc_mwait(&ssc->sc_tq, t0, t1);
674
675         /*
676          * In case of multiple configure requests,
677          * keep track of the last one!
678          */
679         if (fn == ucom_cfg_start_transfers)
680                 sc->sc_last_start_xfer = &task->hdr;
681 }
682
683 static void
684 ucom_shutdown(struct ucom_softc *sc)
685 {
686         struct tty *tp = sc->sc_tty;
687
688         UCOM_MTX_ASSERT(sc, MA_OWNED);
689
690         DPRINTF("\n");
691
692         /*
693          * Hang up if necessary:
694          */
695         if (tp->t_termios.c_cflag & HUPCL) {
696                 ucom_modem(tp, 0, SER_DTR);
697         }
698 }
699
700 /*
701  * Return values:
702  *    0: normal
703  * else: taskqueue is draining or gone
704  */
705 uint8_t
706 ucom_cfg_is_gone(struct ucom_softc *sc)
707 {
708         struct ucom_super_softc *ssc = sc->sc_super;
709
710         return (usb_proc_is_gone(&ssc->sc_tq));
711 }
712
713 static void
714 ucom_cfg_start_transfers(struct usb_proc_msg *_task)
715 {
716         struct ucom_cfg_task *task = 
717             (struct ucom_cfg_task *)_task;
718         struct ucom_softc *sc = task->sc;
719
720         if (!(sc->sc_flag & UCOM_FLAG_LL_READY)) {
721                 return;
722         }
723         if (!(sc->sc_flag & UCOM_FLAG_HL_READY)) {
724                 /* TTY device closed */
725                 return;
726         }
727
728         if (_task == sc->sc_last_start_xfer)
729                 sc->sc_flag |= UCOM_FLAG_GP_DATA;
730
731         if (sc->sc_callback->ucom_start_read) {
732                 (sc->sc_callback->ucom_start_read) (sc);
733         }
734         if (sc->sc_callback->ucom_start_write) {
735                 (sc->sc_callback->ucom_start_write) (sc);
736         }
737 }
738
739 static void
740 ucom_start_transfers(struct ucom_softc *sc)
741 {
742         if (!(sc->sc_flag & UCOM_FLAG_HL_READY)) {
743                 return;
744         }
745         /*
746          * Make sure that data transfers are started in both
747          * directions:
748          */
749         if (sc->sc_callback->ucom_start_read) {
750                 (sc->sc_callback->ucom_start_read) (sc);
751         }
752         if (sc->sc_callback->ucom_start_write) {
753                 (sc->sc_callback->ucom_start_write) (sc);
754         }
755 }
756
757 static void
758 ucom_cfg_open(struct usb_proc_msg *_task)
759 {
760         struct ucom_cfg_task *task = 
761             (struct ucom_cfg_task *)_task;
762         struct ucom_softc *sc = task->sc;
763
764         DPRINTF("\n");
765
766         if (sc->sc_flag & UCOM_FLAG_LL_READY) {
767
768                 /* already opened */
769
770         } else {
771
772                 sc->sc_flag |= UCOM_FLAG_LL_READY;
773
774                 if (sc->sc_callback->ucom_cfg_open) {
775                         (sc->sc_callback->ucom_cfg_open) (sc);
776
777                         /* wait a little */
778                         usb_pause_mtx(sc->sc_lock, hz / 10);
779                 }
780         }
781 }
782
783 static int
784 ucom_dev_open(struct dev_open_args *ap)
785 {
786         cdev_t dev = ap->a_head.a_dev;
787         struct ucom_softc *sc = (struct ucom_softc *)dev->si_drv1;
788         int error;
789         int mynor;
790
791         error = 0;
792         mynor = minor(dev);
793
794         UCOM_MTX_LOCK(sc);
795         error = ucom_open(sc);
796         UCOM_MTX_UNLOCK(sc);
797
798         return error;
799 }
800
801 static int
802 ucom_open(struct ucom_softc *sc)
803 {
804         int error;
805         struct tty *tp;
806
807         int mynor;
808
809         mynor = minor(sc->sc_cdev);
810
811         if (sc->sc_flag & UCOM_FLAG_GONE) {
812                 return (ENXIO);
813         }
814         if (sc->sc_flag & UCOM_FLAG_HL_READY) {
815                 /* already opened */
816                 return (0);
817         }
818         DPRINTF("tp = %p\n", sc->sc_tty);
819
820         if (sc->sc_callback->ucom_pre_open) {
821                 /*
822                  * give the lower layer a chance to disallow TTY open, for
823                  * example if the device is not present:
824                  */
825                 error = (sc->sc_callback->ucom_pre_open) (sc);
826                 if (error) {
827                         return (error);
828                 }
829         }
830         sc->sc_flag |= UCOM_FLAG_HL_READY;
831
832         tp = sc->sc_tty;
833         lwkt_gettoken(&tp->t_token);
834
835         if (!ISSET(tp->t_state, TS_ISOPEN)) {
836                 struct termios t;
837
838                 tp->t_dev = reference_dev(sc->sc_cdev);
839
840                 t = mynor & CALLOUT_MASK ? sc->sc_it_out : sc->sc_it_in;
841
842                 tp->t_ospeed = 0;
843                 ucom_param(tp, &t);
844                 tp->t_iflag = TTYDEF_IFLAG;
845                 tp->t_oflag = TTYDEF_OFLAG;
846                 tp->t_lflag = TTYDEF_LFLAG;
847                 ttychars(tp);
848                 ttsetwater(tp);
849
850                 /* Disable transfers */
851                 sc->sc_flag &= ~UCOM_FLAG_GP_DATA;
852
853                 sc->sc_lsr = 0;
854                 sc->sc_msr = 0;
855                 sc->sc_mcr = 0;
856
857                 /* reset programmed line state */
858                 sc->sc_pls_curr = 0;
859                 sc->sc_pls_set = 0;
860                 sc->sc_pls_clr = 0;
861
862                 /* reset jitter buffer */
863                 sc->sc_jitterbuf_in = 0;
864                 sc->sc_jitterbuf_out = 0;
865
866                 ucom_queue_command(sc, ucom_cfg_open, NULL,
867                                 &sc->sc_open_task[0].hdr,
868                                 &sc->sc_open_task[1].hdr);
869
870                 /* Queue transfer enable command last */
871                 ucom_queue_command(sc, ucom_cfg_start_transfers, NULL,
872                                 &sc->sc_start_task[0].hdr, 
873                                 &sc->sc_start_task[1].hdr);
874
875                 ucom_modem(sc->sc_tty, SER_DTR | SER_RTS, 0);
876
877                 ucom_ring(sc, 0);
878
879                 ucom_break(sc, 0);
880
881                 ucom_status_change(sc);
882
883                 if (ISSET(sc->sc_msr, SER_DCD)) {
884                         (*linesw[tp->t_line].l_modem)(tp, 1);
885                 }
886         }
887
888         error = ttyopen(sc->sc_cdev, tp);
889         if (error) {
890                 lwkt_reltoken(&tp->t_token);
891                 return (error);
892         }
893
894         error = (*linesw[tp->t_line].l_open)(sc->sc_cdev, tp);
895         if (error) {
896                 lwkt_reltoken(&tp->t_token);
897                 return (error);
898         }
899
900         disc_optim(tp, &tp->t_termios, sc);
901
902         lwkt_reltoken(&tp->t_token);
903
904         return (0);
905 }
906
907 static void
908 ucom_cfg_close(struct usb_proc_msg *_task)
909 {
910         struct ucom_cfg_task *task = 
911             (struct ucom_cfg_task *)_task;
912         struct ucom_softc *sc = task->sc;
913
914         DPRINTF("\n");
915
916         if (sc->sc_flag & UCOM_FLAG_LL_READY) {
917                 sc->sc_flag &= ~UCOM_FLAG_LL_READY;
918                 if (sc->sc_callback->ucom_cfg_close)
919                         (sc->sc_callback->ucom_cfg_close) (sc);
920         } else {
921                 /* already closed */
922         }
923 }
924
925 static int
926 ucom_dev_close(struct dev_close_args *ap)
927 {
928         cdev_t dev = ap->a_head.a_dev;
929         struct ucom_softc *sc = (struct ucom_softc *)dev->si_drv1;
930         int error;
931
932         UCOM_MTX_LOCK(sc);
933         error = ucom_close(sc);
934         UCOM_MTX_UNLOCK(sc);
935
936         return error;
937 }
938
939 static int
940 ucom_close(struct ucom_softc *sc)
941 {
942         struct tty *tp = sc->sc_tty;
943         int error = 0;
944
945         DPRINTF("tp=%p\n", tp);
946
947         if (!(sc->sc_flag & UCOM_FLAG_HL_READY)) {
948                 DPRINTF("tp=%p already closed\n", tp);
949                 return (error);
950         }
951         if (!ISSET(tp->t_state, TS_ISOPEN)) {
952                 return(error);
953         }
954         ucom_shutdown(sc);
955
956         ucom_queue_command(sc, ucom_cfg_close, NULL,
957             &sc->sc_close_task[0].hdr,
958             &sc->sc_close_task[1].hdr);
959
960         sc->sc_flag &= ~(UCOM_FLAG_HL_READY | UCOM_FLAG_RTS_IFLOW);
961
962         if (sc->sc_callback->ucom_stop_read) {
963                 (sc->sc_callback->ucom_stop_read) (sc);
964         }
965
966         lwkt_gettoken(&tp->t_token);
967         (*linesw[tp->t_line].l_close)(tp, 0); /* XXX: flags */
968         disc_optim(tp, &tp->t_termios, sc);
969         ttyclose(tp);
970
971         if (tp->t_dev) {
972                 release_dev(tp->t_dev);
973                 tp->t_dev = NULL;
974         }
975         /* XXX: Detach wakeup */
976         lwkt_reltoken(&tp->t_token);
977
978         return (error);
979 }
980
981 #if 0 /* XXX */
982 static void
983 ucom_inwakeup(struct tty *tp)
984 {
985         struct ucom_softc *sc = tty_softc(tp);
986         uint16_t pos;
987
988         if (sc == NULL)
989                 return;
990
991         UCOM_MTX_ASSERT(sc, MA_OWNED);
992
993         DPRINTF("tp=%p\n", tp);
994
995         if (ttydisc_can_bypass(tp) != 0 || 
996             (sc->sc_flag & UCOM_FLAG_HL_READY) == 0 ||
997             (sc->sc_flag & UCOM_FLAG_INWAKEUP) != 0) {
998                 return;
999         }
1000
1001         /* prevent recursion */
1002         sc->sc_flag |= UCOM_FLAG_INWAKEUP;
1003
1004         pos = sc->sc_jitterbuf_out;
1005
1006         while (sc->sc_jitterbuf_in != pos) {
1007                 int c;
1008
1009                 c = (char)sc->sc_jitterbuf[pos];
1010
1011                 if (ttydisc_rint(tp, c, 0) == -1)
1012                         break;
1013                 pos++;
1014                 if (pos >= UCOM_JITTERBUF_SIZE)
1015                         pos -= UCOM_JITTERBUF_SIZE;
1016         }
1017
1018         sc->sc_jitterbuf_out = pos;
1019
1020         /* clear RTS in async fashion */
1021         if ((sc->sc_jitterbuf_in == pos) && 
1022             (sc->sc_flag & UCOM_FLAG_RTS_IFLOW))
1023                 ucom_rts(sc, 0);
1024
1025         sc->sc_flag &= ~UCOM_FLAG_INWAKEUP;
1026 }
1027 #endif
1028
1029 static int
1030 ucom_dev_read(struct dev_read_args *ap)
1031 {
1032         cdev_t dev = ap->a_head.a_dev;
1033         struct ucom_softc *sc;
1034         struct tty *tp;
1035         int error;
1036
1037         sc = 0;
1038
1039         tp = dev->si_tty;
1040         lwkt_gettoken(&tp->t_token);
1041         KKASSERT(tp!=NULL);
1042         sc = tp->t_sc;
1043         KKASSERT(sc!=NULL);
1044
1045         DPRINTF("tp = %p, flag = 0x%x\n", tp, ap->a_ioflag);
1046
1047         /* must not be locked in case it blocks */
1048         /*UCOM_MTX_LOCK(sc);*/
1049         error = (*linesw[tp->t_line].l_read)(tp, ap->a_uio, ap->a_ioflag);
1050         /*UCOM_MTX_UNLOCK(sc);*/
1051
1052         lwkt_reltoken(&tp->t_token);
1053         DPRINTF("error = %d\n", error);
1054
1055         return (error);
1056 }
1057
1058 static int
1059 ucom_dev_write(struct dev_write_args *ap)
1060 {
1061         cdev_t dev = ap->a_head.a_dev;
1062         struct ucom_softc *sc;
1063         struct tty *tp;
1064         int error;
1065
1066         tp = dev->si_tty;
1067         lwkt_gettoken(&tp->t_token);
1068         KKASSERT(tp!=NULL);
1069         sc = tp->t_sc;
1070         KKASSERT(sc!=NULL);
1071
1072         DPRINTF("tp = %p, flag = 0x%x\n", tp, ap->a_ioflag);
1073
1074         /* must not be locked in case it blocks */
1075         /*UCOM_MTX_LOCK(sc);*/
1076         error = (*linesw[tp->t_line].l_write)(tp, ap->a_uio, ap->a_ioflag);
1077         /*UCOM_MTX_UNLOCK(sc);*/
1078
1079         lwkt_reltoken(&tp->t_token);
1080         DPRINTF("ucomwrite: error = %d\n", error);
1081
1082         return (error);
1083 }
1084
1085 static int
1086 ucom_dev_ioctl(struct dev_ioctl_args *ap)
1087 {
1088         cdev_t dev = ap->a_head.a_dev;
1089         struct ucom_softc *sc = (struct ucom_softc *)dev->si_drv1;
1090         u_long cmd = ap->a_cmd;
1091         caddr_t data = ap->a_data;
1092         struct tty *tp = sc->sc_tty;
1093         int d;
1094         int error;
1095         int mynor;
1096
1097         UCOM_MTX_LOCK(sc);
1098         lwkt_gettoken(&tp->t_token);
1099
1100         mynor = minor(dev);
1101
1102         if (!(sc->sc_flag & UCOM_FLAG_HL_READY)) {
1103                 lwkt_reltoken(&tp->t_token);
1104                 UCOM_MTX_UNLOCK(sc);
1105                 return (EIO);
1106         }
1107         DPRINTF("cmd = 0x%08lx\n", cmd);
1108         if (mynor & CONTROL_MASK) {
1109                 struct termios *ct;
1110
1111                 switch (mynor & CONTROL_MASK) {
1112                 case CONTROL_INIT_STATE:
1113                         ct = mynor & CALLOUT_MASK ? &sc->sc_it_out : &sc->sc_it_in;
1114                         break;
1115                 case CONTROL_LOCK_STATE:
1116                         ct = mynor & CALLOUT_MASK ? &sc->sc_lt_out : &sc->sc_lt_in;
1117                         break;
1118                 default:
1119                         lwkt_reltoken(&tp->t_token);
1120                         UCOM_MTX_UNLOCK(sc);
1121                         return (ENODEV);        /* /dev/nodev */
1122                 }
1123                 switch (ap->a_cmd) {
1124                 case TIOCSETA:
1125                         error = priv_check_cred(ap->a_cred, PRIV_ROOT, 0);
1126                         if (error != 0) {
1127                                 lwkt_reltoken(&tp->t_token);
1128                                 UCOM_MTX_UNLOCK(sc);
1129                                 return (error);
1130                         }
1131                         *ct = *(struct termios *)data;
1132                         lwkt_reltoken(&tp->t_token);
1133                         UCOM_MTX_UNLOCK(sc);
1134                         return (0);
1135                 case TIOCGETA:
1136                         *(struct termios *)data = *ct;
1137                         lwkt_reltoken(&tp->t_token);
1138                         UCOM_MTX_UNLOCK(sc);
1139                         return (0);
1140                 case TIOCGETD:
1141                         *(int *)data = TTYDISC;
1142                         lwkt_reltoken(&tp->t_token);
1143                         UCOM_MTX_UNLOCK(sc);
1144                         return (0);
1145                 case TIOCGWINSZ:
1146                         bzero(data, sizeof(struct winsize));
1147                         lwkt_reltoken(&tp->t_token);
1148                         UCOM_MTX_UNLOCK(sc);
1149                         return (0);
1150                 default:
1151                         lwkt_reltoken(&tp->t_token);
1152                         UCOM_MTX_UNLOCK(sc);
1153                         return (ENOTTY);
1154                 }
1155         }
1156
1157         error = (*linesw[tp->t_line].l_ioctl)(tp, ap->a_cmd, ap->a_data,
1158                                               ap->a_fflag, ap->a_cred);
1159
1160         if (error != ENOIOCTL) {
1161                 DPRINTF("ucomioctl: l_ioctl: error = %d\n", error);
1162                 lwkt_reltoken(&tp->t_token);
1163                 UCOM_MTX_UNLOCK(sc);
1164                 return (error);
1165         }
1166
1167         error = ttioctl(tp, ap->a_cmd, ap->a_data, ap->a_fflag);
1168         disc_optim(tp, &tp->t_termios, sc);
1169         if (error != ENOIOCTL) {
1170                 DPRINTF("ucomioctl: ttioctl: error = %d\n", error);
1171                 lwkt_reltoken(&tp->t_token);
1172                 UCOM_MTX_UNLOCK(sc);
1173
1174                 return (error);
1175         }
1176
1177         error = 0;
1178
1179         switch (cmd) {
1180 #if 0 /* XXXDF */
1181         case TIOCSRING:
1182                 ucom_ring(sc, 1);
1183                 error = 0;
1184                 break;
1185         case TIOCCRING:
1186                 ucom_ring(sc, 0);
1187                 error = 0;
1188                 break;
1189 #endif
1190         case TIOCSBRK:
1191                 ucom_break(sc, 1);
1192                 error = 0;
1193                 break;
1194         case TIOCCBRK:
1195                 ucom_break(sc, 0);
1196                 error = 0;
1197                 break;
1198         case TIOCSDTR:
1199                 ucom_dtr(sc, 1);
1200                 break;
1201         case TIOCCDTR:
1202                 ucom_dtr(sc, 0);
1203                 break;
1204         case TIOCMSET:
1205                 d = *(int *)ap->a_data;
1206                 DPRINTF("ucomioctl: TIOCMSET, 0x%x\n", d);
1207                 ucom_modem(tp, ucom_fromtio(d), 0);
1208                 break;
1209         case TIOCMGET:
1210                 d = ucom_modem(tp, 0, 0);
1211                 DPRINTF("ucomioctl: TIOCMGET, 0x%x\n", d);
1212                 *(int *)ap->a_data = ucom_totio(d);
1213                 ucom_status_change(sc);
1214                 break;
1215         case TIOCMBIS:
1216                 d = *(int *)ap->a_data;
1217                 ucom_modem(tp, ucom_fromtio(d), 0);
1218                 break;
1219         case TIOCMBIC:
1220                 d = *(int *)ap->a_data;
1221                 ucom_modem(tp, 0, ucom_fromtio(d));
1222                 break;
1223         default:
1224                 if (sc->sc_callback->ucom_ioctl) {
1225                         error = (sc->sc_callback->ucom_ioctl)
1226                             (sc, cmd, data, 0, curthread);
1227                         if (error>=0) {
1228                                 lwkt_reltoken(&tp->t_token);
1229                                 UCOM_MTX_UNLOCK(sc);
1230
1231                                 return(error);
1232                         }
1233                 } else {
1234                         error = ENOIOCTL;
1235                 }
1236                 if (error == ENOIOCTL)
1237                         error = pps_ioctl(cmd, data, &sc->sc_pps);
1238                 break;
1239         }
1240         lwkt_reltoken(&tp->t_token);
1241         UCOM_MTX_UNLOCK(sc);
1242
1243         return (error);
1244 }
1245
1246 static int
1247 ucom_totio(int bits)
1248 {
1249         int rbits = 0;
1250
1251         SET(bits, TIOCM_LE);
1252
1253         if (ISSET(bits, SER_DTR)) {
1254                 SET(rbits, TIOCM_DTR);
1255         }
1256         if (ISSET(bits, SER_RTS)) {
1257                 SET(rbits, TIOCM_RTS);
1258         }
1259         if (ISSET(bits, SER_CTS)) {
1260                 SET(rbits, TIOCM_CTS);
1261         }
1262         if (ISSET(bits, SER_DCD)) {
1263                 SET(rbits, TIOCM_CD);
1264         }
1265         if (ISSET(bits, SER_DSR)) {
1266                 SET(rbits, TIOCM_DSR);
1267         }
1268         if (ISSET(bits, SER_RI)) {
1269                 SET(rbits, TIOCM_RI);
1270         }
1271
1272         return (rbits);
1273 }
1274
1275 static int
1276 ucom_fromtio(int bits)
1277 {
1278         int rbits = 0;
1279
1280         if (ISSET(bits, TIOCM_DTR)) {
1281                 SET(rbits, SER_DTR);
1282         }
1283         if (ISSET(bits, TIOCM_RTS)) {
1284                 SET(rbits, SER_RTS);
1285         }
1286         if (ISSET(bits, TIOCM_CTS)) {
1287                 SET(rbits, SER_CTS);
1288         }
1289         if (ISSET(bits, TIOCM_CD)) {
1290                 SET(rbits, SER_DCD);
1291         }
1292         if (ISSET(bits, TIOCM_DSR)) {
1293                 SET(rbits, SER_DSR);
1294         }
1295         if (ISSET(bits, TIOCM_RI)) {
1296                 SET(rbits, SER_RI);
1297         }
1298
1299         return (rbits);
1300 }
1301
1302 static int
1303 ucom_modem(struct tty *tp, int sigon, int sigoff)
1304 {
1305         struct ucom_softc *sc = (struct ucom_softc *)tp->t_sc;
1306         uint8_t onoff;
1307
1308         UCOM_MTX_ASSERT(sc, MA_OWNED);
1309
1310         if (!(sc->sc_flag & UCOM_FLAG_HL_READY)) {
1311                 return (0);
1312         }
1313         if ((sigon == 0) && (sigoff == 0)) {
1314
1315                 if (sc->sc_mcr & SER_DTR) {
1316                         sigon |= SER_DTR;
1317                 }
1318                 if (sc->sc_mcr & SER_RTS) {
1319                         sigon |= SER_RTS;
1320                 }
1321                 if (sc->sc_msr & SER_CTS) {
1322                         sigon |= SER_CTS;
1323                 }
1324                 if (sc->sc_msr & SER_DCD) {
1325                         sigon |= SER_DCD;
1326                 }
1327                 if (sc->sc_msr & SER_DSR) {
1328                         sigon |= SER_DSR;
1329                 }
1330                 if (sc->sc_msr & SER_RI) {
1331                         sigon |= SER_RI;
1332                 }
1333                 return (sigon);
1334         }
1335         if (sigon & SER_DTR) {
1336                 sc->sc_mcr |= SER_DTR;
1337         }
1338         if (sigoff & SER_DTR) {
1339                 sc->sc_mcr &= ~SER_DTR;
1340         }
1341         if (sigon & SER_RTS) {
1342                 sc->sc_mcr |= SER_RTS;
1343         }
1344         if (sigoff & SER_RTS) {
1345                 sc->sc_mcr &= ~SER_RTS;
1346         }
1347         onoff = (sc->sc_mcr & SER_DTR) ? 1 : 0;
1348         ucom_dtr(sc, onoff);
1349
1350         onoff = (sc->sc_mcr & SER_RTS) ? 1 : 0;
1351         ucom_rts(sc, onoff);
1352
1353         return (0);
1354 }
1355
1356 static void
1357 ucom_cfg_line_state(struct usb_proc_msg *_task)
1358 {
1359         struct ucom_cfg_task *task = 
1360             (struct ucom_cfg_task *)_task;
1361         struct ucom_softc *sc = task->sc;
1362         uint8_t notch_bits;
1363         uint8_t any_bits;
1364         uint8_t prev_value;
1365         uint8_t last_value;
1366         uint8_t mask;
1367
1368         if (!(sc->sc_flag & UCOM_FLAG_LL_READY)) {
1369                 return;
1370         }
1371
1372         mask = 0;
1373         /* compute callback mask */
1374         if (sc->sc_callback->ucom_cfg_set_dtr)
1375                 mask |= UCOM_LS_DTR;
1376         if (sc->sc_callback->ucom_cfg_set_rts)
1377                 mask |= UCOM_LS_RTS;
1378         if (sc->sc_callback->ucom_cfg_set_break)
1379                 mask |= UCOM_LS_BREAK;
1380         if (sc->sc_callback->ucom_cfg_set_ring)
1381                 mask |= UCOM_LS_RING;
1382
1383         /* compute the bits we are to program */
1384         notch_bits = (sc->sc_pls_set & sc->sc_pls_clr) & mask;
1385         any_bits = (sc->sc_pls_set | sc->sc_pls_clr) & mask;
1386         prev_value = sc->sc_pls_curr ^ notch_bits;
1387         last_value = sc->sc_pls_curr;
1388
1389         /* reset programmed line state */
1390         sc->sc_pls_curr = 0;
1391         sc->sc_pls_set = 0;
1392         sc->sc_pls_clr = 0;
1393
1394         /* ensure that we don't lose any levels */
1395         if (notch_bits & UCOM_LS_DTR)
1396                 sc->sc_callback->ucom_cfg_set_dtr(sc,
1397                     (prev_value & UCOM_LS_DTR) ? 1 : 0);
1398         if (notch_bits & UCOM_LS_RTS)
1399                 sc->sc_callback->ucom_cfg_set_rts(sc,
1400                     (prev_value & UCOM_LS_RTS) ? 1 : 0);
1401         if (notch_bits & UCOM_LS_BREAK)
1402                 sc->sc_callback->ucom_cfg_set_break(sc,
1403                     (prev_value & UCOM_LS_BREAK) ? 1 : 0);
1404         if (notch_bits & UCOM_LS_RING)
1405                 sc->sc_callback->ucom_cfg_set_ring(sc,
1406                     (prev_value & UCOM_LS_RING) ? 1 : 0);
1407
1408         /* set last value */
1409         if (any_bits & UCOM_LS_DTR)
1410                 sc->sc_callback->ucom_cfg_set_dtr(sc,
1411                     (last_value & UCOM_LS_DTR) ? 1 : 0);
1412         if (any_bits & UCOM_LS_RTS)
1413                 sc->sc_callback->ucom_cfg_set_rts(sc,
1414                     (last_value & UCOM_LS_RTS) ? 1 : 0);
1415         if (any_bits & UCOM_LS_BREAK)
1416                 sc->sc_callback->ucom_cfg_set_break(sc,
1417                     (last_value & UCOM_LS_BREAK) ? 1 : 0);
1418         if (any_bits & UCOM_LS_RING)
1419                 sc->sc_callback->ucom_cfg_set_ring(sc,
1420                     (last_value & UCOM_LS_RING) ? 1 : 0);
1421 }
1422
1423 static void
1424 ucom_line_state(struct ucom_softc *sc,
1425     uint8_t set_bits, uint8_t clear_bits)
1426 {
1427         UCOM_MTX_ASSERT(sc, MA_OWNED);
1428
1429         if (!(sc->sc_flag & UCOM_FLAG_HL_READY)) {
1430                 return;
1431         }
1432
1433         DPRINTF("on=0x%02x, off=0x%02x\n", set_bits, clear_bits);
1434
1435         /* update current programmed line state */
1436         sc->sc_pls_curr |= set_bits;
1437         sc->sc_pls_curr &= ~clear_bits;
1438         sc->sc_pls_set |= set_bits;
1439         sc->sc_pls_clr |= clear_bits;
1440
1441         /* defer driver programming */
1442         ucom_queue_command(sc, ucom_cfg_line_state, NULL,
1443             &sc->sc_line_state_task[0].hdr, 
1444             &sc->sc_line_state_task[1].hdr);
1445 }
1446
1447 static void
1448 ucom_ring(struct ucom_softc *sc, uint8_t onoff)
1449 {
1450         DPRINTF("onoff = %d\n", onoff);
1451
1452         if (onoff)
1453                 ucom_line_state(sc, UCOM_LS_RING, 0);
1454         else
1455                 ucom_line_state(sc, 0, UCOM_LS_RING);
1456 }
1457
1458 static void
1459 ucom_break(struct ucom_softc *sc, uint8_t onoff)
1460 {
1461         DPRINTF("onoff = %d\n", onoff);
1462
1463         if (onoff)
1464                 ucom_line_state(sc, UCOM_LS_BREAK, 0);
1465         else
1466                 ucom_line_state(sc, 0, UCOM_LS_BREAK);
1467 }
1468
1469 static void
1470 ucom_dtr(struct ucom_softc *sc, uint8_t onoff)
1471 {
1472         DPRINTF("onoff = %d\n", onoff);
1473
1474         if (onoff)
1475                 ucom_line_state(sc, UCOM_LS_DTR, 0);
1476         else
1477                 ucom_line_state(sc, 0, UCOM_LS_DTR);
1478 }
1479
1480 static void
1481 ucom_rts(struct ucom_softc *sc, uint8_t onoff)
1482 {
1483         DPRINTF("onoff = %d\n", onoff);
1484
1485         if (onoff)
1486                 ucom_line_state(sc, UCOM_LS_RTS, 0);
1487         else
1488                 ucom_line_state(sc, 0, UCOM_LS_RTS);
1489 }
1490
1491 static void
1492 ucom_cfg_status_change(struct usb_proc_msg *_task)
1493 {
1494         struct ucom_cfg_task *task = 
1495             (struct ucom_cfg_task *)_task;
1496         struct ucom_softc *sc = task->sc;
1497         struct tty *tp;
1498         uint8_t new_msr;
1499         uint8_t new_lsr;
1500         uint8_t msr_delta;
1501         uint8_t lsr_delta;
1502
1503         tp = sc->sc_tty;
1504
1505         UCOM_MTX_ASSERT(sc, MA_OWNED);
1506
1507         if (!(sc->sc_flag & UCOM_FLAG_LL_READY)) {
1508                 return;
1509         }
1510         if (sc->sc_callback->ucom_cfg_get_status == NULL) {
1511                 return;
1512         }
1513         /* get status */
1514
1515         new_msr = 0;
1516         new_lsr = 0;
1517
1518         (sc->sc_callback->ucom_cfg_get_status) (sc, &new_lsr, &new_msr);
1519
1520         if (!(sc->sc_flag & UCOM_FLAG_HL_READY)) {
1521                 /* TTY device closed */
1522                 return;
1523         }
1524         msr_delta = (sc->sc_msr ^ new_msr);
1525         lsr_delta = (sc->sc_lsr ^ new_lsr);
1526
1527         sc->sc_msr = new_msr;
1528         sc->sc_lsr = new_lsr;
1529
1530 #if 0   /* missing pps_capture */
1531         /*
1532          * Time pulse counting support. Note that both CTS and DCD are
1533          * active-low signals. The status bit is high to indicate that
1534          * the signal on the line is low, which corresponds to a PPS
1535          * clear event.
1536          */
1537         switch(ucom_pps_mode) {
1538         case 1:
1539                 if ((sc->sc_pps.ppsparam.mode & PPS_CAPTUREBOTH) &&
1540                     (msr_delta & SER_CTS)) {
1541                         pps_capture(&sc->sc_pps);
1542                         pps_event(&sc->sc_pps, (sc->sc_msr & SER_CTS) ?
1543                             PPS_CAPTURECLEAR : PPS_CAPTUREASSERT);
1544                 }
1545                 break;
1546         case 2:
1547                 if ((sc->sc_pps.ppsparam.mode & PPS_CAPTUREBOTH) &&
1548                     (msr_delta & SER_DCD)) {
1549                         pps_capture(&sc->sc_pps);
1550                         pps_event(&sc->sc_pps, (sc->sc_msr & SER_DCD) ?
1551                             PPS_CAPTURECLEAR : PPS_CAPTUREASSERT);
1552                 }
1553                 break;
1554         default:
1555                 break;
1556         }
1557 #endif
1558
1559         if (msr_delta & SER_DCD) {
1560
1561                 int onoff = (sc->sc_msr & SER_DCD) ? 1 : 0;
1562
1563                 DPRINTF("DCD changed to %d\n", onoff);
1564
1565                 (*linesw[tp->t_line].l_modem)(tp, onoff);
1566         }
1567
1568         if ((lsr_delta & ULSR_BI) && (sc->sc_lsr & ULSR_BI)) {
1569
1570                 DPRINTF("BREAK detected\n");
1571                 (*linesw[tp->t_line].l_rint)(0, tp);
1572
1573                 /*
1574                 ttydisc_rint(tp, 0, TRE_BREAK);
1575                 ttydisc_rint_done(tp);
1576                 */
1577         }
1578
1579         if ((lsr_delta & ULSR_FE) && (sc->sc_lsr & ULSR_FE)) {
1580
1581                 DPRINTF("Frame error detected\n");
1582                 (*linesw[tp->t_line].l_rint)(0, tp);
1583
1584                 /*
1585                 ttydisc_rint(tp, 0, TRE_FRAMING);
1586                 ttydisc_rint_done(tp);
1587                 */
1588         }
1589
1590         if ((lsr_delta & ULSR_PE) && (sc->sc_lsr & ULSR_PE)) {
1591
1592                 DPRINTF("Parity error detected\n");
1593                 (*linesw[tp->t_line].l_rint)(0, tp);
1594                 /*
1595                 ttydisc_rint(tp, 0, TRE_PARITY);
1596                 ttydisc_rint_done(tp);
1597                 */
1598         }
1599 }
1600
1601 void
1602 ucom_status_change(struct ucom_softc *sc)
1603 {
1604         UCOM_MTX_ASSERT(sc, MA_OWNED);
1605
1606         if (sc->sc_flag & UCOM_FLAG_CONSOLE)
1607                 return;         /* not supported */
1608
1609         if (!(sc->sc_flag & UCOM_FLAG_HL_READY)) {
1610                 return;
1611         }
1612         DPRINTF("\n");
1613
1614         ucom_queue_command(sc, ucom_cfg_status_change, NULL,
1615             &sc->sc_status_task[0].hdr,
1616             &sc->sc_status_task[1].hdr);
1617 }
1618
1619 static void
1620 ucom_cfg_param(struct usb_proc_msg *_task)
1621 {
1622         struct ucom_param_task *task = 
1623             (struct ucom_param_task *)_task;
1624         struct ucom_softc *sc = task->sc;
1625
1626         if (!(sc->sc_flag & UCOM_FLAG_LL_READY)) {
1627                 return;
1628         }
1629         if (sc->sc_callback->ucom_cfg_param == NULL) {
1630                 return;
1631         }
1632
1633         (sc->sc_callback->ucom_cfg_param) (sc, &task->termios_copy);
1634
1635         /* wait a little */
1636         usb_pause_mtx(sc->sc_lock, hz / 10);
1637 }
1638
1639 static int
1640 ucom_param(struct tty *tp, struct termios *t)
1641 {
1642         struct ucom_softc *sc = (struct ucom_softc *)tp->t_sc;
1643         uint8_t opened;
1644         int error;
1645
1646         lwkt_gettoken(&tp->t_token);
1647         UCOM_MTX_ASSERT(sc, MA_OWNED);
1648
1649         opened = 0;
1650         error = 0;
1651
1652         if (!(sc->sc_flag & UCOM_FLAG_HL_READY)) {
1653
1654                 /* XXX the TTY layer should call "open()" first! */
1655                 /*
1656                  * Not quite: Its ordering is partly backwards, but
1657                  * some parameters must be set early in ttydev_open(),
1658                  * possibly before calling ttydevsw_open().
1659                  */
1660                 error = ucom_open(sc);
1661
1662                 if (error) {
1663                         goto done;
1664                 }
1665                 opened = 1;
1666         }
1667         DPRINTF("sc = %p\n", sc);
1668
1669         /* Check requested parameters. */
1670         if (t->c_ispeed && (t->c_ispeed != t->c_ospeed)) {
1671                 /* XXX c_ospeed == 0 is perfectly valid. */
1672                 DPRINTF("mismatch ispeed and ospeed\n");
1673                 error = EINVAL;
1674                 goto done;
1675         }
1676         t->c_ispeed = t->c_ospeed;
1677
1678         if (sc->sc_callback->ucom_pre_param) {
1679                 /* Let the lower layer verify the parameters */
1680                 error = (sc->sc_callback->ucom_pre_param) (sc, t);
1681                 if (error) {
1682                         DPRINTF("callback error = %d\n", error);
1683                         goto done;
1684                 }
1685         }
1686
1687         /* Disable transfers */
1688         sc->sc_flag &= ~UCOM_FLAG_GP_DATA;
1689
1690         /* Queue baud rate programming command first */
1691         ucom_queue_command(sc, ucom_cfg_param, t,
1692             &sc->sc_param_task[0].hdr,
1693             &sc->sc_param_task[1].hdr);
1694
1695         /* Queue transfer enable command last */
1696         ucom_queue_command(sc, ucom_cfg_start_transfers, NULL,
1697             &sc->sc_start_task[0].hdr, 
1698             &sc->sc_start_task[1].hdr);
1699
1700         if (t->c_cflag & CRTS_IFLOW) {
1701                 sc->sc_flag |= UCOM_FLAG_RTS_IFLOW;
1702         } else if (sc->sc_flag & UCOM_FLAG_RTS_IFLOW) {
1703                 sc->sc_flag &= ~UCOM_FLAG_RTS_IFLOW;
1704                 ucom_modem(tp, SER_RTS, 0);
1705         }
1706 done:
1707         if (error) {
1708                 if (opened) {
1709                         ucom_close(sc);
1710                 }
1711         }
1712         lwkt_reltoken(&tp->t_token);
1713
1714         return (error);
1715 }
1716
1717 static void
1718 ucom_start(struct tty *tp)
1719 {
1720         struct ucom_softc *sc = (struct ucom_softc *)tp->t_sc;
1721         int didlock;
1722
1723         /* may be called locked or unlocked */
1724         if (lockowned(sc->sc_lock)) {
1725                 didlock = 0;
1726         } else {
1727                 UCOM_MTX_LOCK(sc);
1728                 didlock = 1;
1729         }
1730         /* UCOM_MTX_ASSERT(sc, MA_OWNED); */
1731
1732         DPRINTF("sc = %p\n", sc);
1733
1734         if (!(sc->sc_flag & UCOM_FLAG_HL_READY)) {
1735                 /* The higher layer is not ready */
1736                 if (didlock)
1737                         UCOM_MTX_UNLOCK(sc);
1738                 return;
1739         }
1740
1741         lwkt_gettoken(&tp->t_token);
1742
1743         if (tp->t_state & TS_TBLOCK) {
1744                 if (ISSET(sc->sc_mcr, SER_RTS) &&
1745                     ISSET(sc->sc_flag, UCOM_FLAG_RTS_IFLOW)) {
1746                         DPRINTF("ucom_start: clear RTS\n");
1747                         (void)ucom_modem(tp, 0, SER_RTS);
1748                 }
1749         } else {
1750                 if (!ISSET(sc->sc_mcr, SER_RTS) &&
1751                     tp->t_rawq.c_cc <= tp->t_ilowat &&
1752                     ISSET(sc->sc_flag, UCOM_FLAG_RTS_IFLOW)) {
1753                         DPRINTF("ucom_start: set RTS\n");
1754                         (void)ucom_modem(tp, SER_RTS, 0);
1755                 }
1756         }
1757
1758         if (ISSET(tp->t_state, TS_BUSY | TS_TIMEOUT | TS_TTSTOP)) {
1759                 ttwwakeup(tp);
1760                 DPRINTF("ucom_start: stopped\n");
1761                 goto out;
1762         }
1763
1764         if (tp->t_outq.c_cc <= tp->t_olowat) {
1765                 if (ISSET(tp->t_state, TS_SO_OLOWAT)) {
1766                         CLR(tp->t_state, TS_SO_OLOWAT);
1767                         wakeup(TSA_OLOWAT(tp));
1768                 }
1769                 KNOTE(&tp->t_wkq.ki_note, 0);
1770                 if (tp->t_outq.c_cc == 0) {
1771                         if (ISSET(tp->t_state, TS_BUSY | TS_SO_OCOMPLETE) ==
1772                                         TS_SO_OCOMPLETE && tp->t_outq.c_cc == 0) {
1773                                 CLR(tp->t_state, TS_SO_OCOMPLETE);
1774                                 wakeup(TSA_OCOMPLETE(tp));
1775                         }
1776                         goto out;
1777                 }
1778         }
1779
1780         DPRINTF("about to start write?\n");
1781         ucom_start_transfers(sc);
1782
1783         ttwwakeup(tp);
1784
1785 out:
1786         lwkt_reltoken(&tp->t_token);
1787         if (didlock)
1788                 UCOM_MTX_UNLOCK(sc);
1789 }
1790
1791 static void
1792 ucom_stop(struct tty *tp, int flag)
1793 {
1794         struct ucom_softc *sc = (struct ucom_softc *)tp->t_sc;
1795
1796         DPRINTF("sc = %p, x = 0x%x\n", sc, flag);
1797
1798         lwkt_gettoken(&tp->t_token);
1799         if (flag & FREAD) {
1800                 /*   
1801                  * This is just supposed to flush pending receive data,
1802                  * not stop the reception of data entirely!
1803                  */
1804                 DPRINTF("read\n");
1805                 if (sc->sc_callback->ucom_stop_read) {
1806                         (sc->sc_callback->ucom_stop_read) (sc);
1807                 }
1808                 if (sc->sc_callback->ucom_start_read) {
1809                         (sc->sc_callback->ucom_start_read) (sc);
1810                 }
1811 #if 0
1812                 ucomstopread(sc);
1813                 ucomstartread(sc);
1814 #endif
1815         }
1816
1817         if (flag & FWRITE) {
1818                 DPRINTF("write\n");
1819                 if (ISSET(tp->t_state, TS_BUSY)) {
1820                         /* XXX do what? */
1821                         if (!ISSET(tp->t_state, TS_TTSTOP))
1822                                 SET(tp->t_state, TS_FLUSH);
1823                 }
1824         }
1825
1826         DPRINTF("done\n");
1827         lwkt_reltoken(&tp->t_token);
1828 }
1829
1830 /*------------------------------------------------------------------------*
1831  *      ucom_get_data
1832  * Input values:
1833  * len: maximum length of data to get
1834  * 
1835  * Get data from the TTY layer
1836  *
1837  * Return values:
1838  * 0: No data is available.
1839  * Else: Data is available.
1840  *------------------------------------------------------------------------*/
1841
1842 /* Copy data from the tty layer to usb */
1843 uint8_t
1844 ucom_get_data(struct ucom_softc *sc, struct usb_page_cache *pc,
1845     uint32_t offset, uint32_t len, uint32_t *actlen)
1846 {
1847         struct usb_page_search res;
1848         struct tty *tp = sc->sc_tty;
1849         uint32_t cnt;
1850         uint32_t offset_orig;
1851
1852         DPRINTF("\n");
1853
1854         UCOM_MTX_ASSERT(sc, MA_OWNED);
1855
1856         if (sc->sc_flag & UCOM_FLAG_CONSOLE) {
1857                 unsigned int temp;
1858
1859                 /* get total TX length */
1860
1861                 temp = ucom_cons_tx_high - ucom_cons_tx_low;
1862                 temp %= UCOM_CONS_BUFSIZE;
1863
1864                 /* limit TX length */
1865
1866                 if (temp > (UCOM_CONS_BUFSIZE - ucom_cons_tx_low))
1867                         temp = (UCOM_CONS_BUFSIZE - ucom_cons_tx_low);
1868
1869                 if (temp > len)
1870                         temp = len;
1871
1872                 /* copy in data */
1873
1874                 usbd_copy_in(pc, offset, ucom_cons_tx_buf + ucom_cons_tx_low, temp);
1875
1876                 /* update counters */
1877
1878                 ucom_cons_tx_low += temp;
1879                 ucom_cons_tx_low %= UCOM_CONS_BUFSIZE;
1880
1881                 /* store actual length */
1882
1883                 *actlen = temp;
1884
1885                 return (temp ? 1 : 0);
1886         }
1887
1888         if (tty_gone(tp) ||
1889             !(sc->sc_flag & UCOM_FLAG_GP_DATA)) {
1890                 actlen[0] = 0;
1891                 return (0);             /* multiport device polling */
1892         }
1893
1894         offset_orig = offset;
1895
1896         lwkt_gettoken(&tp->t_token);
1897         while (len != 0) {
1898                 usbd_get_page(pc, offset, &res);
1899
1900                 /* Buffer bigger than max requested data */
1901                 if (res.length > len) {
1902                         res.length = len;
1903                 }
1904                 /* copy data directly into USB buffer */
1905                 SET(tp->t_state, TS_BUSY);
1906                 cnt = q_to_b(&tp->t_outq, res.buffer, len);
1907                 if (cnt == 0) {
1908                         DPRINTF("ucom_get_data: cnt == 0\n");
1909                         CLR(tp->t_state, TS_BUSY);
1910                         break;
1911                 }
1912
1913                 CLR(tp->t_state, TS_BUSY);
1914
1915                 /* XXX mp: This breaks avrdude,
1916                            does the flush need to happen
1917                            elsewhere?
1918                 if (ISSET(tp->t_state, TS_FLUSH))
1919                         CLR(tp->t_state, TS_FLUSH);
1920                 else
1921                         ndflush(&tp->t_outq,cnt);
1922                 */
1923
1924                 offset += cnt;
1925                 len -= cnt;
1926
1927                 if (cnt < res.length) {
1928                         /* end of buffer */
1929                         break;
1930                 }
1931         }
1932         lwkt_reltoken(&tp->t_token);
1933
1934         actlen[0] = offset - offset_orig;
1935
1936         DPRINTF("cnt=%d\n", actlen[0]);
1937
1938         if (actlen[0] == 0) {
1939                 return (0);
1940         }
1941         return (1);
1942 }
1943
1944 /*
1945  * Write data to the tty layer
1946  */
1947
1948 void
1949 ucom_put_data(struct ucom_softc *sc, struct usb_page_cache *pc,
1950     uint32_t offset, uint32_t len)
1951 {
1952         struct usb_page_search res;
1953         struct tty *tp = sc->sc_tty;
1954         char *buf;
1955         uint32_t cnt;
1956         int lostcc;
1957
1958         DPRINTF("\n");
1959
1960         UCOM_MTX_ASSERT(sc, MA_OWNED);
1961         lwkt_gettoken(&tp->t_token);
1962
1963         if (sc->sc_flag & UCOM_FLAG_CONSOLE) {
1964                 unsigned int temp;
1965
1966                 /* get maximum RX length */
1967
1968                 temp = (UCOM_CONS_BUFSIZE - 1) - ucom_cons_rx_high + ucom_cons_rx_low;
1969                 temp %= UCOM_CONS_BUFSIZE;
1970
1971                 /* limit RX length */
1972
1973                 if (temp > (UCOM_CONS_BUFSIZE - ucom_cons_rx_high))
1974                         temp = (UCOM_CONS_BUFSIZE - ucom_cons_rx_high);
1975
1976                 if (temp > len)
1977                         temp = len;
1978
1979                 /* copy out data */
1980
1981                 usbd_copy_out(pc, offset, ucom_cons_rx_buf + ucom_cons_rx_high, temp);
1982
1983                 /* update counters */
1984
1985                 ucom_cons_rx_high += temp;
1986                 ucom_cons_rx_high %= UCOM_CONS_BUFSIZE;
1987
1988                 lwkt_reltoken(&tp->t_token);
1989                 return;
1990         }
1991
1992         if (tty_gone(tp)) {
1993                 lwkt_reltoken(&tp->t_token);
1994                 return;                 /* multiport device polling */
1995         }
1996         if (len == 0) {
1997                 lwkt_reltoken(&tp->t_token);
1998                 return;                 /* no data */
1999         }
2000
2001         /* set a flag to prevent recursation ? */
2002
2003         while (len > 0) {
2004                 usbd_get_page(pc, offset, &res);
2005
2006                 if (res.length > len) {
2007                         res.length = len;
2008                 }
2009                 len -= res.length;
2010                 offset += res.length;
2011
2012                 /* pass characters to tty layer */
2013
2014                 buf = res.buffer;
2015                 cnt = res.length;
2016
2017                 /* first check if we can pass the buffer directly */
2018
2019                 if (tp->t_state & TS_CAN_BYPASS_L_RINT) {
2020                         /* clear any jitter buffer */
2021                         sc->sc_jitterbuf_in = 0;
2022                         sc->sc_jitterbuf_out = 0;
2023
2024                         if (tp->t_rawq.c_cc + cnt > tp->t_ihiwat
2025                             && (sc->sc_flag & UCOM_FLAG_RTS_IFLOW
2026                                 || tp->t_iflag & IXOFF)
2027                             && !(tp->t_state & TS_TBLOCK))
2028                                ttyblock(tp);
2029                         lostcc = b_to_q((char *)buf, cnt, &tp->t_rawq);
2030                         tp->t_rawcc += cnt;
2031                         if (sc->hotchar) {
2032                                 while (cnt) {
2033                                         if (*buf == sc->hotchar)
2034                                                 break;
2035                                         --cnt;
2036                                         ++buf;
2037                                 }
2038                                 if (cnt) 
2039                                         setsofttty();
2040                         }
2041                         ttwakeup(tp);
2042                         if (tp->t_state & TS_TTSTOP
2043                             && (tp->t_iflag & IXANY
2044                                 || tp->t_cc[VSTART] == tp->t_cc[VSTOP])) {
2045                                 tp->t_state &= ~TS_TTSTOP;
2046                                 tp->t_lflag &= ~FLUSHO;
2047                                 ucom_start(tp);
2048                         }
2049                         if (lostcc > 0)
2050                                 kprintf("lost %d chars\n", lostcc);
2051
2052                         /*
2053                         if (ttydisc_rint_bypass(tp, buf, cnt) != cnt) {
2054                                 DPRINTF("tp=%p, data lost\n", tp);
2055                         }
2056                         */
2057                         continue;
2058                 } else {
2059                 /* need to loop */
2060                         for (cnt = 0; cnt != res.length; cnt++) {
2061                                 if (sc->sc_jitterbuf_in != sc->sc_jitterbuf_out ||
2062                                     (*linesw[tp->t_line].l_rint)((unsigned char)buf[cnt], tp) == -1) {
2063                                         uint16_t end;
2064                                         uint16_t pos;
2065
2066                                         pos = sc->sc_jitterbuf_in;
2067                                         end = sc->sc_jitterbuf_out +
2068                                             UCOM_JITTERBUF_SIZE - 1;
2069
2070                                         if (end >= UCOM_JITTERBUF_SIZE)
2071                                                 end -= UCOM_JITTERBUF_SIZE;
2072
2073                                         for (; cnt != res.length; cnt++) {
2074                                                 if (pos == end)
2075                                                         break;
2076                                                 sc->sc_jitterbuf[pos] = buf[cnt];
2077                                                 pos++;
2078                                                 if (pos >= UCOM_JITTERBUF_SIZE)
2079                                                         pos -= UCOM_JITTERBUF_SIZE;
2080                                         }
2081
2082                                         sc->sc_jitterbuf_in = pos;
2083
2084                                         /* set RTS in async fashion */
2085                                         if (sc->sc_flag & UCOM_FLAG_RTS_IFLOW)
2086                                                 ucom_rts(sc, 1);
2087
2088                                         DPRINTF("tp=%p, lost %d "
2089                                             "chars\n", tp, res.length - cnt);
2090                                         break;
2091                                 }
2092                         }
2093                 }
2094         }
2095         lwkt_reltoken(&tp->t_token);
2096         /*
2097         ttydisc_rint_done(tp);
2098         */
2099 }
2100
2101 #if 0 /* XXX */
2102 static void
2103 ucom_free(void *xsc)
2104 {
2105         struct ucom_softc *sc = xsc;
2106
2107         if (sc->sc_callback->ucom_free != NULL)
2108                 sc->sc_callback->ucom_free(sc);
2109         else
2110                 /*ucom_unref(sc->sc_super) XXX hack, see end of ucom_detach_tty() */;
2111
2112         lockmgr(&ucom_lock, LK_EXCLUSIVE);
2113         ucom_close_refs--;
2114         lockmgr(&ucom_lock, LK_RELEASE);
2115 }
2116
2117 static cn_probe_t ucom_cnprobe;
2118 static cn_init_t ucom_cninit;
2119 static cn_term_t ucom_cnterm;
2120 static cn_getc_t ucom_cngetc;
2121 static cn_putc_t ucom_cnputc;
2122
2123 /*
2124 static cn_grab_t ucom_cngrab;
2125 static cn_ungrab_t ucom_cnungrab;
2126 CONSOLE_DRIVER(ucom);
2127 */
2128
2129 static void
2130 ucom_cnprobe(struct consdev  *cp)
2131 {
2132         if (ucom_cons_unit != -1)
2133                 cp->cn_pri = CN_NORMAL;
2134         else
2135                 cp->cn_pri = CN_DEAD;
2136
2137         /*
2138         strlcpy(cp->cn_name, "ucom", sizeof(cp->cn_name));
2139         */
2140 }
2141
2142 static void
2143 ucom_cninit(struct consdev  *cp)
2144 {
2145 }
2146
2147 static void
2148 ucom_cnterm(struct consdev  *cp)
2149 {
2150 }
2151
2152 static void
2153 ucom_cngrab(struct consdev *cp)
2154 {
2155 }
2156
2157 static void
2158 ucom_cnungrab(struct consdev *cp)
2159 {
2160 }
2161
2162 static int
2163 ucom_cngetc(struct consdev *cd)
2164 {
2165         struct ucom_softc *sc = ucom_cons_softc;
2166         int c;
2167
2168         if (sc == NULL)
2169                 return (-1);
2170
2171         UCOM_MTX_LOCK(sc);
2172
2173         if (ucom_cons_rx_low != ucom_cons_rx_high) {
2174                 c = ucom_cons_rx_buf[ucom_cons_rx_low];
2175                 ucom_cons_rx_low ++;
2176                 ucom_cons_rx_low %= UCOM_CONS_BUFSIZE;
2177         } else {
2178                 c = -1;
2179         }
2180
2181         /* start USB transfers */
2182         ucom_outwakeup(sc->sc_tty);
2183
2184         UCOM_MTX_UNLOCK(sc);
2185
2186         /* poll if necessary */
2187         /*
2188         if (kdb_active && sc->sc_callback->ucom_poll)
2189                 (sc->sc_callback->ucom_poll) (sc);
2190         */
2191         return (c);
2192 }
2193
2194 static void
2195 ucom_cnputc(void *cd, int c)
2196         /*
2197 ucom_cnputc(struct consdev *cd, int c)
2198         */
2199
2200 {
2201         struct ucom_softc *sc = ucom_cons_softc;
2202         unsigned int temp;
2203
2204         if (sc == NULL)
2205                 return;
2206
2207  repeat:
2208
2209         UCOM_MTX_LOCK(sc);
2210
2211         /* compute maximum TX length */
2212
2213         temp = (UCOM_CONS_BUFSIZE - 1) - ucom_cons_tx_high + ucom_cons_tx_low;
2214         temp %= UCOM_CONS_BUFSIZE;
2215
2216         if (temp) {
2217                 ucom_cons_tx_buf[ucom_cons_tx_high] = c;
2218                 ucom_cons_tx_high ++;
2219                 ucom_cons_tx_high %= UCOM_CONS_BUFSIZE;
2220         }
2221
2222         /* start USB transfers */
2223         ucom_outwakeup(sc->sc_tty);
2224
2225         UCOM_MTX_UNLOCK(sc);
2226
2227         /* poll if necessary */
2228 #if 0 /* XXX */
2229         if (kdb_active && sc->sc_callback->ucom_poll) {
2230                 (sc->sc_callback->ucom_poll) (sc);
2231                 /* simple flow control */
2232                 if (temp == 0)
2233                         goto repeat;
2234         }
2235 #endif
2236 }
2237 #endif
2238 /*------------------------------------------------------------------------*
2239  *      ucom_ref
2240  *
2241  * This function will increment the super UCOM reference count.
2242  *------------------------------------------------------------------------*/
2243 void
2244 ucom_ref(struct ucom_super_softc *ssc)
2245 {
2246         lockmgr(&ucom_lock, LK_EXCLUSIVE);
2247         ssc->sc_refs++;
2248         lockmgr(&ucom_lock, LK_RELEASE);
2249 }
2250
2251 /*------------------------------------------------------------------------*
2252  *      ucom_free_unit
2253  *
2254  * This function will free the super UCOM's allocated unit
2255  * number. This function can be called on a zero-initialized
2256  * structure. This function can be called multiple times.
2257  *------------------------------------------------------------------------*/
2258 static void
2259 ucom_free_unit(struct ucom_super_softc *ssc)
2260 {
2261         if (!(ssc->sc_flag & UCOM_FLAG_FREE_UNIT))
2262                 return;
2263
2264         ucom_unit_free(ssc->sc_unit);
2265
2266         ssc->sc_flag &= ~UCOM_FLAG_FREE_UNIT;
2267 }
2268
2269 /*------------------------------------------------------------------------*
2270  *      ucom_unref
2271  *
2272  * This function will decrement the super UCOM reference count.
2273  *
2274  * Return values:
2275  * 0: UCOM structures are still referenced.
2276  * Else: UCOM structures are no longer referenced.
2277  *------------------------------------------------------------------------*/
2278 int
2279 ucom_unref(struct ucom_super_softc *ssc)
2280 {
2281         int retval;
2282
2283         lockmgr(&ucom_lock, LK_EXCLUSIVE);
2284         retval = (ssc->sc_refs < 2);
2285         ssc->sc_refs--;
2286         lockmgr(&ucom_lock, LK_RELEASE);
2287
2288         if (retval)
2289                 ucom_free_unit(ssc);
2290
2291         return (retval);
2292 }
2293
2294 /*
2295  * NOTE: Must be called with tp->t_token held.
2296  */
2297 static void
2298 disc_optim(struct tty *tp, struct termios *t, struct ucom_softc *sc)
2299 {
2300         ASSERT_LWKT_TOKEN_HELD(&tp->t_token);
2301         if (!(t->c_iflag & (ICRNL | IGNCR | IMAXBEL | INLCR | ISTRIP | IXON))
2302             && (!(t->c_iflag & BRKINT) || (t->c_iflag & IGNBRK))
2303             && (!(t->c_iflag & PARMRK)
2304                 || (t->c_iflag & (IGNPAR | IGNBRK)) == (IGNPAR | IGNBRK))
2305             && !(t->c_lflag & (ECHO | ICANON | IEXTEN | ISIG | PENDIN))
2306             && linesw[tp->t_line].l_rint == ttyinput) {
2307                 DPRINTF("disc_optim: bypass l_rint\n");
2308                 tp->t_state |= TS_CAN_BYPASS_L_RINT;
2309         } else {
2310                 DPRINTF("disc_optim: can't bypass l_rint\n");
2311                 tp->t_state &= ~TS_CAN_BYPASS_L_RINT;
2312         }
2313         sc->hotchar = linesw[tp->t_line].l_hotchar;
2314 }
2315
2316 #if defined(GDB)
2317
2318 #include <gdb/gdb.h>
2319
2320 static gdb_probe_f ucom_gdbprobe;
2321 static gdb_init_f ucom_gdbinit;
2322 static gdb_term_f ucom_gdbterm;
2323 static gdb_getc_f ucom_gdbgetc;
2324 static gdb_putc_f ucom_gdbputc;
2325
2326 GDB_DBGPORT(sio, ucom_gdbprobe, ucom_gdbinit, ucom_gdbterm, ucom_gdbgetc, ucom_gdbputc);
2327
2328 static int
2329 ucom_gdbprobe(void)
2330 {
2331         return ((ucom_cons_softc != NULL) ? 0 : -1);
2332 }
2333
2334 static void
2335 ucom_gdbinit(void)
2336 {
2337 }
2338
2339 static void
2340 ucom_gdbterm(void)
2341 {
2342 }
2343
2344 static void
2345 ucom_gdbputc(int c)
2346 {
2347         ucom_cnputc(NULL, c);
2348 }
2349
2350 static int
2351 ucom_gdbgetc(void)
2352 {
2353         return (ucom_cngetc(NULL));
2354 }
2355
2356 #endif