Home | History | Annotate | Line # | Download | only in usb
ustir.c revision 1.17.10.4
      1 /*	$NetBSD: ustir.c,v 1.17.10.4 2007/06/18 14:16:44 itohy Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2001 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by David Sainty <David.Sainty (at) dtsp.co.nz>
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *        This product includes software developed by the NetBSD
     21  *        Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 __KERNEL_RCSID(0, "$NetBSD: ustir.c,v 1.17.10.4 2007/06/18 14:16:44 itohy Exp $");
     41 
     42 #include <sys/param.h>
     43 #include <sys/systm.h>
     44 #include <sys/kernel.h>
     45 #include <sys/device.h>
     46 #include <sys/malloc.h>
     47 #include <sys/conf.h>
     48 #include <sys/file.h>
     49 #include <sys/poll.h>
     50 #include <sys/select.h>
     51 #include <sys/proc.h>
     52 #include <sys/kthread.h>
     53 
     54 #ifdef USTIR_DEBUG_IOCTLS
     55 #include <sys/ioctl.h>
     56 #include <dev/usb/ustir.h>
     57 #endif
     58 
     59 #include <dev/usb/usb.h>
     60 #include <dev/usb/usbdevs.h>
     61 #include <dev/usb/usbdi.h>
     62 #include <dev/usb/usbdi_util.h>
     63 #include <dev/usb/ustirreg.h>
     64 
     65 #include <dev/ir/ir.h>
     66 #include <dev/ir/irdaio.h>
     67 #include <dev/ir/irframevar.h>
     68 #include <dev/ir/sir.h>
     69 
     70 #ifdef USTIR_DEBUG
     71 #define DPRINTFN(n,x)	if (ustirdebug>(n)) logprintf x
     72 int	ustirdebug = 0;
     73 #else
     74 #define DPRINTFN(n,x)
     75 #endif
     76 
     77 /* Max size with framing. */
     78 #define MAX_USTIR_OUTPUT_FRAME (2*IRDA_MAX_FRAME_SIZE + IRDA_MAX_EBOFS + STIR_OUTPUT_HEADER_SIZE + 4)
     79 
     80 #define USTIR_NSPEEDS 9
     81 struct ustir_speedrec {
     82 	unsigned int speed;
     83 	unsigned int config;
     84 };
     85 
     86 Static struct ustir_speedrec const ustir_speeds[USTIR_NSPEEDS] = {
     87 	{ 4000000, STIR_BRMODE_4000000 },
     88 	{ 1152000, STIR_BRMODE_1152000 },
     89 	{ 576000, STIR_BRMODE_576000 },
     90 	{ 115200, STIR_BRMODE_115200 },
     91 	{ 57600, STIR_BRMODE_57600 },
     92 	{ 38400, STIR_BRMODE_38400 },
     93 	{ 19200, STIR_BRMODE_19200 },
     94 	{ 9600, STIR_BRMODE_9600 },
     95 	{ 2400, STIR_BRMODE_2400 }
     96 };
     97 
     98 struct framedefn {
     99 	unsigned int bof_count;
    100 	u_int8_t bof_byte;
    101 
    102 	u_int8_t esc_byte;
    103 	u_int8_t esc_xor;
    104 
    105 	unsigned int eof_count;
    106 	u_int8_t eof_byte;
    107 
    108 	unsigned int fcs_count;
    109 	u_int32_t fcs_init;
    110 	u_int32_t fcs_correct;
    111 
    112 	u_int32_t (*fcs_calc)(u_int32_t, u_int8_t const*, size_t);
    113 };
    114 
    115 Static u_int32_t crc_ccitt_16(u_int32_t, u_int8_t const*, size_t);
    116 
    117 struct framedefn const framedef_sir = {
    118 	1, 0xc0,
    119 	0x7d, 0x20,
    120 	1, 0xc1,
    121 	2, INITFCS, GOODFCS,
    122 	crc_ccitt_16
    123 };
    124 
    125 enum framefsmstate {
    126 	FSTATE_END_OF_FRAME,
    127 	FSTATE_START_OF_FRAME,
    128 	FSTATE_IN_DATA,
    129 	FSTATE_IN_END
    130 };
    131 
    132 enum frameresult {
    133 	FR_IDLE,
    134 	FR_INPROGRESS,
    135 	FR_FRAMEOK,
    136 	FR_FRAMEBADFCS,
    137 	FR_FRAMEMALFORMED,
    138 	FR_BUFFEROVERRUN
    139 };
    140 
    141 struct framestate {
    142 	struct framedefn const *definition;
    143 
    144 	u_int8_t *buffer;
    145 	size_t buflen;
    146 	size_t bufindex;
    147 
    148 	enum framefsmstate fsmstate;
    149 	u_int escaped;
    150 	u_int state_index;
    151 };
    152 
    153 #define deframe_isclear(fs) ((fs)->fsmstate == FSTATE_END_OF_FRAME)
    154 
    155 Static void deframe_clear(struct framestate *);
    156 Static void deframe_init(struct framestate *, struct framedefn const *,
    157 			 u_int8_t *, size_t);
    158 Static enum frameresult deframe_process(struct framestate *, u_int8_t const **,
    159 					size_t *);
    160 
    161 struct ustir_softc {
    162 	USBBASEDEVICE		sc_dev;
    163 	usbd_device_handle	sc_udev;
    164 	usbd_interface_handle	sc_iface;
    165 
    166 	u_int8_t		*sc_ur_buf; /* Unencapsulated frame */
    167 	u_int			sc_ur_framelen;
    168 
    169 	u_int8_t		*sc_rd_buf; /* Raw incoming data stream */
    170 	size_t			sc_rd_index;
    171 	int			sc_rd_addr;
    172 	usbd_pipe_handle	sc_rd_pipe;
    173 	usbd_xfer_handle	sc_rd_xfer;
    174 	u_int			sc_rd_count;
    175 	int			sc_rd_readinprogress;
    176 	u_int			sc_rd_expectdataticks;
    177 	u_char			sc_rd_err;
    178 	struct framestate	sc_framestate;
    179 	struct proc		*sc_thread;
    180 	struct selinfo		sc_rd_sel;
    181 
    182 	u_int8_t		*sc_wr_buf;
    183 	int			sc_wr_addr;
    184 	int			sc_wr_stalewrite;
    185 	usbd_xfer_handle	sc_wr_xfer;
    186 	usbd_pipe_handle	sc_wr_pipe;
    187 	struct selinfo		sc_wr_sel;
    188 
    189 	enum {
    190 		udir_input, /* Receiving data */
    191 		udir_output, /* Transmitting data */
    192 		udir_stalled, /* Error preventing data flow */
    193 		udir_idle /* Neither receiving nor transmitting */
    194 	} sc_direction;
    195 
    196 	struct ustir_speedrec const *sc_speedrec;
    197 
    198 	struct device		*sc_child;
    199 	struct irda_params	sc_params;
    200 
    201 	int			sc_refcnt;
    202 	char			sc_closing;
    203 	char			sc_dying;
    204 };
    205 
    206 /* True if we cannot safely read data from the device */
    207 #define USTIR_BLOCK_RX_DATA(sc) ((sc)->sc_ur_framelen != 0)
    208 
    209 #define USTIR_WR_TIMEOUT 200
    210 
    211 Static int ustir_activate(device_ptr_t self, enum devact act);
    212 Static int ustir_open(void *h, int flag, int mode, usb_proc_ptr p);
    213 Static int ustir_close(void *h, int flag, int mode, usb_proc_ptr p);
    214 Static int ustir_read(void *h, struct uio *uio, int flag);
    215 Static int ustir_write(void *h, struct uio *uio, int flag);
    216 Static int ustir_set_params(void *h, struct irda_params *params);
    217 Static int ustir_get_speeds(void *h, int *speeds);
    218 Static int ustir_get_turnarounds(void *h, int *times);
    219 Static int ustir_poll(void *h, int events, usb_proc_ptr p);
    220 Static int ustir_kqfilter(void *h, struct knote *kn);
    221 
    222 #ifdef USTIR_DEBUG_IOCTLS
    223 Static int ustir_ioctl(void *h, u_long cmd, usb_ioctlarg_t addr, int flag, usb_proc_ptr p);
    224 #endif
    225 
    226 Static struct irframe_methods const ustir_methods = {
    227 	ustir_open, ustir_close, ustir_read, ustir_write, ustir_poll,
    228 	ustir_kqfilter, ustir_set_params, ustir_get_speeds,
    229 	ustir_get_turnarounds,
    230 #ifdef USTIR_DEBUG_IOCTLS
    231 	ustir_ioctl
    232 #endif
    233 };
    234 
    235 Static void ustir_rd_cb(usbd_xfer_handle, usbd_private_handle, usbd_status);
    236 Static usbd_status ustir_start_read(struct ustir_softc *);
    237 Static void ustir_periodic(struct ustir_softc *);
    238 Static void ustir_thread(void *);
    239 
    240 Static u_int32_t
    241 crc_ccitt_16(u_int32_t crcinit, u_int8_t const *buf, size_t blen)
    242 {
    243 	while (blen-- > 0) {
    244 		u_int8_t chr;
    245 		chr = *buf++;
    246 		crcinit = updateFCS(crcinit, chr);
    247 	}
    248 	return crcinit;
    249 }
    250 
    251 static usbd_status
    252 ustir_read_reg(struct ustir_softc *sc, unsigned int reg, u_int8_t *data)
    253 {
    254 	usb_device_request_t req;
    255 
    256 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
    257 	req.bRequest = STIR_CMD_READMULTIREG;
    258 	USETW(req.wValue, 0);
    259 	USETW(req.wIndex, reg);
    260 	USETW(req.wLength, 1);
    261 
    262 	return usbd_do_request(sc->sc_udev, &req, data);
    263 }
    264 
    265 static usbd_status
    266 ustir_write_reg(struct ustir_softc *sc, unsigned int reg, u_int8_t data)
    267 {
    268 	usb_device_request_t req;
    269 
    270 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
    271 	req.bRequest = STIR_CMD_WRITESINGLEREG;
    272 	USETW(req.wValue, data);
    273 	USETW(req.wIndex, reg);
    274 	USETW(req.wLength, 0);
    275 
    276 	return usbd_do_request(sc->sc_udev, &req, NULL);
    277 }
    278 
    279 #ifdef USTIR_DEBUG
    280 static void
    281 ustir_dumpdata(u_int8_t const *data, size_t dlen, char const *desc)
    282 {
    283 	size_t bdindex;
    284 	printf("%s: (%lx)", desc, (unsigned long)dlen);
    285 	for (bdindex = 0; bdindex < dlen; bdindex++)
    286 		printf(" %02x", (unsigned int)data[bdindex]);
    287 	printf("\n");
    288 }
    289 #endif
    290 
    291 USB_DECLARE_DRIVER(ustir);
    292 
    293 USB_MATCH(ustir)
    294 {
    295 	USB_MATCH_START(ustir, uaa);
    296 
    297 	DPRINTFN(50,("ustir_match\n"));
    298 
    299 #ifndef USB_USE_IFATTACH
    300 	if (uaa->iface == NULL)
    301 		return UMATCH_NONE;
    302 #endif /* USB_USE_IFATTACH */
    303 
    304 	if (uaa->vendor == USB_VENDOR_SIGMATEL &&
    305 	    uaa->product == USB_PRODUCT_SIGMATEL_IRDA)
    306 		return UMATCH_VENDOR_PRODUCT;
    307 
    308 	return UMATCH_NONE;
    309 }
    310 
    311 USB_ATTACH(ustir)
    312 {
    313 	USB_ATTACH_START(ustir, sc, uaa);
    314 	usbd_device_handle dev = uaa->device;
    315 #ifndef USB_USE_IFATTACH
    316 	usbd_interface_handle iface = uaa->iface;
    317 #else
    318 	usbd_interface_handle iface;
    319 #endif /* USB_USE_IFATTACH */
    320 	char *devinfop;
    321 	usb_endpoint_descriptor_t *ed;
    322 	u_int8_t epcount;
    323 	int i;
    324 	struct ir_attach_args ia;
    325 
    326 	DPRINTFN(10,("ustir_attach: sc=%p\n", sc));
    327 
    328 	devinfop = usbd_devinfo_alloc(dev, 0);
    329 	USB_ATTACH_SETUP;
    330 	printf("%s: %s\n", USBDEVNAME(sc->sc_dev), devinfop);
    331 	usbd_devinfo_free(devinfop);
    332 
    333 #ifdef USB_USE_IFATTACH
    334 	if (usbd_set_config_index(dev, 0, 1)
    335 	    || usbd_device2interface_handle(dev, 0, &iface)) {
    336 		printf("%s: Configuration failed\n", USBDEVNAME(sc->sc_dev));
    337 		USB_ATTACH_ERROR_RETURN;
    338 	}
    339 #endif /* USB_USE_IFATTACH */
    340 
    341 	sc->sc_udev = dev;
    342 	sc->sc_iface = iface;
    343 
    344 	epcount = 0;
    345 	(void)usbd_endpoint_count(iface, &epcount);
    346 
    347 	sc->sc_rd_addr = -1;
    348 	sc->sc_wr_addr = -1;
    349 	for (i = 0; i < epcount; i++) {
    350 		ed = usbd_interface2endpoint_descriptor(iface, i);
    351 		if (ed == NULL) {
    352 			printf("%s: couldn't get ep %d\n",
    353 			    USBDEVNAME(sc->sc_dev), i);
    354 			USB_ATTACH_ERROR_RETURN;
    355 		}
    356 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
    357 		    UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
    358 			sc->sc_rd_addr = ed->bEndpointAddress;
    359 		} else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT &&
    360 			   UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
    361 			sc->sc_wr_addr = ed->bEndpointAddress;
    362 		}
    363 	}
    364 	if (sc->sc_rd_addr == -1 || sc->sc_wr_addr == -1) {
    365 		printf("%s: missing endpoint\n", USBDEVNAME(sc->sc_dev));
    366 		USB_ATTACH_ERROR_RETURN;
    367 	}
    368 
    369 	DPRINTFN(10, ("ustir_attach: %p\n", sc->sc_udev));
    370 
    371 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev,
    372 			   USBDEV(sc->sc_dev));
    373 
    374 	ia.ia_type = IR_TYPE_IRFRAME;
    375 	ia.ia_methods = &ustir_methods;
    376 	ia.ia_handle = sc;
    377 
    378 	sc->sc_child = config_found(self, &ia, ir_print);
    379 
    380 	USB_ATTACH_SUCCESS_RETURN;
    381 }
    382 
    383 USB_DETACH(ustir)
    384 {
    385 	USB_DETACH_START(ustir, sc);
    386 	int s;
    387 	int rv = 0;
    388 
    389 	DPRINTFN(0, ("ustir_detach: sc=%p flags=%d\n", sc, flags));
    390 
    391 	sc->sc_closing = sc->sc_dying = 1;
    392 
    393 	wakeup(&sc->sc_thread);
    394 
    395 	while (sc->sc_thread != NULL)
    396 		tsleep(&sc->sc_closing, PWAIT, "usircl", 0);
    397 
    398 	/* Abort all pipes.  Causes processes waiting for transfer to wake. */
    399 	if (sc->sc_rd_pipe != NULL) {
    400 		usbd_abort_pipe(sc->sc_rd_pipe);
    401 		usbd_close_pipe(sc->sc_rd_pipe);
    402 		sc->sc_rd_pipe = NULL;
    403 	}
    404 	if (sc->sc_wr_pipe != NULL) {
    405 		usbd_abort_pipe(sc->sc_wr_pipe);
    406 		usbd_close_pipe(sc->sc_wr_pipe);
    407 		sc->sc_wr_pipe = NULL;
    408 	}
    409 	wakeup(&sc->sc_ur_framelen);
    410 	wakeup(&sc->sc_wr_buf);
    411 
    412 	s = splusb();
    413 	if (--sc->sc_refcnt >= 0) {
    414 		/* Wait for processes to go away. */
    415 		usb_detach_wait(USBDEV(sc->sc_dev));
    416 	}
    417 	splx(s);
    418 
    419 	if (sc->sc_child != NULL) {
    420 		rv = config_detach(sc->sc_child, flags);
    421 		sc->sc_child = NULL;
    422 	}
    423 
    424 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev,
    425 			   USBDEV(sc->sc_dev));
    426 
    427 	return rv;
    428 }
    429 
    430 Static void
    431 deframe_clear(struct framestate *fstate)
    432 {
    433 	fstate->bufindex = 0;
    434 	fstate->fsmstate = FSTATE_END_OF_FRAME;
    435 	fstate->escaped = 0;
    436 }
    437 
    438 Static void
    439 deframe_init(struct framestate *fstate, struct framedefn const *definition,
    440 	     u_int8_t *buf, size_t buflen)
    441 {
    442 	fstate->definition = definition;
    443 	fstate->buffer = buf;
    444 	fstate->buflen = buflen;
    445 
    446 	deframe_clear(fstate);
    447 }
    448 
    449 Static enum frameresult
    450 deframe_process(struct framestate *fstate, u_int8_t const **bptr, size_t *blen)
    451 {
    452 	struct framedefn const *definition;
    453 	u_int8_t const *cptr;
    454 	u_int8_t escchr;
    455 	size_t ibuflen, obufindex, obuflen;
    456 	enum framefsmstate fsmstate;
    457 	enum frameresult result;
    458 
    459 	cptr = *bptr;
    460 	fsmstate = fstate->fsmstate;
    461 	definition = fstate->definition;
    462 	escchr = definition->esc_byte;
    463 	obufindex = fstate->bufindex;
    464 	obuflen = fstate->buflen;
    465 	ibuflen = *blen;
    466 
    467 	while (ibuflen-- > 0) {
    468 		u_int8_t chr;
    469 
    470 		chr = *cptr++;
    471 
    472 		if (fstate->escaped) {
    473 			fstate->escaped = 0;
    474 			chr ^= definition->esc_xor;
    475 		} else if (chr == escchr) {
    476 			fstate->escaped = 1;
    477 			continue;
    478 		}
    479 
    480 		switch (fsmstate) {
    481 		case FSTATE_IN_DATA:
    482 			if (chr == definition->eof_byte) {
    483 				fsmstate = FSTATE_IN_END;
    484 				fstate->state_index = definition->eof_count;
    485 				goto state_in_end;
    486 			}
    487 			if (obufindex >= obuflen) {
    488 				result = FR_BUFFEROVERRUN;
    489 				fsmstate = FSTATE_END_OF_FRAME;
    490 				goto complete;
    491 			}
    492 			fstate->buffer[obufindex++] = chr;
    493 			break;
    494 
    495 		state_in_end:
    496 			/* FALLTHROUGH */
    497 
    498 		case FSTATE_IN_END:
    499 			if (--fstate->state_index == 0) {
    500 				u_int32_t crc;
    501 				size_t fcslen;
    502 
    503 				fsmstate = FSTATE_END_OF_FRAME;
    504 
    505 				fcslen = definition->fcs_count;
    506 
    507 				if (obufindex < fcslen) {
    508 					result = FR_FRAMEMALFORMED;
    509 					goto complete;
    510 				}
    511 
    512 				crc = definition->
    513 					fcs_calc(definition->fcs_init,
    514 						 fstate->buffer, obufindex);
    515 
    516 				/* Remove check bytes from buffer length */
    517 				obufindex -= fcslen;
    518 
    519 				if (crc == definition->fcs_correct)
    520 					result = FR_FRAMEOK;
    521 				else
    522 					result = FR_FRAMEBADFCS;
    523 
    524 				goto complete;
    525 			}
    526 			break;
    527 
    528 		case FSTATE_END_OF_FRAME:
    529 			if (chr != definition->bof_byte)
    530 				break;
    531 
    532 			fsmstate = FSTATE_START_OF_FRAME;
    533 			fstate->state_index = definition->bof_count;
    534 			/* FALLTHROUGH */
    535 		case FSTATE_START_OF_FRAME:
    536 			if (--fstate->state_index == 0) {
    537 				fsmstate = FSTATE_IN_DATA;
    538 				obufindex = 0;
    539 			}
    540 			break;
    541 		}
    542 	}
    543 
    544 	result = (fsmstate == FSTATE_END_OF_FRAME) ? FR_IDLE : FR_INPROGRESS;
    545 
    546  complete:
    547 	fstate->bufindex = obufindex;
    548 	fstate->fsmstate = fsmstate;
    549 	*blen = ibuflen;
    550 
    551 	return result;
    552 }
    553 
    554 /* Returns 0 if more data required, 1 if a complete frame was extracted */
    555 static int
    556 deframe_rd_ur(struct ustir_softc *sc)
    557 {
    558 	while (sc->sc_rd_index < sc->sc_rd_count) {
    559 		u_int8_t const *buf;
    560 		size_t buflen;
    561 		enum frameresult fresult;
    562 
    563 		buf = &sc->sc_rd_buf[sc->sc_rd_index];
    564 		buflen = sc->sc_rd_count - sc->sc_rd_index;
    565 
    566 		fresult = deframe_process(&sc->sc_framestate, &buf, &buflen);
    567 
    568 		sc->sc_rd_index = sc->sc_rd_count - buflen;
    569 
    570 		DPRINTFN(1,("%s: result=%d\n", __func__, (int)fresult));
    571 
    572 		switch (fresult) {
    573 		case FR_IDLE:
    574 		case FR_INPROGRESS:
    575 		case FR_FRAMEBADFCS:
    576 		case FR_FRAMEMALFORMED:
    577 		case FR_BUFFEROVERRUN:
    578 			break;
    579 		case FR_FRAMEOK:
    580 			sc->sc_ur_framelen = sc->sc_framestate.bufindex;
    581 			wakeup(&sc->sc_ur_framelen); /* XXX should use flag */
    582 			selnotify(&sc->sc_rd_sel, 0);
    583 			return 1;
    584 		}
    585 	}
    586 
    587 	/* Reset indices into USB-side buffer */
    588 	sc->sc_rd_index = sc->sc_rd_count = 0;
    589 
    590 	return 0;
    591 }
    592 
    593 /*
    594  * Direction transitions:
    595  *
    596  * ustir_periodic() can switch the direction from:
    597  *
    598  *	output -> idle
    599  *	output -> stalled
    600  *	stalled -> idle
    601  *	idle -> input
    602  *
    603  * ustir_rd_cb() can switch the direction from:
    604  *
    605  *	input -> stalled
    606  *	input -> idle
    607  *
    608  * ustir_write() can switch the direction from:
    609  *
    610  *	idle -> output
    611  */
    612 Static void
    613 ustir_periodic(struct ustir_softc *sc)
    614 {
    615 	DPRINTFN(60, ("%s: direction = %d\n",
    616 		      __func__, sc->sc_direction));
    617 
    618 	if (sc->sc_direction == udir_output ||
    619 	    sc->sc_direction == udir_stalled) {
    620 		usbd_status err;
    621 		u_int8_t regval;
    622 
    623 		DPRINTFN(60, ("%s: reading status register\n",
    624 			      __func__));
    625 
    626 		err = ustir_read_reg(sc, STIR_REG_STATUS,
    627 				     &regval);
    628 		if (err != USBD_NORMAL_COMPLETION) {
    629 			printf("%s: status register read failed: %s\n",
    630 			       USBDEVNAME(sc->sc_dev),
    631 			       usbd_errstr(err));
    632 		} else {
    633 			DPRINTFN(10, ("%s: status register = 0x%x\n",
    634 				      __func__,
    635 				      (unsigned int)regval));
    636 			if (sc->sc_direction == udir_output &&
    637 			    !(regval & STIR_RSTATUS_FFDIR))
    638 				/* Output has completed */
    639 				sc->sc_direction = udir_idle;
    640 			if (regval & STIR_RSTATUS_FFOVER) {
    641 				/*
    642 				 * On an overrun the FIFO hangs, and
    643 				 * any data bulk transfers will stall.
    644 				 * Reset the FIFO.
    645 				 */
    646 				sc->sc_direction = udir_stalled;
    647 
    648 				DPRINTFN(10, ("%s: clearing FIFO error\n",
    649 					      __func__));
    650 
    651 				err = ustir_write_reg(sc, STIR_REG_STATUS,
    652 						      STIR_RSTATUS_FFCLR);
    653 				/* XXX if we fail partway through
    654 				 * this, we may not recover? */
    655 				if (err == USBD_NORMAL_COMPLETION)
    656 					err = ustir_write_reg(sc,
    657 							      STIR_REG_STATUS,
    658 							      0);
    659 				if (err != USBD_NORMAL_COMPLETION) {
    660 					printf("%s: FIFO reset failed: %s\n",
    661 					       USBDEVNAME(sc->sc_dev),
    662 					       usbd_errstr(err));
    663 				} else {
    664 					/* FIFO reset */
    665 					sc->sc_direction = udir_idle;
    666 				}
    667 			}
    668 		}
    669 	}
    670 
    671 	if (sc->sc_wr_stalewrite && sc->sc_direction == udir_idle) {
    672 		/*
    673 		 * In a stale write case, we need to check if the
    674 		 * write has completed.  Once that has happened, the
    675 		 * write is no longer stale.
    676 		 *
    677 		 * But note that we may immediately start a read poll...
    678 		 */
    679 		sc->sc_wr_stalewrite = 0;
    680 		wakeup(&sc->sc_wr_buf);
    681 	}
    682 
    683 	if (!sc->sc_rd_readinprogress &&
    684 	    (sc->sc_direction == udir_idle ||
    685 	     sc->sc_direction == udir_input))
    686 		/* Do a read poll if appropriate... */
    687 		ustir_start_read(sc);
    688 }
    689 
    690 Static void
    691 ustir_thread(void *arg)
    692 {
    693 	struct ustir_softc *sc = arg;
    694 
    695 	DPRINTFN(20, ("%s: starting polling thread\n", __func__));
    696 
    697 	while (!sc->sc_closing) {
    698 		if (!sc->sc_rd_readinprogress && !USTIR_BLOCK_RX_DATA(sc))
    699 			ustir_periodic(sc);
    700 
    701 		if (!sc->sc_closing) {
    702 			int error;
    703 			error = tsleep(&sc->sc_thread, PWAIT,
    704 				       "ustir", hz / 10);
    705 			if (error == EWOULDBLOCK &&
    706 			    sc->sc_rd_expectdataticks > 0)
    707 				/*
    708 				 * After a timeout decrement the tick
    709 				 * counter within which time we expect
    710 				 * data to arrive if we are receiving
    711 				 * data...
    712 				 */
    713 				sc->sc_rd_expectdataticks--;
    714 		}
    715 	}
    716 
    717 	DPRINTFN(20, ("%s: exiting polling thread\n", __func__));
    718 
    719 	sc->sc_thread = NULL;
    720 
    721 	wakeup(&sc->sc_closing);
    722 
    723 	if (--sc->sc_refcnt < 0)
    724 		usb_detach_wakeup(USBDEV(sc->sc_dev));
    725 
    726 	kthread_exit(0);
    727 }
    728 
    729 Static void
    730 ustir_rd_cb(usbd_xfer_handle xfer, usbd_private_handle priv,
    731 	    usbd_status status)
    732 {
    733 	struct ustir_softc *sc = priv;
    734 	u_int32_t size;
    735 
    736 	DPRINTFN(60, ("%s: sc=%p\n", __func__, sc));
    737 
    738 	/* Read is no longer in progress */
    739 	sc->sc_rd_readinprogress = 0;
    740 
    741 	if (status == USBD_CANCELLED || sc->sc_closing) /* this is normal */
    742 		return;
    743 	if (status) {
    744 		size = 0;
    745 		sc->sc_rd_err = 1;
    746 
    747 		if (sc->sc_direction == udir_input ||
    748 		    sc->sc_direction == udir_idle) {
    749 			/*
    750 			 * Receive error, probably need to clear error
    751 			 * condition.
    752 			 */
    753 			sc->sc_direction = udir_stalled;
    754 		}
    755 	} else {
    756 		usbd_get_xfer_status(xfer, NULL, NULL, &size, NULL);
    757 	}
    758 
    759 	sc->sc_rd_index = 0;
    760 	sc->sc_rd_count = size;
    761 
    762 	DPRINTFN(((size > 0 || sc->sc_rd_err != 0) ? 20 : 60),
    763 		 ("%s: sc=%p size=%u, err=%d\n", __func__,
    764 		  sc, size, sc->sc_rd_err));
    765 
    766 #ifdef USTIR_DEBUG
    767 	if (ustirdebug >= 20 && size > 0)
    768 		ustir_dumpdata(sc->sc_rd_buf, size, __func__);
    769 #endif
    770 
    771 	if (!deframe_rd_ur(sc)) {
    772 		if (!deframe_isclear(&sc->sc_framestate) && size == 0 &&
    773 		    sc->sc_rd_expectdataticks == 0) {
    774 			/*
    775 			 * Expected data, but didn't get it
    776 			 * within expected time...
    777 			 */
    778 			DPRINTFN(5,("%s: incoming packet timeout\n",
    779 				    __func__));
    780 			deframe_clear(&sc->sc_framestate);
    781 		} else if (size > 0) {
    782 			/*
    783 			 * If we also received actual data, reset the
    784 			 * data read timeout and wake up the possibly
    785 			 * sleeping thread...
    786 			 */
    787 			sc->sc_rd_expectdataticks = 2;
    788 			wakeup(&sc->sc_thread);
    789 		}
    790 	}
    791 
    792 	/*
    793 	 * Check if incoming data has stopped, or that we cannot
    794 	 * safely read any more data.  In the case of the latter we
    795 	 * must switch to idle so that a write will not block...
    796 	 */
    797 	if (sc->sc_direction == udir_input &&
    798 	    ((size == 0 && sc->sc_rd_expectdataticks == 0) ||
    799 	     USTIR_BLOCK_RX_DATA(sc))) {
    800 		DPRINTFN(8,("%s: idling on packet timeout, "
    801 			    "complete frame, or no data\n", __func__));
    802 		sc->sc_direction = udir_idle;
    803 
    804 		/* Wake up for possible output */
    805 		wakeup(&sc->sc_wr_buf);
    806 		selnotify(&sc->sc_wr_sel, 0);
    807 	}
    808 }
    809 
    810 Static usbd_status
    811 ustir_start_read(struct ustir_softc *sc)
    812 {
    813 	usbd_status err;
    814 
    815 	DPRINTFN(60,("%s: sc=%p, size=%d\n", __func__, sc,
    816 		     sc->sc_params.maxsize));
    817 
    818 	if (sc->sc_dying)
    819 		return USBD_IOERROR;
    820 
    821 	if (USTIR_BLOCK_RX_DATA(sc) || deframe_rd_ur(sc)) {
    822 		/*
    823 		 * Can't start reading just yet.  Since we aren't
    824 		 * going to start a read, have to switch direction to
    825 		 * idle.
    826 		 */
    827 		sc->sc_direction = udir_idle;
    828 		return USBD_NORMAL_COMPLETION;
    829 	}
    830 
    831 	/* Starting a read... */
    832 	sc->sc_rd_readinprogress = 1;
    833 	sc->sc_direction = udir_input;
    834 
    835 	if (sc->sc_rd_err) {
    836 		sc->sc_rd_err = 0;
    837 		DPRINTFN(0, ("%s: clear stall\n", __func__));
    838 		usbd_clear_endpoint_stall(sc->sc_rd_pipe);
    839 	}
    840 
    841 	usbd_setup_xfer(sc->sc_rd_xfer, sc->sc_rd_pipe, sc, sc->sc_rd_buf,
    842 			sc->sc_params.maxsize,
    843 			USBD_SHORT_XFER_OK | USBD_NO_COPY,
    844 			USBD_NO_TIMEOUT, ustir_rd_cb);
    845 	err = usbd_transfer(sc->sc_rd_xfer);
    846 	if (err != USBD_IN_PROGRESS) {
    847 		DPRINTFN(0, ("%s: err=%d\n", __func__, (int)err));
    848 		return err;
    849 	}
    850 	return USBD_NORMAL_COMPLETION;
    851 }
    852 
    853 Static int
    854 ustir_activate(device_ptr_t self, enum devact act)
    855 {
    856 	struct ustir_softc *sc = (struct ustir_softc *)self;
    857 	int error = 0;
    858 
    859 	switch (act) {
    860 	case DVACT_ACTIVATE:
    861 		return EOPNOTSUPP;
    862 
    863 	case DVACT_DEACTIVATE:
    864 		sc->sc_dying = 1;
    865 		if (sc->sc_child != NULL)
    866 			error = config_deactivate(sc->sc_child);
    867 		break;
    868 	}
    869 	return error;
    870 }
    871 
    872 /* ARGSUSED */
    873 Static int
    874 ustir_open(void *h, int flag, int mode,
    875     usb_proc_ptr p)
    876 {
    877 	struct ustir_softc *sc = h;
    878 	int error;
    879 	usbd_status err;
    880 
    881 	DPRINTFN(0, ("%s: sc=%p\n", __func__, sc));
    882 
    883 	err = usbd_open_pipe(sc->sc_iface, sc->sc_rd_addr, 0, &sc->sc_rd_pipe);
    884 	if (err != USBD_NORMAL_COMPLETION) {
    885 		error = EIO;
    886 		goto bad1;
    887 	}
    888 	err = usbd_open_pipe(sc->sc_iface, sc->sc_wr_addr, 0, &sc->sc_wr_pipe);
    889 	if (err != USBD_NORMAL_COMPLETION) {
    890 		error = EIO;
    891 		goto bad2;
    892 	}
    893 	sc->sc_rd_xfer = usbd_alloc_xfer(sc->sc_udev, sc->sc_rd_pipe);
    894 	if (sc->sc_rd_xfer == NULL) {
    895 		error = ENOMEM;
    896 		goto bad3;
    897 	}
    898 	sc->sc_wr_xfer = usbd_alloc_xfer(sc->sc_udev, sc->sc_wr_pipe);
    899 	if (sc->sc_wr_xfer == NULL) {
    900 		error = ENOMEM;
    901 		goto bad4;
    902 	}
    903 	sc->sc_rd_buf = usbd_alloc_buffer(sc->sc_rd_xfer,
    904 			    IRDA_MAX_FRAME_SIZE);
    905 	if (sc->sc_rd_buf == NULL) {
    906 		error = ENOMEM;
    907 		goto bad5;
    908 	}
    909 	sc->sc_wr_buf = usbd_alloc_buffer(sc->sc_wr_xfer,
    910 			    IRDA_MAX_FRAME_SIZE + STIR_OUTPUT_HEADER_SIZE);
    911 	if (sc->sc_wr_buf == NULL) {
    912 		error = ENOMEM;
    913 		goto bad5;
    914 	}
    915 	sc->sc_ur_buf = malloc(IRDA_MAX_FRAME_SIZE, M_USBDEV, M_NOWAIT);
    916 	if (sc->sc_ur_buf == NULL) {
    917 		error = ENOMEM;
    918 		goto bad5;
    919 	}
    920 
    921 	sc->sc_rd_index = sc->sc_rd_count = 0;
    922 	sc->sc_closing = 0;
    923 	sc->sc_rd_readinprogress = 0;
    924 	sc->sc_rd_expectdataticks = 0;
    925 	sc->sc_ur_framelen = 0;
    926 	sc->sc_rd_err = 0;
    927 	sc->sc_wr_stalewrite = 0;
    928 	sc->sc_speedrec = NULL;
    929 	sc->sc_direction = udir_idle;
    930 	sc->sc_params.speed = 0;
    931 	sc->sc_params.ebofs = 0;
    932 	sc->sc_params.maxsize = IRDA_MAX_FRAME_SIZE;
    933 
    934 	deframe_init(&sc->sc_framestate, &framedef_sir, sc->sc_ur_buf,
    935 		     IRDA_MAX_FRAME_SIZE);
    936 
    937 	error = kthread_create1(ustir_thread, sc, &sc->sc_thread, "%s",
    938 				sc->sc_dev.dv_xname);
    939 	if (error)
    940 		goto bad5;
    941 	/* Increment reference for thread */
    942 	sc->sc_refcnt++;
    943 
    944 	return 0;
    945 
    946  bad5:
    947 	usbd_free_xfer(sc->sc_wr_xfer);
    948 	sc->sc_wr_xfer = NULL;
    949  bad4:
    950 	usbd_free_xfer(sc->sc_rd_xfer);
    951 	sc->sc_rd_xfer = NULL;
    952  bad3:
    953 	usbd_close_pipe(sc->sc_wr_pipe);
    954 	sc->sc_wr_pipe = NULL;
    955  bad2:
    956 	usbd_close_pipe(sc->sc_rd_pipe);
    957 	sc->sc_rd_pipe = NULL;
    958  bad1:
    959 	return error;
    960 }
    961 
    962 /* ARGSUSED */
    963 Static int
    964 ustir_close(void *h, int flag, int mode, usb_proc_ptr p)
    965 {
    966 	struct ustir_softc *sc = h;
    967 
    968 	DPRINTFN(0, ("%s: sc=%p\n", __func__, sc));
    969 
    970 	sc->sc_refcnt++;
    971 
    972 	sc->sc_rd_readinprogress = 1;
    973 	sc->sc_closing = 1;
    974 
    975 	wakeup(&sc->sc_thread);
    976 
    977 	while (sc->sc_thread != NULL)
    978 		tsleep(&sc->sc_closing, PWAIT, "usircl", 0);
    979 
    980 	if (sc->sc_rd_pipe != NULL)
    981 		usbd_abort_pipe(sc->sc_rd_pipe);
    982 	if (sc->sc_wr_pipe != NULL)
    983 		usbd_abort_pipe(sc->sc_wr_pipe);
    984 	if (sc->sc_rd_xfer != NULL) {
    985 		usbd_free_xfer(sc->sc_rd_xfer);
    986 		sc->sc_rd_xfer = NULL;
    987 		sc->sc_rd_buf = NULL;
    988 	}
    989 	if (sc->sc_wr_xfer != NULL) {
    990 		usbd_free_xfer(sc->sc_wr_xfer);
    991 		sc->sc_wr_xfer = NULL;
    992 		sc->sc_wr_buf = NULL;
    993 	}
    994 	if (sc->sc_ur_buf != NULL) {
    995 		free(sc->sc_ur_buf, M_USBDEV);
    996 		sc->sc_ur_buf = NULL;
    997 	}
    998 	if (sc->sc_rd_pipe != NULL) {
    999 		usbd_close_pipe(sc->sc_rd_pipe);
   1000 		sc->sc_rd_pipe = NULL;
   1001 	}
   1002 	if (sc->sc_wr_pipe != NULL) {
   1003 		usbd_close_pipe(sc->sc_wr_pipe);
   1004 		sc->sc_wr_pipe = NULL;
   1005 	}
   1006 
   1007 	if (--sc->sc_refcnt < 0)
   1008 		usb_detach_wakeup(USBDEV(sc->sc_dev));
   1009 
   1010 	return 0;
   1011 }
   1012 
   1013 /* ARGSUSED */
   1014 Static int
   1015 ustir_read(void *h, struct uio *uio, int flag)
   1016 {
   1017 	struct ustir_softc *sc = h;
   1018 	int s;
   1019 	int error;
   1020 	u_int uframelen;
   1021 
   1022 	DPRINTFN(1,("%s: sc=%p\n", __func__, sc));
   1023 
   1024 	if (sc->sc_dying)
   1025 		return EIO;
   1026 
   1027 #ifdef DIAGNOSTIC
   1028 	if (sc->sc_rd_buf == NULL)
   1029 		return EINVAL;
   1030 #endif
   1031 
   1032 	sc->sc_refcnt++;
   1033 
   1034 	if (!sc->sc_rd_readinprogress && !USTIR_BLOCK_RX_DATA(sc))
   1035 		/* Possibly wake up polling thread */
   1036 		wakeup(&sc->sc_thread);
   1037 
   1038 	do {
   1039 		s = splusb();
   1040 		while (sc->sc_ur_framelen == 0) {
   1041 			DPRINTFN(5,("%s: calling tsleep()\n", __func__));
   1042 			error = tsleep(&sc->sc_ur_framelen, PZERO | PCATCH,
   1043 				       "usirrd", 0);
   1044 			if (sc->sc_dying)
   1045 				error = EIO;
   1046 			if (error) {
   1047 				splx(s);
   1048 				DPRINTFN(0, ("%s: tsleep() = %d\n",
   1049 					     __func__, error));
   1050 				goto ret;
   1051 			}
   1052 		}
   1053 		splx(s);
   1054 
   1055 		uframelen = sc->sc_ur_framelen;
   1056 		DPRINTFN(1,("%s: sc=%p framelen=%u, hdr=0x%02x\n",
   1057 			    __func__, sc, uframelen, sc->sc_ur_buf[0]));
   1058 		if (uframelen > uio->uio_resid)
   1059 			error = EINVAL;
   1060 		else
   1061 			error = uiomove(sc->sc_ur_buf, uframelen, uio);
   1062 		sc->sc_ur_framelen = 0;
   1063 
   1064 		if (!deframe_rd_ur(sc) && uframelen > 0) {
   1065 			/*
   1066 			 * Need to wait for another read to obtain a
   1067 			 * complete frame...  If we also obtained
   1068 			 * actual data, wake up the possibly sleeping
   1069 			 * thread immediately...
   1070 			 */
   1071 			wakeup(&sc->sc_thread);
   1072 		}
   1073 	} while (uframelen == 0);
   1074 
   1075 	DPRINTFN(1,("%s: return %d\n", __func__, error));
   1076 
   1077  ret:
   1078 	if (--sc->sc_refcnt < 0)
   1079 		usb_detach_wakeup(USBDEV(sc->sc_dev));
   1080 	return error;
   1081 }
   1082 
   1083 /* ARGSUSED */
   1084 Static int
   1085 ustir_write(void *h, struct uio *uio, int flag)
   1086 {
   1087 	struct ustir_softc *sc = h;
   1088 	usbd_status err;
   1089 	u_int32_t wrlen;
   1090 	int error, sirlength;
   1091 	u_int8_t *wrbuf;
   1092 	int s;
   1093 
   1094 	DPRINTFN(1,("%s: sc=%p\n", __func__, sc));
   1095 
   1096 	if (sc->sc_dying)
   1097 		return EIO;
   1098 
   1099 #ifdef DIAGNOSTIC
   1100 	if (sc->sc_wr_buf == NULL)
   1101 		return EINVAL;
   1102 #endif
   1103 
   1104 	wrlen = uio->uio_resid;
   1105 	if (wrlen > sc->sc_params.maxsize)
   1106 		return EINVAL;
   1107 
   1108 	sc->sc_refcnt++;
   1109 
   1110 	if (!USTIR_BLOCK_RX_DATA(sc)) {
   1111 		/*
   1112 		 * If reads are not blocked, determine what action we
   1113 		 * should potentially take...
   1114 		 */
   1115 		if (sc->sc_direction == udir_output) {
   1116 			/*
   1117 			 * If the last operation was an output, wait for the
   1118 			 * polling thread to check for incoming data.
   1119 			 */
   1120 			sc->sc_wr_stalewrite = 1;
   1121 			wakeup(&sc->sc_thread);
   1122 		} else if (!sc->sc_rd_readinprogress &&
   1123 			   (sc->sc_direction == udir_idle ||
   1124 			    sc->sc_direction == udir_input)) {
   1125 			/* If idle, check for input before outputting */
   1126 			ustir_start_read(sc);
   1127 		}
   1128 	}
   1129 
   1130 	s = splusb();
   1131 	while (sc->sc_wr_stalewrite ||
   1132 	       (sc->sc_direction != udir_output &&
   1133 		sc->sc_direction != udir_idle)) {
   1134 		DPRINTFN(5, ("%s: sc=%p stalewrite=%d direction=%d, "
   1135 			     "calling tsleep()\n", __func__,
   1136 			     sc, sc->sc_wr_stalewrite, sc->sc_direction));
   1137 		error = tsleep(&sc->sc_wr_buf, PZERO | PCATCH,
   1138 			       "usirwr", 0);
   1139 		if (sc->sc_dying)
   1140 			error = EIO;
   1141 		if (error) {
   1142 			splx(s);
   1143 			DPRINTFN(0, ("%s: tsleep() = %d\n", __func__,
   1144 				     error));
   1145 			goto ret;
   1146 		}
   1147 	}
   1148 	splx(s);
   1149 
   1150 	wrbuf = sc->sc_wr_buf;
   1151 
   1152 	/* Build header */
   1153 	wrbuf[0] = STIR_OUTPUT_HEADER_BYTE0;
   1154 	wrbuf[1] = STIR_OUTPUT_HEADER_BYTE1;
   1155 
   1156 	sirlength = irda_sir_frame(&wrbuf[STIR_OUTPUT_HEADER_SIZE],
   1157 				   MAX_USTIR_OUTPUT_FRAME -
   1158 				   STIR_OUTPUT_HEADER_SIZE,
   1159 				   uio, sc->sc_params.ebofs);
   1160 	if (sirlength < 0) {
   1161 		error = -sirlength;
   1162 	} else {
   1163 		u_int32_t btlen;
   1164 
   1165 		DPRINTFN(1, ("%s: transfer %u bytes\n", __func__,
   1166 			     (unsigned int)wrlen));
   1167 
   1168 		wrbuf[2] = sirlength & 0xff;
   1169 		wrbuf[3] = (sirlength >> 8) & 0xff;
   1170 
   1171 		btlen = STIR_OUTPUT_HEADER_SIZE + sirlength;
   1172 
   1173 		sc->sc_direction = udir_output;
   1174 
   1175 #ifdef USTIR_DEBUG
   1176 		if (ustirdebug >= 20)
   1177 			ustir_dumpdata(wrbuf, btlen, __func__);
   1178 #endif
   1179 
   1180 		err = usbd_bulk_transfer(sc->sc_wr_xfer, sc->sc_wr_pipe,
   1181 					 USBD_FORCE_SHORT_XFER | USBD_NO_COPY,
   1182 					 USTIR_WR_TIMEOUT,
   1183 					 wrbuf, &btlen, "ustiwr");
   1184 		DPRINTFN(2, ("%s: err=%d\n", __func__, err));
   1185 		if (err != USBD_NORMAL_COMPLETION) {
   1186 			if (err == USBD_INTERRUPTED)
   1187 				error = EINTR;
   1188 			else if (err == USBD_TIMEOUT)
   1189 				error = ETIMEDOUT;
   1190 			else
   1191 				error = EIO;
   1192 		} else {
   1193 			error = 0;
   1194 		}
   1195 	}
   1196 
   1197  ret:
   1198 	if (--sc->sc_refcnt < 0)
   1199 		usb_detach_wakeup(USBDEV(sc->sc_dev));
   1200 
   1201 	DPRINTFN(1,("%s: sc=%p done\n", __func__, sc));
   1202 	return error;
   1203 }
   1204 
   1205 Static int
   1206 ustir_poll(void *h, int events, usb_proc_ptr p)
   1207 {
   1208 	struct ustir_softc *sc = h;
   1209 	int revents = 0;
   1210 
   1211 	DPRINTFN(1,("%s: sc=%p\n", __func__, sc));
   1212 
   1213 	if (events & (POLLOUT | POLLWRNORM)) {
   1214 		if (sc->sc_direction != udir_input) {
   1215 			revents |= events & (POLLOUT | POLLWRNORM);
   1216 		} else {
   1217 			DPRINTFN(2,("%s: recording write select\n",
   1218 				    __func__));
   1219 			selrecord(p, &sc->sc_wr_sel);
   1220 		}
   1221 	}
   1222 
   1223 	if (events & (POLLIN | POLLRDNORM)) {
   1224 		if (sc->sc_ur_framelen != 0) {
   1225 			DPRINTFN(2,("%s: have data\n", __func__));
   1226 			revents |= events & (POLLIN | POLLRDNORM);
   1227 		} else {
   1228 			DPRINTFN(2,("%s: recording read select\n",
   1229 				    __func__));
   1230 			selrecord(p, &sc->sc_rd_sel);
   1231 		}
   1232 	}
   1233 
   1234 	return revents;
   1235 }
   1236 
   1237 static void
   1238 filt_ustirrdetach(struct knote *kn)
   1239 {
   1240 	struct ustir_softc *sc = kn->kn_hook;
   1241 	int s;
   1242 
   1243 	s = splusb();
   1244 	SLIST_REMOVE(&sc->sc_rd_sel.sel_klist, kn, knote, kn_selnext);
   1245 	splx(s);
   1246 }
   1247 
   1248 /* ARGSUSED */
   1249 static int
   1250 filt_ustirread(struct knote *kn, long hint)
   1251 {
   1252 	struct ustir_softc *sc = kn->kn_hook;
   1253 
   1254 	kn->kn_data = sc->sc_ur_framelen;
   1255 	return (kn->kn_data > 0);
   1256 }
   1257 
   1258 static void
   1259 filt_ustirwdetach(struct knote *kn)
   1260 {
   1261 	struct ustir_softc *sc = kn->kn_hook;
   1262 	int s;
   1263 
   1264 	s = splusb();
   1265 	SLIST_REMOVE(&sc->sc_wr_sel.sel_klist, kn, knote, kn_selnext);
   1266 	splx(s);
   1267 }
   1268 
   1269 /* ARGSUSED */
   1270 static int
   1271 filt_ustirwrite(struct knote *kn, long hint)
   1272 {
   1273 	struct ustir_softc *sc = kn->kn_hook;
   1274 
   1275 	kn->kn_data = 0;
   1276 	return (sc->sc_direction != udir_input);
   1277 }
   1278 
   1279 static const struct filterops ustirread_filtops =
   1280 	{ 1, NULL, filt_ustirrdetach, filt_ustirread };
   1281 static const struct filterops ustirwrite_filtops =
   1282 	{ 1, NULL, filt_ustirwdetach, filt_ustirwrite };
   1283 
   1284 Static int
   1285 ustir_kqfilter(void *h, struct knote *kn)
   1286 {
   1287 	struct ustir_softc *sc = h;
   1288 	struct klist *klist;
   1289 	int s;
   1290 
   1291 	switch (kn->kn_filter) {
   1292 	case EVFILT_READ:
   1293 		klist = &sc->sc_rd_sel.sel_klist;
   1294 		kn->kn_fop = &ustirread_filtops;
   1295 		break;
   1296 	case EVFILT_WRITE:
   1297 		klist = &sc->sc_wr_sel.sel_klist;
   1298 		kn->kn_fop = &ustirwrite_filtops;
   1299 		break;
   1300 	default:
   1301 		return (1);
   1302 	}
   1303 
   1304 	kn->kn_hook = sc;
   1305 
   1306 	s = splusb();
   1307 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
   1308 	splx(s);
   1309 
   1310 	return (0);
   1311 }
   1312 
   1313 #ifdef USTIR_DEBUG_IOCTLS
   1314 Static int ustir_ioctl(void *h, u_long cmd, usb_ioctlarg_t addr, int flag, usb_proc_ptr p)
   1315 {
   1316 	struct ustir_softc *sc = h;
   1317 	int error;
   1318 	unsigned int regnum;
   1319 	usbd_status err;
   1320 	u_int8_t regdata;
   1321 
   1322 	if (sc->sc_dying)
   1323 		return EIO;
   1324 
   1325 	sc->sc_refcnt++;
   1326 
   1327 	error = 0;
   1328 	switch (cmd) {
   1329 	case USTIR_READ_REGISTER:
   1330 		regnum = *(unsigned int *)addr;
   1331 
   1332 		if (regnum > STIR_MAX_REG) {
   1333 			error = EINVAL;
   1334 			break;
   1335 		}
   1336 
   1337 		err = ustir_read_reg(sc, regnum, &regdata);
   1338 
   1339 		DPRINTFN(10, ("%s: regget(%u) = 0x%x\n", __func__,
   1340 			      regnum, (unsigned int)regdata));
   1341 
   1342 		*(unsigned int *)addr = regdata;
   1343 		if (err != USBD_NORMAL_COMPLETION) {
   1344 			printf("%s: register read failed: %s\n",
   1345 			       USBDEVNAME(sc->sc_dev),
   1346 			       usbd_errstr(err));
   1347 			error = EIO;
   1348 		}
   1349 		break;
   1350 
   1351 	case USTIR_WRITE_REGISTER:
   1352 		regnum = *(unsigned int *)addr;
   1353 		regdata = (regnum >> 8) & 0xff;
   1354 		regnum = regnum & 0xff;
   1355 
   1356 		if (regnum > STIR_MAX_REG) {
   1357 			error = EINVAL;
   1358 			break;
   1359 		}
   1360 
   1361 		DPRINTFN(10, ("%s: regset(%u, 0x%x)\n", __func__,
   1362 			      regnum, (unsigned int)regdata));
   1363 
   1364 		err = ustir_write_reg(sc, regnum, regdata);
   1365 		if (err != USBD_NORMAL_COMPLETION) {
   1366 			printf("%s: register write failed: %s\n",
   1367 			       USBDEVNAME(sc->sc_dev),
   1368 			       usbd_errstr(err));
   1369 			error = EIO;
   1370 		}
   1371 		break;
   1372 
   1373 	case USTIR_DEBUG_LEVEL:
   1374 #ifdef USTIR_DEBUG
   1375 		ustirdebug = *(int *)addr;
   1376 #endif
   1377 		break;
   1378 
   1379 	case USTIR_DEBUG_OPERATION:
   1380 		break;
   1381 
   1382 	default:
   1383 		error = EINVAL;
   1384 		break;
   1385 	}
   1386 
   1387 	if (--sc->sc_refcnt < 0)
   1388 		usb_detach_wakeup(USBDEV(sc->sc_dev));
   1389 
   1390 	return error;
   1391 }
   1392 #endif
   1393 
   1394 Static int
   1395 ustir_set_params(void *h, struct irda_params *p)
   1396 {
   1397 	struct ustir_softc *sc = h;
   1398 	struct ustir_speedrec const *speedblk;
   1399 	int i;
   1400 
   1401 	DPRINTFN(0, ("%s: sc=%p, speed=%d ebofs=%d maxsize=%d\n", __func__,
   1402 		     sc, p->speed, p->ebofs, p->maxsize));
   1403 
   1404 	if (sc->sc_dying)
   1405 		return EIO;
   1406 
   1407 	speedblk = NULL;
   1408 
   1409 	if (sc->sc_speedrec == NULL || p->speed != sc->sc_speedrec->speed) {
   1410 		/* find speed */
   1411 		for (i = 0; i < USTIR_NSPEEDS; i++) {
   1412 			if (ustir_speeds[i].speed == p->speed) {
   1413 				speedblk = &ustir_speeds[i];
   1414 				goto found2;
   1415 			}
   1416 		}
   1417 		/* no good value found */
   1418 		return EINVAL;
   1419 	found2:
   1420 		;
   1421 	}
   1422 	if (p->maxsize != sc->sc_params.maxsize) {
   1423 		if (p->maxsize > IRDA_MAX_FRAME_SIZE)
   1424 			return EINVAL;
   1425 		sc->sc_params.maxsize = p->maxsize;
   1426 	}
   1427 
   1428 	sc->sc_params = *p;
   1429 
   1430 	if (speedblk != NULL) {
   1431 		usbd_status err;
   1432 		u_int8_t regmode;
   1433 		u_int8_t regbrate;
   1434 
   1435 		sc->sc_speedrec = speedblk;
   1436 
   1437 		regmode = STIR_BRMODE_MODEREG(speedblk->config);
   1438 		regbrate = STIR_BRMODE_BRATEREG(speedblk->config);
   1439 
   1440 		/*
   1441 		 * FFSPRST must be set to enable the FIFO.
   1442 		 */
   1443 		regmode |= STIR_RMODE_FFSPRST;
   1444 
   1445 		DPRINTFN(10, ("%s: setting BRATE = %x\n", __func__,
   1446 			      (unsigned int)regbrate));
   1447 		err = ustir_write_reg(sc, STIR_REG_BRATE, regbrate);
   1448 		if (err == USBD_NORMAL_COMPLETION) {
   1449 			DPRINTFN(10, ("%s: setting MODE = %x\n", __func__,
   1450 				      (unsigned int)regmode));
   1451 			err = ustir_write_reg(sc, STIR_REG_MODE, regmode);
   1452 		}
   1453 		if (err != USBD_NORMAL_COMPLETION) {
   1454 			DPRINTFN(10, ("%s: error setting register: %s\n",
   1455 				      __func__, usbd_errstr(err)));
   1456 			return EIO;
   1457 		}
   1458 	}
   1459 
   1460 	return 0;
   1461 }
   1462 
   1463 Static int
   1464 ustir_get_speeds(void *h, int *speeds)
   1465 {
   1466 	struct ustir_softc *sc = h;
   1467 
   1468 	DPRINTFN(0, ("%s: sc=%p\n", __func__, sc));
   1469 
   1470 	if (sc->sc_dying)
   1471 		return EIO;
   1472 
   1473 	/* All these speeds are supported */
   1474 	*speeds = IRDA_SPEED_4000000 |
   1475 		IRDA_SPEED_1152000 |
   1476 		IRDA_SPEED_576000 |
   1477 		IRDA_SPEED_115200 |
   1478 		IRDA_SPEED_57600 |
   1479 		IRDA_SPEED_38400 |
   1480 		IRDA_SPEED_19200 |
   1481 		IRDA_SPEED_9600 |
   1482 		IRDA_SPEED_2400;
   1483 
   1484 	return 0;
   1485 }
   1486 
   1487 Static int
   1488 ustir_get_turnarounds(void *h, int *turnarounds)
   1489 {
   1490 	struct ustir_softc *sc = h;
   1491 
   1492 	DPRINTFN(0, ("%s: sc=%p\n", __func__, sc));
   1493 
   1494 	if (sc->sc_dying)
   1495 		return EIO;
   1496 
   1497 	/*
   1498 	 * Documentation is on the light side with respect to
   1499 	 * turnaround time for this device.
   1500 	 */
   1501 	*turnarounds = IRDA_TURNT_10000;
   1502 
   1503 	return 0;
   1504 }
   1505