xref: /netbsd-src/sys/dev/usb/ustir.c (revision 23c8222edbfb0f0932d88a8351d3a0cf817dfb9e)
1 /*	$NetBSD: ustir.c,v 1.13 2004/04/23 17:25:27 itojun 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@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.13 2004/04/23 17:25:27 itojun 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, caddr_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 	if (uaa->iface == NULL)
300 		return UMATCH_NONE;
301 
302 	if (uaa->vendor == USB_VENDOR_SIGMATEL &&
303 	    uaa->product == USB_PRODUCT_SIGMATEL_IRDA)
304 		return UMATCH_VENDOR_PRODUCT;
305 
306 	return UMATCH_NONE;
307 }
308 
309 USB_ATTACH(ustir)
310 {
311 	USB_ATTACH_START(ustir, sc, uaa);
312 	usbd_device_handle dev = uaa->device;
313 	usbd_interface_handle iface = uaa->iface;
314 	char devinfo[1024];
315 	usb_endpoint_descriptor_t *ed;
316 	u_int8_t epcount;
317 	int i;
318 	struct ir_attach_args ia;
319 
320 	DPRINTFN(10,("ustir_attach: sc=%p\n", sc));
321 
322 	usbd_devinfo(dev, 0, devinfo, sizeof(devinfo));
323 	USB_ATTACH_SETUP;
324 	printf("%s: %s\n", USBDEVNAME(sc->sc_dev), devinfo);
325 
326 	sc->sc_udev = dev;
327 	sc->sc_iface = iface;
328 
329 	epcount = 0;
330 	(void)usbd_endpoint_count(iface, &epcount);
331 
332 	sc->sc_rd_addr = -1;
333 	sc->sc_wr_addr = -1;
334 	for (i = 0; i < epcount; i++) {
335 		ed = usbd_interface2endpoint_descriptor(iface, i);
336 		if (ed == NULL) {
337 			printf("%s: couldn't get ep %d\n",
338 			    USBDEVNAME(sc->sc_dev), i);
339 			USB_ATTACH_ERROR_RETURN;
340 		}
341 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
342 		    UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
343 			sc->sc_rd_addr = ed->bEndpointAddress;
344 		} else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT &&
345 			   UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
346 			sc->sc_wr_addr = ed->bEndpointAddress;
347 		}
348 	}
349 	if (sc->sc_rd_addr == -1 || sc->sc_wr_addr == -1) {
350 		printf("%s: missing endpoint\n", USBDEVNAME(sc->sc_dev));
351 		USB_ATTACH_ERROR_RETURN;
352 	}
353 
354 	DPRINTFN(10, ("ustir_attach: %p\n", sc->sc_udev));
355 
356 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev,
357 			   USBDEV(sc->sc_dev));
358 
359 	ia.ia_type = IR_TYPE_IRFRAME;
360 	ia.ia_methods = &ustir_methods;
361 	ia.ia_handle = sc;
362 
363 	sc->sc_child = config_found(self, &ia, ir_print);
364 
365 	USB_ATTACH_SUCCESS_RETURN;
366 }
367 
368 USB_DETACH(ustir)
369 {
370 	USB_DETACH_START(ustir, sc);
371 	int s;
372 	int rv = 0;
373 
374 	DPRINTFN(0, ("ustir_detach: sc=%p flags=%d\n", sc, flags));
375 
376 	sc->sc_closing = sc->sc_dying = 1;
377 
378 	wakeup(&sc->sc_thread);
379 
380 	while (sc->sc_thread != NULL)
381 		tsleep(&sc->sc_closing, PWAIT, "usircl", 0);
382 
383 	/* Abort all pipes.  Causes processes waiting for transfer to wake. */
384 	if (sc->sc_rd_pipe != NULL) {
385 		usbd_abort_pipe(sc->sc_rd_pipe);
386 		usbd_close_pipe(sc->sc_rd_pipe);
387 		sc->sc_rd_pipe = NULL;
388 	}
389 	if (sc->sc_wr_pipe != NULL) {
390 		usbd_abort_pipe(sc->sc_wr_pipe);
391 		usbd_close_pipe(sc->sc_wr_pipe);
392 		sc->sc_wr_pipe = NULL;
393 	}
394 	wakeup(&sc->sc_ur_framelen);
395 	wakeup(&sc->sc_wr_buf);
396 
397 	s = splusb();
398 	if (--sc->sc_refcnt >= 0) {
399 		/* Wait for processes to go away. */
400 		usb_detach_wait(USBDEV(sc->sc_dev));
401 	}
402 	splx(s);
403 
404 	if (sc->sc_child != NULL) {
405 		rv = config_detach(sc->sc_child, flags);
406 		sc->sc_child = NULL;
407 	}
408 
409 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev,
410 			   USBDEV(sc->sc_dev));
411 
412 	return rv;
413 }
414 
415 Static void
416 deframe_clear(struct framestate *fstate)
417 {
418 	fstate->bufindex = 0;
419 	fstate->fsmstate = FSTATE_END_OF_FRAME;
420 	fstate->escaped = 0;
421 }
422 
423 Static void
424 deframe_init(struct framestate *fstate, struct framedefn const *definition,
425 	     u_int8_t *buf, size_t buflen)
426 {
427 	fstate->definition = definition;
428 	fstate->buffer = buf;
429 	fstate->buflen = buflen;
430 
431 	deframe_clear(fstate);
432 }
433 
434 Static enum frameresult
435 deframe_process(struct framestate *fstate, u_int8_t const **bptr, size_t *blen)
436 {
437 	struct framedefn const *definition;
438 	u_int8_t const *cptr;
439 	u_int8_t escchr;
440 	size_t ibuflen, obufindex, obuflen;
441 	enum framefsmstate fsmstate;
442 	enum frameresult result;
443 
444 	cptr = *bptr;
445 	fsmstate = fstate->fsmstate;
446 	definition = fstate->definition;
447 	escchr = definition->esc_byte;
448 	obufindex = fstate->bufindex;
449 	obuflen = fstate->buflen;
450 	ibuflen = *blen;
451 
452 	while (ibuflen-- > 0) {
453 		u_int8_t chr;
454 
455 		chr = *cptr++;
456 
457 		if (fstate->escaped) {
458 			fstate->escaped = 0;
459 			chr ^= definition->esc_xor;
460 		} else if (chr == escchr) {
461 			fstate->escaped = 1;
462 			continue;
463 		}
464 
465 		switch (fsmstate) {
466 		case FSTATE_IN_DATA:
467 			if (chr == definition->eof_byte) {
468 				fsmstate = FSTATE_IN_END;
469 				fstate->state_index = definition->eof_count;
470 				goto state_in_end;
471 			}
472 			if (obufindex >= obuflen) {
473 				result = FR_BUFFEROVERRUN;
474 				fsmstate = FSTATE_END_OF_FRAME;
475 				goto complete;
476 			}
477 			fstate->buffer[obufindex++] = chr;
478 			break;
479 
480 		state_in_end:
481 			/* FALLTHROUGH */
482 
483 		case FSTATE_IN_END:
484 			if (--fstate->state_index == 0) {
485 				u_int32_t crc;
486 				size_t fcslen;
487 
488 				fsmstate = FSTATE_END_OF_FRAME;
489 
490 				fcslen = definition->fcs_count;
491 
492 				if (obufindex < fcslen) {
493 					result = FR_FRAMEMALFORMED;
494 					goto complete;
495 				}
496 
497 				crc = definition->
498 					fcs_calc(definition->fcs_init,
499 						 fstate->buffer, obufindex);
500 
501 				/* Remove check bytes from buffer length */
502 				obufindex -= fcslen;
503 
504 				if (crc == definition->fcs_correct)
505 					result = FR_FRAMEOK;
506 				else
507 					result = FR_FRAMEBADFCS;
508 
509 				goto complete;
510 			}
511 			break;
512 
513 		case FSTATE_END_OF_FRAME:
514 			if (chr != definition->bof_byte)
515 				break;
516 
517 			fsmstate = FSTATE_START_OF_FRAME;
518 			fstate->state_index = definition->bof_count;
519 			/* FALLTHROUGH */
520 		case FSTATE_START_OF_FRAME:
521 			if (--fstate->state_index == 0) {
522 				fsmstate = FSTATE_IN_DATA;
523 				obufindex = 0;
524 			}
525 			break;
526 		}
527 	}
528 
529 	result = (fsmstate == FSTATE_END_OF_FRAME) ? FR_IDLE : FR_INPROGRESS;
530 
531  complete:
532 	fstate->bufindex = obufindex;
533 	fstate->fsmstate = fsmstate;
534 	*blen = ibuflen;
535 
536 	return result;
537 }
538 
539 /* Returns 0 if more data required, 1 if a complete frame was extracted */
540 static int
541 deframe_rd_ur(struct ustir_softc *sc)
542 {
543 	while (sc->sc_rd_index < sc->sc_rd_count) {
544 		u_int8_t const *buf;
545 		size_t buflen;
546 		enum frameresult fresult;
547 
548 		buf = &sc->sc_rd_buf[sc->sc_rd_index];
549 		buflen = sc->sc_rd_count - sc->sc_rd_index;
550 
551 		fresult = deframe_process(&sc->sc_framestate, &buf, &buflen);
552 
553 		sc->sc_rd_index = sc->sc_rd_count - buflen;
554 
555 		DPRINTFN(1,("%s: result=%d\n", __func__, (int)fresult));
556 
557 		switch (fresult) {
558 		case FR_IDLE:
559 		case FR_INPROGRESS:
560 		case FR_FRAMEBADFCS:
561 		case FR_FRAMEMALFORMED:
562 		case FR_BUFFEROVERRUN:
563 			break;
564 		case FR_FRAMEOK:
565 			sc->sc_ur_framelen = sc->sc_framestate.bufindex;
566 			wakeup(&sc->sc_ur_framelen); /* XXX should use flag */
567 			selnotify(&sc->sc_rd_sel, 0);
568 			return 1;
569 		}
570 	}
571 
572 	/* Reset indices into USB-side buffer */
573 	sc->sc_rd_index = sc->sc_rd_count = 0;
574 
575 	return 0;
576 }
577 
578 /*
579  * Direction transitions:
580  *
581  * ustir_periodic() can switch the direction from:
582  *
583  *	output -> idle
584  *	output -> stalled
585  *	stalled -> idle
586  *	idle -> input
587  *
588  * ustir_rd_cb() can switch the direction from:
589  *
590  *	input -> stalled
591  *	input -> idle
592  *
593  * ustir_write() can switch the direction from:
594  *
595  *	idle -> output
596  */
597 Static void
598 ustir_periodic(struct ustir_softc *sc)
599 {
600 	DPRINTFN(60, ("%s: direction = %d\n",
601 		      __func__, sc->sc_direction));
602 
603 	if (sc->sc_direction == udir_output ||
604 	    sc->sc_direction == udir_stalled) {
605 		usbd_status err;
606 		u_int8_t regval;
607 
608 		DPRINTFN(60, ("%s: reading status register\n",
609 			      __func__));
610 
611 		err = ustir_read_reg(sc, STIR_REG_STATUS,
612 				     &regval);
613 		if (err != USBD_NORMAL_COMPLETION) {
614 			printf("%s: status register read failed: %s\n",
615 			       USBDEVNAME(sc->sc_dev),
616 			       usbd_errstr(err));
617 		} else {
618 			DPRINTFN(10, ("%s: status register = 0x%x\n",
619 				      __func__,
620 				      (unsigned int)regval));
621 			if (sc->sc_direction == udir_output &&
622 			    !(regval & STIR_RSTATUS_FFDIR))
623 				/* Output has completed */
624 				sc->sc_direction = udir_idle;
625 			if (regval & STIR_RSTATUS_FFOVER) {
626 				/*
627 				 * On an overrun the FIFO hangs, and
628 				 * any data bulk transfers will stall.
629 				 * Reset the FIFO.
630 				 */
631 				sc->sc_direction = udir_stalled;
632 
633 				DPRINTFN(10, ("%s: clearing FIFO error\n",
634 					      __func__));
635 
636 				err = ustir_write_reg(sc, STIR_REG_STATUS,
637 						      STIR_RSTATUS_FFCLR);
638 				/* XXX if we fail partway through
639 				 * this, we may not recover? */
640 				if (err == USBD_NORMAL_COMPLETION)
641 					err = ustir_write_reg(sc,
642 							      STIR_REG_STATUS,
643 							      0);
644 				if (err != USBD_NORMAL_COMPLETION) {
645 					printf("%s: FIFO reset failed: %s\n",
646 					       USBDEVNAME(sc->sc_dev),
647 					       usbd_errstr(err));
648 				} else {
649 					/* FIFO reset */
650 					sc->sc_direction = udir_idle;
651 				}
652 			}
653 		}
654 	}
655 
656 	if (sc->sc_wr_stalewrite && sc->sc_direction == udir_idle) {
657 		/*
658 		 * In a stale write case, we need to check if the
659 		 * write has completed.  Once that has happened, the
660 		 * write is no longer stale.
661 		 *
662 		 * But note that we may immediately start a read poll...
663 		 */
664 		sc->sc_wr_stalewrite = 0;
665 		wakeup(&sc->sc_wr_buf);
666 	}
667 
668 	if (!sc->sc_rd_readinprogress &&
669 	    (sc->sc_direction == udir_idle ||
670 	     sc->sc_direction == udir_input))
671 		/* Do a read poll if appropriate... */
672 		ustir_start_read(sc);
673 }
674 
675 Static void
676 ustir_thread(void *arg)
677 {
678 	struct ustir_softc *sc = arg;
679 
680 	DPRINTFN(20, ("%s: starting polling thread\n", __func__));
681 
682 	while (!sc->sc_closing) {
683 		if (!sc->sc_rd_readinprogress && !USTIR_BLOCK_RX_DATA(sc))
684 			ustir_periodic(sc);
685 
686 		if (!sc->sc_closing) {
687 			int error;
688 			error = tsleep(&sc->sc_thread, PWAIT,
689 				       "ustir", hz / 10);
690 			if (error == EWOULDBLOCK &&
691 			    sc->sc_rd_expectdataticks > 0)
692 				/*
693 				 * After a timeout decrement the tick
694 				 * counter within which time we expect
695 				 * data to arrive if we are receiving
696 				 * data...
697 				 */
698 				sc->sc_rd_expectdataticks--;
699 		}
700 	}
701 
702 	DPRINTFN(20, ("%s: exiting polling thread\n", __func__));
703 
704 	sc->sc_thread = NULL;
705 
706 	wakeup(&sc->sc_closing);
707 
708 	if (--sc->sc_refcnt < 0)
709 		usb_detach_wakeup(USBDEV(sc->sc_dev));
710 
711 	kthread_exit(0);
712 }
713 
714 Static void
715 ustir_rd_cb(usbd_xfer_handle xfer, usbd_private_handle priv,
716 	    usbd_status status)
717 {
718 	struct ustir_softc *sc = priv;
719 	u_int32_t size;
720 
721 	DPRINTFN(60, ("%s: sc=%p\n", __func__, sc));
722 
723 	/* Read is no longer in progress */
724 	sc->sc_rd_readinprogress = 0;
725 
726 	if (status == USBD_CANCELLED || sc->sc_closing) /* this is normal */
727 		return;
728 	if (status) {
729 		size = 0;
730 		sc->sc_rd_err = 1;
731 
732 		if (sc->sc_direction == udir_input ||
733 		    sc->sc_direction == udir_idle) {
734 			/*
735 			 * Receive error, probably need to clear error
736 			 * condition.
737 			 */
738 			sc->sc_direction = udir_stalled;
739 		}
740 	} else {
741 		usbd_get_xfer_status(xfer, NULL, NULL, &size, NULL);
742 	}
743 
744 	sc->sc_rd_index = 0;
745 	sc->sc_rd_count = size;
746 
747 	DPRINTFN(((size > 0 || sc->sc_rd_err != 0) ? 20 : 60),
748 		 ("%s: sc=%p size=%u, err=%d\n", __func__,
749 		  sc, size, sc->sc_rd_err));
750 
751 #ifdef USTIR_DEBUG
752 	if (ustirdebug >= 20 && size > 0)
753 		ustir_dumpdata(sc->sc_rd_buf, size, __func__);
754 #endif
755 
756 	if (!deframe_rd_ur(sc)) {
757 		if (!deframe_isclear(&sc->sc_framestate) && size == 0 &&
758 		    sc->sc_rd_expectdataticks == 0) {
759 			/*
760 			 * Expected data, but didn't get it
761 			 * within expected time...
762 			 */
763 			DPRINTFN(5,("%s: incoming packet timeout\n",
764 				    __func__));
765 			deframe_clear(&sc->sc_framestate);
766 		} else if (size > 0) {
767 			/*
768 			 * If we also received actual data, reset the
769 			 * data read timeout and wake up the possibly
770 			 * sleeping thread...
771 			 */
772 			sc->sc_rd_expectdataticks = 2;
773 			wakeup(&sc->sc_thread);
774 		}
775 	}
776 
777 	/*
778 	 * Check if incoming data has stopped, or that we cannot
779 	 * safely read any more data.  In the case of the latter we
780 	 * must switch to idle so that a write will not block...
781 	 */
782 	if (sc->sc_direction == udir_input &&
783 	    ((size == 0 && sc->sc_rd_expectdataticks == 0) ||
784 	     USTIR_BLOCK_RX_DATA(sc))) {
785 		DPRINTFN(8,("%s: idling on packet timeout, "
786 			    "complete frame, or no data\n", __func__));
787 		sc->sc_direction = udir_idle;
788 
789 		/* Wake up for possible output */
790 		wakeup(&sc->sc_wr_buf);
791 		selnotify(&sc->sc_wr_sel, 0);
792 	}
793 }
794 
795 Static usbd_status
796 ustir_start_read(struct ustir_softc *sc)
797 {
798 	usbd_status err;
799 
800 	DPRINTFN(60,("%s: sc=%p, size=%d\n", __func__, sc,
801 		     sc->sc_params.maxsize));
802 
803 	if (sc->sc_dying)
804 		return USBD_IOERROR;
805 
806 	if (USTIR_BLOCK_RX_DATA(sc) || deframe_rd_ur(sc)) {
807 		/*
808 		 * Can't start reading just yet.  Since we aren't
809 		 * going to start a read, have to switch direction to
810 		 * idle.
811 		 */
812 		sc->sc_direction = udir_idle;
813 		return USBD_NORMAL_COMPLETION;
814 	}
815 
816 	/* Starting a read... */
817 	sc->sc_rd_readinprogress = 1;
818 	sc->sc_direction = udir_input;
819 
820 	if (sc->sc_rd_err) {
821 		sc->sc_rd_err = 0;
822 		DPRINTFN(0, ("%s: clear stall\n", __func__));
823 		usbd_clear_endpoint_stall(sc->sc_rd_pipe);
824 	}
825 
826 	usbd_setup_xfer(sc->sc_rd_xfer, sc->sc_rd_pipe, sc, sc->sc_rd_buf,
827 			sc->sc_params.maxsize,
828 			USBD_SHORT_XFER_OK | USBD_NO_COPY,
829 			USBD_NO_TIMEOUT, ustir_rd_cb);
830 	err = usbd_transfer(sc->sc_rd_xfer);
831 	if (err != USBD_IN_PROGRESS) {
832 		DPRINTFN(0, ("%s: err=%d\n", __func__, (int)err));
833 		return err;
834 	}
835 	return USBD_NORMAL_COMPLETION;
836 }
837 
838 Static int
839 ustir_activate(device_ptr_t self, enum devact act)
840 {
841 	struct ustir_softc *sc = (struct ustir_softc *)self;
842 	int error = 0;
843 
844 	switch (act) {
845 	case DVACT_ACTIVATE:
846 		return EOPNOTSUPP;
847 
848 	case DVACT_DEACTIVATE:
849 		sc->sc_dying = 1;
850 		if (sc->sc_child != NULL)
851 			error = config_deactivate(sc->sc_child);
852 		break;
853 	}
854 	return error;
855 }
856 
857 /* ARGSUSED */
858 Static int
859 ustir_open(void *h, int flag, int mode, usb_proc_ptr p)
860 {
861 	struct ustir_softc *sc = h;
862 	int error;
863 	usbd_status err;
864 
865 	DPRINTFN(0, ("%s: sc=%p\n", __func__, sc));
866 
867 	err = usbd_open_pipe(sc->sc_iface, sc->sc_rd_addr, 0, &sc->sc_rd_pipe);
868 	if (err != USBD_NORMAL_COMPLETION) {
869 		error = EIO;
870 		goto bad1;
871 	}
872 	err = usbd_open_pipe(sc->sc_iface, sc->sc_wr_addr, 0, &sc->sc_wr_pipe);
873 	if (err != USBD_NORMAL_COMPLETION) {
874 		error = EIO;
875 		goto bad2;
876 	}
877 	sc->sc_rd_xfer = usbd_alloc_xfer(sc->sc_udev);
878 	if (sc->sc_rd_xfer == NULL) {
879 		error = ENOMEM;
880 		goto bad3;
881 	}
882 	sc->sc_wr_xfer = usbd_alloc_xfer(sc->sc_udev);
883 	if (sc->sc_wr_xfer == NULL) {
884 		error = ENOMEM;
885 		goto bad4;
886 	}
887 	sc->sc_rd_buf = usbd_alloc_buffer(sc->sc_rd_xfer,
888 			    IRDA_MAX_FRAME_SIZE);
889 	if (sc->sc_rd_buf == NULL) {
890 		error = ENOMEM;
891 		goto bad5;
892 	}
893 	sc->sc_wr_buf = usbd_alloc_buffer(sc->sc_wr_xfer,
894 			    IRDA_MAX_FRAME_SIZE + STIR_OUTPUT_HEADER_SIZE);
895 	if (sc->sc_wr_buf == NULL) {
896 		error = ENOMEM;
897 		goto bad5;
898 	}
899 	sc->sc_ur_buf = malloc(IRDA_MAX_FRAME_SIZE, M_USBDEV, M_NOWAIT);
900 	if (sc->sc_ur_buf == NULL) {
901 		error = ENOMEM;
902 		goto bad5;
903 	}
904 
905 	sc->sc_rd_index = sc->sc_rd_count = 0;
906 	sc->sc_closing = 0;
907 	sc->sc_rd_readinprogress = 0;
908 	sc->sc_rd_expectdataticks = 0;
909 	sc->sc_ur_framelen = 0;
910 	sc->sc_rd_err = 0;
911 	sc->sc_wr_stalewrite = 0;
912 	sc->sc_speedrec = NULL;
913 	sc->sc_direction = udir_idle;
914 	sc->sc_params.speed = 0;
915 	sc->sc_params.ebofs = 0;
916 	sc->sc_params.maxsize = IRDA_MAX_FRAME_SIZE;
917 
918 	deframe_init(&sc->sc_framestate, &framedef_sir, sc->sc_ur_buf,
919 		     IRDA_MAX_FRAME_SIZE);
920 
921 	error = kthread_create1(ustir_thread, sc, &sc->sc_thread, "%s",
922 				sc->sc_dev.dv_xname);
923 	if (error)
924 		goto bad5;
925 	/* Increment reference for thread */
926 	sc->sc_refcnt++;
927 
928 	return 0;
929 
930  bad5:
931 	usbd_free_xfer(sc->sc_wr_xfer);
932 	sc->sc_wr_xfer = NULL;
933  bad4:
934 	usbd_free_xfer(sc->sc_rd_xfer);
935 	sc->sc_rd_xfer = NULL;
936  bad3:
937 	usbd_close_pipe(sc->sc_wr_pipe);
938 	sc->sc_wr_pipe = NULL;
939  bad2:
940 	usbd_close_pipe(sc->sc_rd_pipe);
941 	sc->sc_rd_pipe = NULL;
942  bad1:
943 	return error;
944 }
945 
946 /* ARGSUSED */
947 Static int
948 ustir_close(void *h, int flag, int mode, usb_proc_ptr p)
949 {
950 	struct ustir_softc *sc = h;
951 
952 	DPRINTFN(0, ("%s: sc=%p\n", __func__, sc));
953 
954 	sc->sc_refcnt++;
955 
956 	sc->sc_rd_readinprogress = 1;
957 	sc->sc_closing = 1;
958 
959 	wakeup(&sc->sc_thread);
960 
961 	while (sc->sc_thread != NULL)
962 		tsleep(&sc->sc_closing, PWAIT, "usircl", 0);
963 
964 	if (sc->sc_rd_pipe != NULL) {
965 		usbd_abort_pipe(sc->sc_rd_pipe);
966 		usbd_close_pipe(sc->sc_rd_pipe);
967 		sc->sc_rd_pipe = NULL;
968 	}
969 	if (sc->sc_wr_pipe != NULL) {
970 		usbd_abort_pipe(sc->sc_wr_pipe);
971 		usbd_close_pipe(sc->sc_wr_pipe);
972 		sc->sc_wr_pipe = NULL;
973 	}
974 	if (sc->sc_rd_xfer != NULL) {
975 		usbd_free_xfer(sc->sc_rd_xfer);
976 		sc->sc_rd_xfer = NULL;
977 		sc->sc_rd_buf = NULL;
978 	}
979 	if (sc->sc_wr_xfer != NULL) {
980 		usbd_free_xfer(sc->sc_wr_xfer);
981 		sc->sc_wr_xfer = NULL;
982 		sc->sc_wr_buf = NULL;
983 	}
984 	if (sc->sc_ur_buf != NULL) {
985 		free(sc->sc_ur_buf, M_USBDEV);
986 		sc->sc_ur_buf = NULL;
987 	}
988 
989 	if (--sc->sc_refcnt < 0)
990 		usb_detach_wakeup(USBDEV(sc->sc_dev));
991 
992 	return 0;
993 }
994 
995 /* ARGSUSED */
996 Static int
997 ustir_read(void *h, struct uio *uio, int flag)
998 {
999 	struct ustir_softc *sc = h;
1000 	int s;
1001 	int error;
1002 	u_int uframelen;
1003 
1004 	DPRINTFN(1,("%s: sc=%p\n", __func__, sc));
1005 
1006 	if (sc->sc_dying)
1007 		return EIO;
1008 
1009 #ifdef DIAGNOSTIC
1010 	if (sc->sc_rd_buf == NULL)
1011 		return EINVAL;
1012 #endif
1013 
1014 	sc->sc_refcnt++;
1015 
1016 	if (!sc->sc_rd_readinprogress && !USTIR_BLOCK_RX_DATA(sc))
1017 		/* Possibly wake up polling thread */
1018 		wakeup(&sc->sc_thread);
1019 
1020 	do {
1021 		s = splusb();
1022 		while (sc->sc_ur_framelen == 0) {
1023 			DPRINTFN(5,("%s: calling tsleep()\n", __func__));
1024 			error = tsleep(&sc->sc_ur_framelen, PZERO | PCATCH,
1025 				       "usirrd", 0);
1026 			if (sc->sc_dying)
1027 				error = EIO;
1028 			if (error) {
1029 				splx(s);
1030 				DPRINTFN(0, ("%s: tsleep() = %d\n",
1031 					     __func__, error));
1032 				goto ret;
1033 			}
1034 		}
1035 		splx(s);
1036 
1037 		uframelen = sc->sc_ur_framelen;
1038 		DPRINTFN(1,("%s: sc=%p framelen=%u, hdr=0x%02x\n",
1039 			    __func__, sc, uframelen, sc->sc_ur_buf[0]));
1040 		if (uframelen > uio->uio_resid)
1041 			error = EINVAL;
1042 		else
1043 			error = uiomove(sc->sc_ur_buf, uframelen, uio);
1044 		sc->sc_ur_framelen = 0;
1045 
1046 		if (!deframe_rd_ur(sc) && uframelen > 0) {
1047 			/*
1048 			 * Need to wait for another read to obtain a
1049 			 * complete frame...  If we also obtained
1050 			 * actual data, wake up the possibly sleeping
1051 			 * thread immediately...
1052 			 */
1053 			wakeup(&sc->sc_thread);
1054 		}
1055 	} while (uframelen == 0);
1056 
1057 	DPRINTFN(1,("%s: return %d\n", __func__, error));
1058 
1059  ret:
1060 	if (--sc->sc_refcnt < 0)
1061 		usb_detach_wakeup(USBDEV(sc->sc_dev));
1062 	return error;
1063 }
1064 
1065 /* ARGSUSED */
1066 Static int
1067 ustir_write(void *h, struct uio *uio, int flag)
1068 {
1069 	struct ustir_softc *sc = h;
1070 	usbd_status err;
1071 	u_int32_t wrlen;
1072 	int error, sirlength;
1073 	u_int8_t *wrbuf;
1074 	int s;
1075 
1076 	DPRINTFN(1,("%s: sc=%p\n", __func__, sc));
1077 
1078 	if (sc->sc_dying)
1079 		return EIO;
1080 
1081 #ifdef DIAGNOSTIC
1082 	if (sc->sc_wr_buf == NULL)
1083 		return EINVAL;
1084 #endif
1085 
1086 	wrlen = uio->uio_resid;
1087 	if (wrlen > sc->sc_params.maxsize)
1088 		return EINVAL;
1089 
1090 	sc->sc_refcnt++;
1091 
1092 	if (!USTIR_BLOCK_RX_DATA(sc)) {
1093 		/*
1094 		 * If reads are not blocked, determine what action we
1095 		 * should potentially take...
1096 		 */
1097 		if (sc->sc_direction == udir_output) {
1098 			/*
1099 			 * If the last operation was an output, wait for the
1100 			 * polling thread to check for incoming data.
1101 			 */
1102 			sc->sc_wr_stalewrite = 1;
1103 			wakeup(&sc->sc_thread);
1104 		} else if (!sc->sc_rd_readinprogress &&
1105 			   (sc->sc_direction == udir_idle ||
1106 			    sc->sc_direction == udir_input)) {
1107 			/* If idle, check for input before outputting */
1108 			ustir_start_read(sc);
1109 		}
1110 	}
1111 
1112 	s = splusb();
1113 	while (sc->sc_wr_stalewrite ||
1114 	       (sc->sc_direction != udir_output &&
1115 		sc->sc_direction != udir_idle)) {
1116 		DPRINTFN(5, ("%s: sc=%p stalewrite=%d direction=%d, "
1117 			     "calling tsleep()\n", __func__,
1118 			     sc, sc->sc_wr_stalewrite, sc->sc_direction));
1119 		error = tsleep(&sc->sc_wr_buf, PZERO | PCATCH,
1120 			       "usirwr", 0);
1121 		if (sc->sc_dying)
1122 			error = EIO;
1123 		if (error) {
1124 			splx(s);
1125 			DPRINTFN(0, ("%s: tsleep() = %d\n", __func__,
1126 				     error));
1127 			goto ret;
1128 		}
1129 	}
1130 	splx(s);
1131 
1132 	wrbuf = sc->sc_wr_buf;
1133 
1134 	/* Build header */
1135 	wrbuf[0] = STIR_OUTPUT_HEADER_BYTE0;
1136 	wrbuf[1] = STIR_OUTPUT_HEADER_BYTE1;
1137 
1138 	sirlength = irda_sir_frame(&wrbuf[STIR_OUTPUT_HEADER_SIZE],
1139 				   MAX_USTIR_OUTPUT_FRAME -
1140 				   STIR_OUTPUT_HEADER_SIZE,
1141 				   uio, sc->sc_params.ebofs);
1142 	if (sirlength < 0) {
1143 		error = -sirlength;
1144 	} else {
1145 		u_int32_t btlen;
1146 
1147 		DPRINTFN(1, ("%s: transfer %u bytes\n", __func__,
1148 			     (unsigned int)wrlen));
1149 
1150 		wrbuf[2] = sirlength & 0xff;
1151 		wrbuf[3] = (sirlength >> 8) & 0xff;
1152 
1153 		btlen = STIR_OUTPUT_HEADER_SIZE + sirlength;
1154 
1155 		sc->sc_direction = udir_output;
1156 
1157 #ifdef USTIR_DEBUG
1158 		if (ustirdebug >= 20)
1159 			ustir_dumpdata(wrbuf, btlen, __func__);
1160 #endif
1161 
1162 		err = usbd_bulk_transfer(sc->sc_wr_xfer, sc->sc_wr_pipe,
1163 					 USBD_FORCE_SHORT_XFER | USBD_NO_COPY,
1164 					 USTIR_WR_TIMEOUT,
1165 					 wrbuf, &btlen, "ustiwr");
1166 		DPRINTFN(2, ("%s: err=%d\n", __func__, err));
1167 		if (err != USBD_NORMAL_COMPLETION) {
1168 			if (err == USBD_INTERRUPTED)
1169 				error = EINTR;
1170 			else if (err == USBD_TIMEOUT)
1171 				error = ETIMEDOUT;
1172 			else
1173 				error = EIO;
1174 		} else {
1175 			error = 0;
1176 		}
1177 	}
1178 
1179  ret:
1180 	if (--sc->sc_refcnt < 0)
1181 		usb_detach_wakeup(USBDEV(sc->sc_dev));
1182 
1183 	DPRINTFN(1,("%s: sc=%p done\n", __func__, sc));
1184 	return error;
1185 }
1186 
1187 Static int
1188 ustir_poll(void *h, int events, usb_proc_ptr p)
1189 {
1190 	struct ustir_softc *sc = h;
1191 	int revents = 0;
1192 
1193 	DPRINTFN(1,("%s: sc=%p\n", __func__, sc));
1194 
1195 	if (events & (POLLOUT | POLLWRNORM)) {
1196 		if (sc->sc_direction != udir_input) {
1197 			revents |= events & (POLLOUT | POLLWRNORM);
1198 		} else {
1199 			DPRINTFN(2,("%s: recording write select\n",
1200 				    __func__));
1201 			selrecord(p, &sc->sc_wr_sel);
1202 		}
1203 	}
1204 
1205 	if (events & (POLLIN | POLLRDNORM)) {
1206 		if (sc->sc_ur_framelen != 0) {
1207 			DPRINTFN(2,("%s: have data\n", __func__));
1208 			revents |= events & (POLLIN | POLLRDNORM);
1209 		} else {
1210 			DPRINTFN(2,("%s: recording read select\n",
1211 				    __func__));
1212 			selrecord(p, &sc->sc_rd_sel);
1213 		}
1214 	}
1215 
1216 	return revents;
1217 }
1218 
1219 static void
1220 filt_ustirrdetach(struct knote *kn)
1221 {
1222 	struct ustir_softc *sc = kn->kn_hook;
1223 	int s;
1224 
1225 	s = splusb();
1226 	SLIST_REMOVE(&sc->sc_rd_sel.sel_klist, kn, knote, kn_selnext);
1227 	splx(s);
1228 }
1229 
1230 /* ARGSUSED */
1231 static int
1232 filt_ustirread(struct knote *kn, long hint)
1233 {
1234 	struct ustir_softc *sc = kn->kn_hook;
1235 
1236 	kn->kn_data = sc->sc_ur_framelen;
1237 	return (kn->kn_data > 0);
1238 }
1239 
1240 static void
1241 filt_ustirwdetach(struct knote *kn)
1242 {
1243 	struct ustir_softc *sc = kn->kn_hook;
1244 	int s;
1245 
1246 	s = splusb();
1247 	SLIST_REMOVE(&sc->sc_wr_sel.sel_klist, kn, knote, kn_selnext);
1248 	splx(s);
1249 }
1250 
1251 /* ARGSUSED */
1252 static int
1253 filt_ustirwrite(struct knote *kn, long hint)
1254 {
1255 	struct ustir_softc *sc = kn->kn_hook;
1256 
1257 	kn->kn_data = 0;
1258 	return (sc->sc_direction != udir_input);
1259 }
1260 
1261 static const struct filterops ustirread_filtops =
1262 	{ 1, NULL, filt_ustirrdetach, filt_ustirread };
1263 static const struct filterops ustirwrite_filtops =
1264 	{ 1, NULL, filt_ustirwdetach, filt_ustirwrite };
1265 
1266 Static int
1267 ustir_kqfilter(void *h, struct knote *kn)
1268 {
1269 	struct ustir_softc *sc = h;
1270 	struct klist *klist;
1271 	int s;
1272 
1273 	switch (kn->kn_filter) {
1274 	case EVFILT_READ:
1275 		klist = &sc->sc_rd_sel.sel_klist;
1276 		kn->kn_fop = &ustirread_filtops;
1277 		break;
1278 	case EVFILT_WRITE:
1279 		klist = &sc->sc_wr_sel.sel_klist;
1280 		kn->kn_fop = &ustirwrite_filtops;
1281 		break;
1282 	default:
1283 		return (1);
1284 	}
1285 
1286 	kn->kn_hook = sc;
1287 
1288 	s = splusb();
1289 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
1290 	splx(s);
1291 
1292 	return (0);
1293 }
1294 
1295 #ifdef USTIR_DEBUG_IOCTLS
1296 Static int ustir_ioctl(void *h, u_long cmd, caddr_t addr, int flag, usb_proc_ptr p)
1297 {
1298 	struct ustir_softc *sc = h;
1299 	int error;
1300 	unsigned int regnum;
1301 	usbd_status err;
1302 	u_int8_t regdata;
1303 
1304 	if (sc->sc_dying)
1305 		return EIO;
1306 
1307 	sc->sc_refcnt++;
1308 
1309 	error = 0;
1310 	switch (cmd) {
1311 	case USTIR_READ_REGISTER:
1312 		regnum = *(unsigned int *)addr;
1313 
1314 		if (regnum > STIR_MAX_REG) {
1315 			error = EINVAL;
1316 			break;
1317 		}
1318 
1319 		err = ustir_read_reg(sc, regnum, &regdata);
1320 
1321 		DPRINTFN(10, ("%s: regget(%u) = 0x%x\n", __func__,
1322 			      regnum, (unsigned int)regdata));
1323 
1324 		*(unsigned int *)addr = regdata;
1325 		if (err != USBD_NORMAL_COMPLETION) {
1326 			printf("%s: register read failed: %s\n",
1327 			       USBDEVNAME(sc->sc_dev),
1328 			       usbd_errstr(err));
1329 			error = EIO;
1330 		}
1331 		break;
1332 
1333 	case USTIR_WRITE_REGISTER:
1334 		regnum = *(unsigned int *)addr;
1335 		regdata = (regnum >> 8) & 0xff;
1336 		regnum = regnum & 0xff;
1337 
1338 		if (regnum > STIR_MAX_REG) {
1339 			error = EINVAL;
1340 			break;
1341 		}
1342 
1343 		DPRINTFN(10, ("%s: regset(%u, 0x%x)\n", __func__,
1344 			      regnum, (unsigned int)regdata));
1345 
1346 		err = ustir_write_reg(sc, regnum, regdata);
1347 		if (err != USBD_NORMAL_COMPLETION) {
1348 			printf("%s: register write failed: %s\n",
1349 			       USBDEVNAME(sc->sc_dev),
1350 			       usbd_errstr(err));
1351 			error = EIO;
1352 		}
1353 		break;
1354 
1355 	case USTIR_DEBUG_LEVEL:
1356 #ifdef USTIR_DEBUG
1357 		ustirdebug = *(int *)addr;
1358 #endif
1359 		break;
1360 
1361 	case USTIR_DEBUG_OPERATION:
1362 		break;
1363 
1364 	default:
1365 		error = EINVAL;
1366 		break;
1367 	}
1368 
1369 	if (--sc->sc_refcnt < 0)
1370 		usb_detach_wakeup(USBDEV(sc->sc_dev));
1371 
1372 	return error;
1373 }
1374 #endif
1375 
1376 Static int
1377 ustir_set_params(void *h, struct irda_params *p)
1378 {
1379 	struct ustir_softc *sc = h;
1380 	struct ustir_speedrec const *speedblk;
1381 	int i;
1382 
1383 	DPRINTFN(0, ("%s: sc=%p, speed=%d ebofs=%d maxsize=%d\n", __func__,
1384 		     sc, p->speed, p->ebofs, p->maxsize));
1385 
1386 	if (sc->sc_dying)
1387 		return EIO;
1388 
1389 	speedblk = NULL;
1390 
1391 	if (sc->sc_speedrec == NULL || p->speed != sc->sc_speedrec->speed) {
1392 		/* find speed */
1393 		for (i = 0; i < USTIR_NSPEEDS; i++) {
1394 			if (ustir_speeds[i].speed == p->speed) {
1395 				speedblk = &ustir_speeds[i];
1396 				goto found2;
1397 			}
1398 		}
1399 		/* no good value found */
1400 		return EINVAL;
1401 	found2:
1402 		;
1403 	}
1404 	if (p->maxsize != sc->sc_params.maxsize) {
1405 		if (p->maxsize > IRDA_MAX_FRAME_SIZE)
1406 			return EINVAL;
1407 		sc->sc_params.maxsize = p->maxsize;
1408 	}
1409 
1410 	sc->sc_params = *p;
1411 
1412 	if (speedblk != NULL) {
1413 		usbd_status err;
1414 		u_int8_t regmode;
1415 		u_int8_t regbrate;
1416 
1417 		sc->sc_speedrec = speedblk;
1418 
1419 		regmode = STIR_BRMODE_MODEREG(speedblk->config);
1420 		regbrate = STIR_BRMODE_BRATEREG(speedblk->config);
1421 
1422 		/*
1423 		 * FFSPRST must be set to enable the FIFO.
1424 		 */
1425 		regmode |= STIR_RMODE_FFSPRST;
1426 
1427 		DPRINTFN(10, ("%s: setting BRATE = %x\n", __func__,
1428 			      (unsigned int)regbrate));
1429 		err = ustir_write_reg(sc, STIR_REG_BRATE, regbrate);
1430 		if (err == USBD_NORMAL_COMPLETION) {
1431 			DPRINTFN(10, ("%s: setting MODE = %x\n", __func__,
1432 				      (unsigned int)regmode));
1433 			err = ustir_write_reg(sc, STIR_REG_MODE, regmode);
1434 		}
1435 		if (err != USBD_NORMAL_COMPLETION) {
1436 			DPRINTFN(10, ("%s: error setting register: %s\n",
1437 				      __func__, usbd_errstr(err)));
1438 			return EIO;
1439 		}
1440 	}
1441 
1442 	return 0;
1443 }
1444 
1445 Static int
1446 ustir_get_speeds(void *h, int *speeds)
1447 {
1448 	struct ustir_softc *sc = h;
1449 
1450 	DPRINTFN(0, ("%s: sc=%p\n", __func__, sc));
1451 
1452 	if (sc->sc_dying)
1453 		return EIO;
1454 
1455 	/* All these speeds are supported */
1456 	*speeds = IRDA_SPEED_4000000 |
1457 		IRDA_SPEED_1152000 |
1458 		IRDA_SPEED_576000 |
1459 		IRDA_SPEED_115200 |
1460 		IRDA_SPEED_57600 |
1461 		IRDA_SPEED_38400 |
1462 		IRDA_SPEED_19200 |
1463 		IRDA_SPEED_9600 |
1464 		IRDA_SPEED_2400;
1465 
1466 	return 0;
1467 }
1468 
1469 Static int
1470 ustir_get_turnarounds(void *h, int *turnarounds)
1471 {
1472 	struct ustir_softc *sc = h;
1473 
1474 	DPRINTFN(0, ("%s: sc=%p\n", __func__, sc));
1475 
1476 	if (sc->sc_dying)
1477 		return EIO;
1478 
1479 	/*
1480 	 * Documentation is on the light side with respect to
1481 	 * turnaround time for this device.
1482 	 */
1483 	*turnarounds = IRDA_TURNT_10000;
1484 
1485 	return 0;
1486 }
1487