Home | History | Annotate | Line # | Download | only in usb
ulpt.c revision 1.79.6.1
      1 /*	$NetBSD: ulpt.c,v 1.79.6.1 2008/04/05 23:33:23 mjf Exp $	*/
      2 /*	$FreeBSD: src/sys/dev/usb/ulpt.c,v 1.24 1999/11/17 22:33:44 n_hibma Exp $	*/
      3 
      4 /*
      5  * Copyright (c) 1998, 2003 The NetBSD Foundation, Inc.
      6  * All rights reserved.
      7  *
      8  * This code is derived from software contributed to The NetBSD Foundation
      9  * by Lennart Augustsson (lennart (at) augustsson.net) at
     10  * Carlstedt Research & Technology.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *        This product includes software developed by the NetBSD
     23  *        Foundation, Inc. and its contributors.
     24  * 4. Neither the name of The NetBSD Foundation nor the names of its
     25  *    contributors may be used to endorse or promote products derived
     26  *    from this software without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     29  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     30  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     31  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     32  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     38  * POSSIBILITY OF SUCH DAMAGE.
     39  */
     40 
     41 /*
     42  * Printer Class spec: http://www.usb.org/developers/data/devclass/usbprint109.PDF
     43  */
     44 
     45 #include <sys/cdefs.h>
     46 __KERNEL_RCSID(0, "$NetBSD: ulpt.c,v 1.79.6.1 2008/04/05 23:33:23 mjf Exp $");
     47 
     48 #include <sys/param.h>
     49 #include <sys/systm.h>
     50 #include <sys/proc.h>
     51 #include <sys/kernel.h>
     52 #include <sys/fcntl.h>
     53 #if defined(__NetBSD__) || defined(__OpenBSD__)
     54 #include <sys/device.h>
     55 #include <sys/ioctl.h>
     56 #elif defined(__FreeBSD__)
     57 #include <sys/ioccom.h>
     58 #include <sys/module.h>
     59 #include <sys/bus.h>
     60 #endif
     61 #include <sys/uio.h>
     62 #include <sys/conf.h>
     63 #include <sys/vnode.h>
     64 #include <sys/syslog.h>
     65 
     66 #include <machine/vmparam.h>	/* PAGE_SIZE */
     67 
     68 #include <dev/usb/usb.h>
     69 #include <dev/usb/usbdi.h>
     70 #include <dev/usb/usbdi_util.h>
     71 #include <dev/usb/usbdevs.h>
     72 #include <dev/usb/usb_quirks.h>
     73 
     74 #define	TIMEOUT		hz*16	/* wait up to 16 seconds for a ready */
     75 #define	STEP		hz/4
     76 
     77 #define	LPTPRI		(PZERO+8)
     78 #define	ULPT_BSIZE	PAGE_SIZE
     79 
     80 #define ULPT_READS_PER_SEC 5
     81 /* XXX Why is 10 us a reasonable value? */
     82 #define ULPT_READ_TIMO 10
     83 
     84 #ifdef ULPT_DEBUG
     85 #define DPRINTFN(n,x)	if (ulptdebug>=(n)) logprintf x
     86 int	ulptdebug = 0;
     87 /*
     88  * The strategy for debug levels is:
     89  *   1: attach-time operations
     90  *   2: open/close/status/reset
     91  *   3: read/write basic
     92  *   4: read/write details
     93  *  10: left over from previous debug code
     94  */
     95 #else
     96 #define DPRINTFN(n,x)
     97 #endif
     98 
     99 #define UR_GET_DEVICE_ID 0
    100 #define UR_GET_PORT_STATUS 1
    101 #define UR_SOFT_RESET 2
    102 
    103 #define	LPS_NERR		0x08	/* printer no error */
    104 #define	LPS_SELECT		0x10	/* printer selected */
    105 #define	LPS_NOPAPER		0x20	/* printer out of paper */
    106 #define LPS_INVERT      (LPS_SELECT|LPS_NERR)
    107 #define LPS_MASK        (LPS_SELECT|LPS_NERR|LPS_NOPAPER)
    108 
    109 struct ulpt_softc {
    110 	USBBASEDEVICE sc_dev;
    111 	usbd_device_handle sc_udev;	/* device */
    112 	usbd_interface_handle sc_iface;	/* interface */
    113 	int sc_ifaceno;
    114 
    115 	int sc_out;
    116 	usbd_pipe_handle sc_out_pipe;	/* bulk out pipe */
    117 	usbd_xfer_handle sc_out_xfer;
    118 	void *sc_out_buf;
    119 
    120 	int sc_in;
    121 	usbd_pipe_handle sc_in_pipe;	/* bulk in pipe */
    122 	usbd_xfer_handle sc_in_xfer;
    123 	void *sc_in_buf;
    124 
    125 	usb_callout_t sc_read_callout;	/* to drain input on write-only opens */
    126 	int sc_has_callout;
    127 
    128 	u_char sc_state;
    129 #define	ULPT_OPEN	0x01	/* device is open */
    130 #define	ULPT_OBUSY	0x02	/* printer is busy doing output */
    131 #define	ULPT_INIT	0x04	/* waiting to initialize for open */
    132 	u_char sc_flags;
    133 #define	ULPT_NOPRIME	0x40	/* don't prime on open */
    134 	u_char sc_laststatus;
    135 
    136 	int sc_refcnt;
    137 	u_char sc_dying;
    138 
    139 #if defined(__FreeBSD__)
    140 	dev_t dev;
    141 	dev_t dev_noprime;
    142 #endif
    143 };
    144 
    145 #if defined(__NetBSD__)
    146 dev_type_open(ulptopen);
    147 dev_type_close(ulptclose);
    148 dev_type_write(ulptwrite);
    149 dev_type_read(ulptread);
    150 dev_type_ioctl(ulptioctl);
    151 
    152 const struct cdevsw ulpt_cdevsw = {
    153 	ulptopen, ulptclose, ulptread, ulptwrite, ulptioctl,
    154 	nostop, notty, nopoll, nommap, nokqfilter, D_OTHER,
    155 };
    156 #elif defined(__OpenBSD__)
    157 cdev_decl(ulpt);
    158 #elif defined(__FreeBSD__)
    159 Static d_open_t ulptopen;
    160 Static d_close_t ulptclose;
    161 Static d_write_t ulptwrite;
    162 Static d_ioctl_t ulptioctl;
    163 
    164 #define ULPT_CDEV_MAJOR 113
    165 
    166 Static struct cdevsw ulpt_cdevsw = {
    167 	/* open */	ulptopen,
    168 	/* close */	ulptclose,
    169 	/* read */	noread,
    170 	/* write */	ulptwrite,
    171 	/* ioctl */	ulptioctl,
    172 	/* poll */	nopoll,
    173 	/* mmap */	nommap,
    174 	/* strategy */	nostrategy,
    175 	/* name */	"ulpt",
    176 	/* maj */	ULPT_CDEV_MAJOR,
    177 	/* dump */	nodump,
    178 	/* psize */	nopsize,
    179 	/* flags */	0,
    180 #if !defined(__FreeBSD__) || (__FreeBSD__ < 5)
    181 	/* bmaj */	-1
    182 #endif
    183 };
    184 #endif
    185 
    186 void ulpt_disco(void *);
    187 
    188 int ulpt_do_write(struct ulpt_softc *, struct uio *uio, int);
    189 int ulpt_do_read(struct ulpt_softc *, struct uio *uio, int);
    190 int ulpt_status(struct ulpt_softc *);
    191 void ulpt_reset(struct ulpt_softc *);
    192 int ulpt_statusmsg(u_char, struct ulpt_softc *);
    193 void ulpt_read_cb(usbd_xfer_handle xfer, usbd_private_handle priv,
    194 		  usbd_status status);
    195 void ulpt_tick(void *xsc);
    196 
    197 #if 0
    198 void ieee1284_print_id(char *);
    199 #endif
    200 
    201 #define	ULPTUNIT(s)	(minor(s) & 0x1f)
    202 #define	ULPTFLAGS(s)	(minor(s) & 0xe0)
    203 #define ULPTRESET(s)	((s) + 64)
    204 
    205 
    206 USB_DECLARE_DRIVER(ulpt);
    207 
    208 USB_MATCH(ulpt)
    209 {
    210 	USB_IFMATCH_START(ulpt, uaa);
    211 
    212 	/* XXX Print something useful, or don't. */
    213 	DPRINTFN(10,("ulpt_match\n"));
    214 
    215 	if (uaa->class == UICLASS_PRINTER &&
    216 	    uaa->subclass == UISUBCLASS_PRINTER &&
    217 	    (uaa->proto == UIPROTO_PRINTER_UNI ||
    218 	     uaa->proto == UIPROTO_PRINTER_BI ||
    219 	     uaa->proto == UIPROTO_PRINTER_1284))
    220 		return (UMATCH_IFACECLASS_IFACESUBCLASS_IFACEPROTO);
    221 	return (UMATCH_NONE);
    222 }
    223 
    224 USB_ATTACH(ulpt)
    225 {
    226 	USB_IFATTACH_START(ulpt, sc, uaa);
    227 	usbd_device_handle dev = uaa->device;
    228 	usbd_interface_handle iface = uaa->iface;
    229 	usb_interface_descriptor_t *ifcd = usbd_get_interface_descriptor(iface);
    230 	const usb_interface_descriptor_t *id;
    231 	usbd_status err;
    232 	char *devinfop;
    233 	usb_endpoint_descriptor_t *ed;
    234 	u_int8_t epcount;
    235 	int i, altno, maj;
    236 	usbd_desc_iter_t iter;
    237 
    238 	devinfop = usbd_devinfo_alloc(dev, 0);
    239 	USB_ATTACH_SETUP;
    240 	printf("%s: %s, iclass %d/%d\n", USBDEVNAME(sc->sc_dev),
    241 	       devinfop, ifcd->bInterfaceClass, ifcd->bInterfaceSubClass);
    242 	usbd_devinfo_free(devinfop);
    243 
    244 	/* Loop through descriptors looking for a bidir mode. */
    245 	usb_desc_iter_init(dev, &iter);
    246 	for (altno = 0;;) {
    247 		id = (const usb_interface_descriptor_t *)usb_desc_iter_next(&iter);
    248 		if (!id)
    249 			break;
    250 		if (id->bDescriptorType == UDESC_INTERFACE &&
    251 		    id->bInterfaceNumber == ifcd->bInterfaceNumber) {
    252 			if (id->bInterfaceClass == UICLASS_PRINTER &&
    253 			    id->bInterfaceSubClass == UISUBCLASS_PRINTER &&
    254 			    (id->bInterfaceProtocol == UIPROTO_PRINTER_BI /*||
    255 			     id->bInterfaceProtocol == UIPROTO_PRINTER_1284*/))
    256 				goto found;
    257 			altno++;
    258 		}
    259 	}
    260 	id = ifcd;		/* not found, use original */
    261  found:
    262 	if (id != ifcd) {
    263 		/* Found a new bidir setting */
    264 		DPRINTFN(1, ("ulpt_attach: set altno = %d\n", altno));
    265 		err = usbd_set_interface(iface, altno);
    266 		if (err) {
    267 			printf("%s: setting alternate interface failed\n",
    268 			       USBDEVNAME(sc->sc_dev));
    269 			sc->sc_dying = 1;
    270 			USB_ATTACH_ERROR_RETURN;
    271 		}
    272 	}
    273 
    274 	epcount = 0;
    275 	(void)usbd_endpoint_count(iface, &epcount);
    276 
    277 	sc->sc_in = -1;
    278 	sc->sc_out = -1;
    279 	for (i = 0; i < epcount; i++) {
    280 		ed = usbd_interface2endpoint_descriptor(iface, i);
    281 		if (ed == NULL) {
    282 			printf("%s: couldn't get ep %d\n",
    283 			    USBDEVNAME(sc->sc_dev), i);
    284 			USB_ATTACH_ERROR_RETURN;
    285 		}
    286 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
    287 		    UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
    288 			sc->sc_in = ed->bEndpointAddress;
    289 		} else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT &&
    290 			   UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
    291 			sc->sc_out = ed->bEndpointAddress;
    292 		}
    293 	}
    294 	if (sc->sc_out == -1) {
    295 		printf("%s: could not find bulk out endpoint\n",
    296 		    USBDEVNAME(sc->sc_dev));
    297 		sc->sc_dying = 1;
    298 		USB_ATTACH_ERROR_RETURN;
    299 	}
    300 
    301 	if (usbd_get_quirks(dev)->uq_flags & UQ_BROKEN_BIDIR) {
    302 		/* This device doesn't handle reading properly. */
    303 		sc->sc_in = -1;
    304 	}
    305 
    306 	printf("%s: using %s-directional mode\n", USBDEVNAME(sc->sc_dev),
    307 	       sc->sc_in >= 0 ? "bi" : "uni");
    308 
    309 	sc->sc_iface = iface;
    310 	sc->sc_ifaceno = id->bInterfaceNumber;
    311 	sc->sc_udev = dev;
    312 
    313 #if 0
    314 /*
    315  * This code is disabled because for some mysterious reason it causes
    316  * printing not to work.  But only sometimes, and mostly with
    317  * UHCI and less often with OHCI.  *sigh*
    318  */
    319 	{
    320 	usb_config_descriptor_t *cd = usbd_get_config_descriptor(dev);
    321 	usb_device_request_t req;
    322 	int len, alen;
    323 
    324 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
    325 	req.bRequest = UR_GET_DEVICE_ID;
    326 	USETW(req.wValue, cd->bConfigurationValue);
    327 	USETW2(req.wIndex, id->bInterfaceNumber, id->bAlternateSetting);
    328 	USETW(req.wLength, DEVINFOSIZE - 1);
    329 	err = usbd_do_request_flags(dev, &req, devinfop, USBD_SHORT_XFER_OK,
    330 		  &alen, USBD_DEFAULT_TIMEOUT);
    331 	if (err) {
    332 		printf("%s: cannot get device id\n", USBDEVNAME(sc->sc_dev));
    333 	} else if (alen <= 2) {
    334 		printf("%s: empty device id, no printer connected?\n",
    335 		       USBDEVNAME(sc->sc_dev));
    336 	} else {
    337 		/* devinfop now contains an IEEE-1284 device ID */
    338 		len = ((devinfop[0] & 0xff) << 8) | (devinfop[1] & 0xff);
    339 		if (len > DEVINFOSIZE - 3)
    340 			len = DEVINFOSIZE - 3;
    341 		devinfop[len] = 0;
    342 		printf("%s: device id <", USBDEVNAME(sc->sc_dev));
    343 		ieee1284_print_id(devinfop+2);
    344 		printf(">\n");
    345 	}
    346 	}
    347 #endif
    348 
    349 #if defined(__FreeBSD__)
    350 	sc->dev = make_dev(&ulpt_cdevsw, device_get_unit(self),
    351 		UID_ROOT, GID_OPERATOR, 0644, "ulpt%d", device_get_unit(self));
    352 	sc->dev_noprime = make_dev(&ulpt_cdevsw,
    353 		device_get_unit(self)|ULPT_NOPRIME,
    354 		UID_ROOT, GID_OPERATOR, 0644, "unlpt%d", device_get_unit(self));
    355 #endif
    356 
    357 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev,
    358 			   USBDEV(sc->sc_dev));
    359 
    360 	DPRINTFN(1, ("ulpt_attach: sc=%p in=%d out=%d\n",
    361 		     sc, sc->sc_out, sc->sc_in));
    362 
    363 	maj = cdevsw_lookup_major(&ulpt_cdevsw);
    364 	device_register_name(makedev(maj, device_unit(self)), self, true,
    365 	    DEV_OTHER, "ulpt%d", device_unit(self));
    366 	device_register_name(makedev(maj, ULPTRESET(device_unit(self))),
    367 	    self, true, DEV_OTHER, "ulpn%d", device_unit(self));
    368 
    369 	USB_ATTACH_SUCCESS_RETURN;
    370 }
    371 
    372 #if defined(__NetBSD__) || defined(__OpenBSD__)
    373 int
    374 ulpt_activate(device_ptr_t self, enum devact act)
    375 {
    376 	struct ulpt_softc *sc = (struct ulpt_softc *)self;
    377 
    378 	switch (act) {
    379 	case DVACT_ACTIVATE:
    380 		return (EOPNOTSUPP);
    381 
    382 	case DVACT_DEACTIVATE:
    383 		sc->sc_dying = 1;
    384 		break;
    385 	}
    386 	return (0);
    387 }
    388 #endif
    389 
    390 USB_DETACH(ulpt)
    391 {
    392 	USB_DETACH_START(ulpt, sc);
    393 	int s;
    394 #if defined(__NetBSD__) || defined(__OpenBSD__)
    395 	int maj, mn;
    396 #elif defined(__FreeBSD__)
    397 	struct vnode *vp;
    398 #endif
    399 
    400 	DPRINTFN(1, ("ulpt_detach: sc=%p\n", sc));
    401 
    402 	device_unregister_all(self);
    403 
    404 	sc->sc_dying = 1;
    405 	if (sc->sc_out_pipe != NULL)
    406 		usbd_abort_pipe(sc->sc_out_pipe);
    407 	if (sc->sc_in_pipe != NULL)
    408 		usbd_abort_pipe(sc->sc_in_pipe);
    409 
    410 	s = splusb();
    411 	if (--sc->sc_refcnt >= 0) {
    412 		/* There is noone to wake, aborting the pipe is enough */
    413 		/* Wait for processes to go away. */
    414 		usb_detach_wait(USBDEV(sc->sc_dev));
    415 	}
    416 	splx(s);
    417 
    418 #if defined(__NetBSD__) || defined(__OpenBSD__)
    419 	/* locate the major number */
    420 #if defined(__NetBSD__)
    421 	maj = cdevsw_lookup_major(&ulpt_cdevsw);
    422 #elif defined(__OpenBSD__)
    423 	for (maj = 0; maj < nchrdev; maj++)
    424 		if (cdevsw[maj].d_open == ulptopen)
    425 			break;
    426 #endif
    427 
    428 	/* Nuke the vnodes for any open instances (calls close). */
    429 	mn = device_unit(self);
    430 	vdevgone(maj, mn, mn, VCHR);
    431 	vdevgone(maj, mn | ULPT_NOPRIME , mn | ULPT_NOPRIME, VCHR);
    432 #elif defined(__FreeBSD__)
    433 	vp = SLIST_FIRST(&sc->dev->si_hlist);
    434 	if (vp)
    435 		VOP_REVOKE(vp, REVOKEALL);
    436 	vp = SLIST_FIRST(&sc->dev_noprime->si_hlist);
    437 	if (vp)
    438 		VOP_REVOKE(vp, REVOKEALL);
    439 
    440 	destroy_dev(sc->dev);
    441 	destroy_dev(sc->dev_noprime);
    442 #endif
    443 
    444 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev,
    445 			   USBDEV(sc->sc_dev));
    446 
    447 	return (0);
    448 }
    449 
    450 int
    451 ulpt_status(struct ulpt_softc *sc)
    452 {
    453 	usb_device_request_t req;
    454 	usbd_status err;
    455 	u_char status;
    456 
    457 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
    458 	req.bRequest = UR_GET_PORT_STATUS;
    459 	USETW(req.wValue, 0);
    460 	USETW(req.wIndex, sc->sc_ifaceno);
    461 	USETW(req.wLength, 1);
    462 	err = usbd_do_request(sc->sc_udev, &req, &status);
    463 	DPRINTFN(2, ("ulpt_status: status=0x%02x err=%d\n", status, err));
    464 	if (!err)
    465 		return (status);
    466 	else
    467 		return (0);
    468 }
    469 
    470 void
    471 ulpt_reset(struct ulpt_softc *sc)
    472 {
    473 	usb_device_request_t req;
    474 
    475 	DPRINTFN(2, ("ulpt_reset\n"));
    476 	req.bRequest = UR_SOFT_RESET;
    477 	USETW(req.wValue, 0);
    478 	USETW(req.wIndex, sc->sc_ifaceno);
    479 	USETW(req.wLength, 0);
    480 
    481 	/*
    482 	 * There was a mistake in the USB printer 1.0 spec that gave the
    483 	 * request type as UT_WRITE_CLASS_OTHER; it should have been
    484 	 * UT_WRITE_CLASS_INTERFACE.  Many printers use the old one,
    485 	 * so we try both.
    486 	 */
    487 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
    488 	if (usbd_do_request(sc->sc_udev, &req, 0)) {	/* 1.0 */
    489 		req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
    490 		(void)usbd_do_request(sc->sc_udev, &req, 0); /* 1.1 */
    491 	}
    492 }
    493 
    494 int ulptusein = 1;
    495 
    496 /*
    497  * Reset the printer, then wait until it's selected and not busy.
    498  */
    499 int
    500 ulptopen(dev_t dev, int flag, int mode, struct lwp *l)
    501 {
    502 	u_char flags = ULPTFLAGS(dev);
    503 	struct ulpt_softc *sc;
    504 	usbd_status err;
    505 	int spin, error;
    506 
    507 	USB_GET_SC_OPEN(ulpt, ULPTUNIT(dev), sc);
    508 
    509 	if (sc == NULL || sc->sc_iface == NULL || sc->sc_dying)
    510 		return (ENXIO);
    511 
    512 	if (sc->sc_state)
    513 		return (EBUSY);
    514 
    515 	sc->sc_state = ULPT_INIT;
    516 	sc->sc_flags = flags;
    517 	DPRINTFN(2, ("ulptopen: flags=0x%x\n", (unsigned)flags));
    518 
    519 #if defined(ULPT_DEBUG) && defined(__FreeBSD__)
    520 	/* Ignoring these flags might not be a good idea */
    521 	if ((flags & ~ULPT_NOPRIME) != 0)
    522 		printf("ulptopen: flags ignored: %b\n", flags,
    523 			"\20\3POS_INIT\4POS_ACK\6PRIME_OPEN\7AUTOLF\10BYPASS");
    524 #endif
    525 
    526 
    527 	error = 0;
    528 	sc->sc_refcnt++;
    529 
    530 #if 0 /* XXX causes some printers to disconnect */
    531 	if ((flags & ULPT_NOPRIME) == 0)
    532 		ulpt_reset(sc);
    533 #endif
    534 
    535 	for (spin = 0; (ulpt_status(sc) & LPS_SELECT) == 0; spin += STEP) {
    536 		DPRINTFN(2, ("ulpt_open: waiting a while\n"));
    537 		if (spin >= TIMEOUT) {
    538 			error = EBUSY;
    539 			sc->sc_state = 0;
    540 			goto done;
    541 		}
    542 
    543 		/* wait 1/4 second, give up if we get a signal */
    544 		error = tsleep((void *)sc, LPTPRI | PCATCH, "ulptop", STEP);
    545 		if (error != EWOULDBLOCK) {
    546 			sc->sc_state = 0;
    547 			goto done;
    548 		}
    549 
    550 		if (sc->sc_dying) {
    551 			error = ENXIO;
    552 			sc->sc_state = 0;
    553 			goto done;
    554 		}
    555 	}
    556 
    557 	err = usbd_open_pipe(sc->sc_iface, sc->sc_out, 0, &sc->sc_out_pipe);
    558 	if (err) {
    559 		error = EIO;
    560 		goto err0;
    561 	}
    562 	sc->sc_out_xfer = usbd_alloc_xfer(sc->sc_udev);
    563 	if (sc->sc_out_xfer == NULL) {
    564 		error = ENOMEM;
    565 		goto err1;
    566 	}
    567 	sc->sc_out_buf = usbd_alloc_buffer(sc->sc_out_xfer, ULPT_BSIZE);
    568 	if (sc->sc_out_buf == NULL) {
    569 		error = ENOMEM;
    570 		goto err2;
    571 	}
    572 
    573 	if (ulptusein && sc->sc_in != -1) {
    574 		DPRINTFN(2, ("ulpt_open: opening input pipe %d\n", sc->sc_in));
    575 		err = usbd_open_pipe(sc->sc_iface, sc->sc_in,0,&sc->sc_in_pipe);
    576 		if (err) {
    577 			error = EIO;
    578 			goto err2;
    579 		}
    580 		sc->sc_in_xfer = usbd_alloc_xfer(sc->sc_udev);
    581 		if (sc->sc_in_xfer == NULL) {
    582 			error = ENOMEM;
    583 			goto err3;
    584 		}
    585 		sc->sc_in_buf = usbd_alloc_buffer(sc->sc_in_xfer, ULPT_BSIZE);
    586 		if (sc->sc_in_buf == NULL) {
    587 			error = ENOMEM;
    588 			goto err4;
    589 		}
    590 
    591 		/* If it's not opened for read then set up a reader. */
    592 		if (!(flag & FREAD)) {
    593 			DPRINTFN(2, ("ulpt_open: start read callout\n"));
    594 			usb_callout_init(sc->sc_read_callout);
    595 			usb_callout(sc->sc_read_callout, hz/5, ulpt_tick, sc);
    596 			sc->sc_has_callout = 1;
    597 		}
    598 	}
    599 
    600 	sc->sc_state = ULPT_OPEN;
    601 	goto done;
    602 
    603  err4:
    604 	usbd_free_xfer(sc->sc_in_xfer);
    605 	sc->sc_in_xfer = NULL;
    606  err3:
    607 	usbd_close_pipe(sc->sc_in_pipe);
    608 	sc->sc_in_pipe = NULL;
    609  err2:
    610 	usbd_free_xfer(sc->sc_out_xfer);
    611 	sc->sc_out_xfer = NULL;
    612  err1:
    613 	usbd_close_pipe(sc->sc_out_pipe);
    614 	sc->sc_out_pipe = NULL;
    615  err0:
    616 	sc->sc_state = 0;
    617 
    618  done:
    619 	if (--sc->sc_refcnt < 0)
    620 		usb_detach_wakeup(USBDEV(sc->sc_dev));
    621 
    622 	DPRINTFN(2, ("ulptopen: done, error=%d\n", error));
    623 	return (error);
    624 }
    625 
    626 /*
    627  * XXX Document return value semantics.
    628  */
    629 int
    630 ulpt_statusmsg(u_char status, struct ulpt_softc *sc)
    631 {
    632 	u_char new;
    633 
    634 	status = (status ^ LPS_INVERT) & LPS_MASK;
    635 	new = status & ~sc->sc_laststatus;
    636 	sc->sc_laststatus = status;
    637 
    638 	if (new & LPS_SELECT)
    639 		log(LOG_NOTICE, "%s: offline\n", USBDEVNAME(sc->sc_dev));
    640 	if (new & LPS_NOPAPER)
    641 		log(LOG_NOTICE, "%s: out of paper\n", USBDEVNAME(sc->sc_dev));
    642 	if (new & LPS_NERR)
    643 		log(LOG_NOTICE, "%s: output error\n", USBDEVNAME(sc->sc_dev));
    644 
    645 	return (status);
    646 }
    647 
    648 int
    649 ulptclose(dev_t dev, int flag, int mode,
    650     struct lwp *l)
    651 {
    652 	struct ulpt_softc *sc;
    653 
    654 	USB_GET_SC(ulpt, ULPTUNIT(dev), sc);
    655 
    656 	if (sc->sc_state != ULPT_OPEN)
    657 		/* We are being forced to close before the open completed. */
    658 		return (0);
    659 
    660 	if (sc->sc_has_callout) {
    661 		DPRINTFN(2, ("ulptclose: stopping read callout\n"));
    662 		usb_uncallout(sc->sc_read_callout, ulpt_tick, sc);
    663 		sc->sc_has_callout = 0;
    664 	}
    665 
    666 	if (sc->sc_out_pipe != NULL) {
    667 		usbd_abort_pipe(sc->sc_out_pipe);
    668 		usbd_close_pipe(sc->sc_out_pipe);
    669 		sc->sc_out_pipe = NULL;
    670 	}
    671 	if (sc->sc_out_xfer != NULL) {
    672 		usbd_free_xfer(sc->sc_out_xfer);
    673 		sc->sc_out_xfer = NULL;
    674 	}
    675 
    676 	if (sc->sc_in_pipe != NULL) {
    677 		usbd_abort_pipe(sc->sc_in_pipe);
    678 		usbd_close_pipe(sc->sc_in_pipe);
    679 		sc->sc_in_pipe = NULL;
    680 	}
    681 	if (sc->sc_in_xfer != NULL) {
    682 		usbd_free_xfer(sc->sc_in_xfer);
    683 		sc->sc_in_xfer = NULL;
    684 	}
    685 
    686 	sc->sc_state = 0;
    687 
    688 	DPRINTFN(2, ("ulptclose: closed\n"));
    689 	return (0);
    690 }
    691 
    692 int
    693 ulpt_do_write(struct ulpt_softc *sc, struct uio *uio, int flags)
    694 {
    695 	u_int32_t n;
    696 	int error = 0;
    697 	void *bufp;
    698 	usbd_xfer_handle xfer;
    699 	usbd_status err;
    700 
    701 	DPRINTFN(3, ("ulptwrite\n"));
    702 	xfer = sc->sc_out_xfer;
    703 	bufp = sc->sc_out_buf;
    704 	while ((n = min(ULPT_BSIZE, uio->uio_resid)) != 0) {
    705 		ulpt_statusmsg(ulpt_status(sc), sc);
    706 		error = uiomove(bufp, n, uio);
    707 		if (error)
    708 			break;
    709 		DPRINTFN(4, ("ulptwrite: transfer %d bytes\n", n));
    710 		err = usbd_bulk_transfer(xfer, sc->sc_out_pipe, USBD_NO_COPY,
    711 			  USBD_NO_TIMEOUT, bufp, &n, "ulptwr");
    712 		if (err) {
    713 			DPRINTFN(3, ("ulptwrite: error=%d\n", err));
    714 			error = EIO;
    715 			break;
    716 		}
    717 	}
    718 
    719 	return (error);
    720 }
    721 
    722 int
    723 ulptwrite(dev_t dev, struct uio *uio, int flags)
    724 {
    725 	struct ulpt_softc *sc;
    726 	int error;
    727 
    728 	USB_GET_SC(ulpt, ULPTUNIT(dev), sc);
    729 
    730 	if (sc->sc_dying)
    731 		return (EIO);
    732 
    733 	sc->sc_refcnt++;
    734 	error = ulpt_do_write(sc, uio, flags);
    735 	if (--sc->sc_refcnt < 0)
    736 		usb_detach_wakeup(USBDEV(sc->sc_dev));
    737 	return (error);
    738 }
    739 
    740 /*
    741  * Perform a read operation according to the given uio.
    742  * This should respect nonblocking I/O status.
    743  *
    744  * XXX Doing a short read when more data is available seems to be
    745  * problematic.  See
    746  * http://www.freebsd.org/cgi/query-pr.cgi?pr=91538&cat= for a fix.
    747  * However, this will be unnecessary given a proper fix for the next
    748  * problem, and most actual callers read a lot.
    749  *
    750  * XXX This code should interact properly with select/poll, and that
    751  * requires the USB transactions to be queued and function before the
    752  * user does a read.  Read will then consume data from a buffer, and
    753  * not interact with the device. See ucom.c for an example of how to
    754  * do this.
    755  */
    756 int
    757 ulpt_do_read(struct ulpt_softc *sc, struct uio *uio, int flags)
    758 {
    759 	u_int32_t n, nread, nreq;
    760 	int error = 0, nonblocking, timeout;
    761 	void *bufp;
    762 	usbd_xfer_handle xfer;
    763 	usbd_status err = USBD_NORMAL_COMPLETION;
    764 
    765 	/* XXX Resolve with background reader process.  KASSERT? */
    766 	if (sc->sc_in_pipe == NULL)
    767 		return EIO;
    768 
    769 	if (flags & IO_NDELAY)
    770 		nonblocking = 1;
    771 	else
    772 		nonblocking = 0;
    773 
    774 	if (nonblocking)
    775 		timeout = USBD_DEFAULT_TIMEOUT; /* 5 ms */
    776 	else
    777 		timeout = USBD_NO_TIMEOUT;
    778 
    779 	DPRINTFN(3, ("ulptread nonblocking=%d uio_reside=%d timeout=%d\n",
    780 		     nonblocking, uio->uio_resid, timeout));
    781 
    782 	xfer = sc->sc_in_xfer;
    783 	bufp = sc->sc_in_buf;
    784 	nread = 0;
    785 	while ((nreq = min(ULPT_BSIZE, uio->uio_resid)) != 0) {
    786 		KASSERT(error == 0);
    787 		if (error != 0) {
    788 			printf("ulptread: pre-switch error %d != 0", error);
    789 			goto done;
    790 		}
    791 
    792 		/*
    793 		 * XXX Even with the short timeout, this will tsleep,
    794 		 * but it should be adequately prompt in practice.
    795 		 */
    796 		n = nreq;
    797 		DPRINTFN(4, ("ulptread: transfer %d bytes, nonblocking=%d timeout=%d\n",
    798 			     n, nonblocking, timeout));
    799 		err = usbd_bulk_transfer(xfer, sc->sc_in_pipe,
    800 			  USBD_NO_COPY | USBD_SHORT_XFER_OK,
    801 			  timeout, bufp, &n, "ulptrd");
    802 
    803 		DPRINTFN(4, ("ulptread: transfer complete nreq %d n %d nread %d err %d\n",
    804 			     nreq, n, nread, err));
    805 		/*
    806 		 * Process "err" return, jumping to done if we set "error".
    807 		 */
    808 		switch (err) {
    809 		case USBD_NORMAL_COMPLETION:
    810 			if (n == 0) {
    811 				DPRINTFN(3, ("ulptread: NORMAL n==0\n"));
    812 			}
    813 			break;
    814 
    815 		case USBD_SHORT_XFER:
    816 			/* We said SHORT_XFER_OK, so shouldn't happen. */
    817 			DPRINTFN(3, ("ulptread: SHORT n=%d\n", n));
    818 			break;
    819 
    820 		case USBD_TIMEOUT:
    821 			if (nonblocking == 0) {
    822 				/* XXX Cannot happen; perhaps KASSERT. */
    823 				printf("ulptread: timeout in blocking mode\n");
    824 				error = EIO;
    825 				goto done;
    826 			}
    827 
    828 			DPRINTFN(3, ("ulptread: TIMEOUT n %d nread %d error %d\n",
    829 				     n, nread, error));
    830 			/*
    831 			 * Don't set error until we understand why
    832 			 * this happens.
    833 			 */
    834 			break;
    835 
    836 		case USBD_INTERRUPTED:
    837 			/*
    838 			 * The tsleep in usbd_bulk_transfer was
    839 			 * interrupted.  Reflect it to the caller so
    840 			 * that reading can be interrupted.
    841 			 */
    842 			error = EINTR;
    843 			DPRINTFN(3, ("ulptread: EINTR error %d\n", error));
    844 			goto done;
    845 			break;
    846 
    847 		default:
    848 			/* Assume all other return codes are really errors. */
    849 			error = EIO;
    850 			DPRINTFN(3, ("ulptread: n %d err %d error %d\n",
    851 				     n, err, error));
    852 			goto done;
    853 			break;
    854 		}
    855 		/* XXX KASSERT */
    856 		if (error != 0) {
    857 			printf("ulptread: post-switch error %d != 0", error);
    858 			goto done;
    859 		}
    860 
    861 		if (n > 0) {
    862 			/*
    863 			 * Record progress to enable later choosing
    864 			 * between short reads and EWOULDBLOCK.
    865 			 */
    866 			nread += n;
    867 
    868 			/* Copy to userspace, giving up on any error. */
    869 			error = uiomove(bufp, n, uio);
    870 			if (error != 0)
    871 				break;
    872 		} else {
    873 			/*
    874 			 * We read 0 bytes, and therefore are done,
    875 			 * even if we aren't in nonblocking mode.
    876 			 */
    877 			if (error == 0 && nread == 0)
    878 				error = EWOULDBLOCK;
    879 			DPRINTFN(3, ("ulptread: read 0=>done error %d\n",
    880 				     error));
    881 			goto done;
    882 		}
    883 
    884 		/*
    885 		 * A short transfer indicates no more data will be
    886 		 * forthcoming.  Terminate this read regardless of
    887 		 * whether we are in nonblocking mode.  XXX Reconsider
    888 		 * for blocking mode; maybe we should continue to
    889 		 * block, but maybe it just doesn't make senes to do
    890 		 * blocking reads from devices like this.
    891 		 */
    892 		if (err == USBD_SHORT_XFER) {
    893 			DPRINTFN(3, ("ulptread: SHORT=>done n %d nread %d err %d error %d\n",
    894 				     n, nread, err, error));
    895 			break;
    896 		}
    897 	}
    898 
    899 done:
    900 	DPRINTFN(3, ("ulptread: finished n %d nread %d err %d error %d\n",
    901 			     n, nread, err, error));
    902 	return (error);
    903 }
    904 
    905 int
    906 ulptread(dev_t dev, struct uio *uio, int flags)
    907 {
    908 	struct ulpt_softc *sc;
    909 	int error;
    910 
    911 	USB_GET_SC(ulpt, ULPTUNIT(dev), sc);
    912 
    913 	if (sc->sc_dying)
    914 		return (EIO);
    915 
    916 	sc->sc_refcnt++;
    917 	error = ulpt_do_read(sc, uio, flags);
    918 	if (--sc->sc_refcnt < 0)
    919 		usb_detach_wakeup(USBDEV(sc->sc_dev));
    920 	return (error);
    921 }
    922 
    923 void
    924 ulpt_read_cb(usbd_xfer_handle xfer, usbd_private_handle priv,
    925 	     usbd_status status)
    926 {
    927 	usbd_status err;
    928 	u_int32_t n;
    929 	usbd_private_handle xsc;
    930 	struct ulpt_softc *sc;
    931 
    932 	usbd_get_xfer_status(xfer, &xsc, NULL, &n, &err);
    933 	sc = xsc;
    934 
    935 	DPRINTFN(4, ("ulpt_read_cb: start sc=%p, err=%d n=%d\n", sc, err, n));
    936 
    937 #ifdef ULPT_DEBUG
    938 	if (!err && n > 0)
    939 		DPRINTFN(3, ("ulpt_tick: discarding %d bytes\n", n));
    940 #endif
    941 	if (!err || err == USBD_TIMEOUT)
    942 		usb_callout(sc->sc_read_callout, hz / ULPT_READS_PER_SEC,
    943 			    ulpt_tick, sc);
    944 }
    945 
    946 /*
    947  * For devices which are not opened for reading, this function is
    948  * called continuously to start read bulk transfers to avoid the
    949  * printer overflowing its output buffer.
    950  *
    951  * XXX This should be adapted for continuous reads to allow select to
    952  * work; see do_ulpt_read().
    953  */
    954 void
    955 ulpt_tick(void *xsc)
    956 {
    957 	struct ulpt_softc *sc = xsc;
    958 	usbd_status err;
    959 
    960 	if (sc == NULL || sc->sc_dying)
    961 		return;
    962 
    963 	usbd_setup_xfer(sc->sc_in_xfer, sc->sc_in_pipe, sc, sc->sc_in_buf,
    964 			ULPT_BSIZE, USBD_NO_COPY | USBD_SHORT_XFER_OK,
    965 			ULPT_READ_TIMO, ulpt_read_cb);
    966 	err = usbd_transfer(sc->sc_in_xfer);
    967 	DPRINTFN(3, ("ulpt_tick: sc=%p err=%d\n", sc, err));
    968 }
    969 
    970 int
    971 ulptioctl(dev_t dev, u_long cmd, void *data,
    972     int flag, struct lwp *l)
    973 {
    974 	struct ulpt_softc *sc;
    975 
    976 	USB_GET_SC(ulpt, ULPTUNIT(dev), sc);
    977 
    978 	switch (cmd) {
    979 	case FIONBIO:
    980 		return 0;
    981 	}
    982 
    983 	return ENODEV;
    984 }
    985 
    986 #if 0
    987 /* XXX This does not belong here. */
    988 /*
    989  * Print select parts of a IEEE 1284 device ID.
    990  */
    991 void
    992 ieee1284_print_id(char *str)
    993 {
    994 	char *p, *q;
    995 
    996 	for (p = str-1; p; p = strchr(p, ';')) {
    997 		p++;		/* skip ';' */
    998 		if (strncmp(p, "MFG:", 4) == 0 ||
    999 		    strncmp(p, "MANUFACTURER:", 14) == 0 ||
   1000 		    strncmp(p, "MDL:", 4) == 0 ||
   1001 		    strncmp(p, "MODEL:", 6) == 0) {
   1002 			q = strchr(p, ';');
   1003 			if (q)
   1004 				printf("%.*s", (int)(q - p + 1), p);
   1005 		}
   1006 	}
   1007 }
   1008 #endif
   1009 
   1010 #if defined(__FreeBSD__)
   1011 DRIVER_MODULE(ulpt, uhub, ulpt_driver, ulpt_devclass, usbd_driver_load, 0);
   1012 #endif
   1013