Home | History | Annotate | Line # | Download | only in usb
ulpt.c revision 1.79
      1 /*	$NetBSD: ulpt.c,v 1.79 2008/01/08 00:58:09 gdt 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 2008/01/08 00:58:09 gdt 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 
    204 
    205 USB_DECLARE_DRIVER(ulpt);
    206 
    207 USB_MATCH(ulpt)
    208 {
    209 	USB_IFMATCH_START(ulpt, uaa);
    210 
    211 	/* XXX Print something useful, or don't. */
    212 	DPRINTFN(10,("ulpt_match\n"));
    213 
    214 	if (uaa->class == UICLASS_PRINTER &&
    215 	    uaa->subclass == UISUBCLASS_PRINTER &&
    216 	    (uaa->proto == UIPROTO_PRINTER_UNI ||
    217 	     uaa->proto == UIPROTO_PRINTER_BI ||
    218 	     uaa->proto == UIPROTO_PRINTER_1284))
    219 		return (UMATCH_IFACECLASS_IFACESUBCLASS_IFACEPROTO);
    220 	return (UMATCH_NONE);
    221 }
    222 
    223 USB_ATTACH(ulpt)
    224 {
    225 	USB_IFATTACH_START(ulpt, sc, uaa);
    226 	usbd_device_handle dev = uaa->device;
    227 	usbd_interface_handle iface = uaa->iface;
    228 	usb_interface_descriptor_t *ifcd = usbd_get_interface_descriptor(iface);
    229 	const usb_interface_descriptor_t *id;
    230 	usbd_status err;
    231 	char *devinfop;
    232 	usb_endpoint_descriptor_t *ed;
    233 	u_int8_t epcount;
    234 	int i, altno;
    235 	usbd_desc_iter_t iter;
    236 
    237 	devinfop = usbd_devinfo_alloc(dev, 0);
    238 	USB_ATTACH_SETUP;
    239 	printf("%s: %s, iclass %d/%d\n", USBDEVNAME(sc->sc_dev),
    240 	       devinfop, ifcd->bInterfaceClass, ifcd->bInterfaceSubClass);
    241 	usbd_devinfo_free(devinfop);
    242 
    243 	/* Loop through descriptors looking for a bidir mode. */
    244 	usb_desc_iter_init(dev, &iter);
    245 	for (altno = 0;;) {
    246 		id = (const usb_interface_descriptor_t *)usb_desc_iter_next(&iter);
    247 		if (!id)
    248 			break;
    249 		if (id->bDescriptorType == UDESC_INTERFACE &&
    250 		    id->bInterfaceNumber == ifcd->bInterfaceNumber) {
    251 			if (id->bInterfaceClass == UICLASS_PRINTER &&
    252 			    id->bInterfaceSubClass == UISUBCLASS_PRINTER &&
    253 			    (id->bInterfaceProtocol == UIPROTO_PRINTER_BI /*||
    254 			     id->bInterfaceProtocol == UIPROTO_PRINTER_1284*/))
    255 				goto found;
    256 			altno++;
    257 		}
    258 	}
    259 	id = ifcd;		/* not found, use original */
    260  found:
    261 	if (id != ifcd) {
    262 		/* Found a new bidir setting */
    263 		DPRINTFN(1, ("ulpt_attach: set altno = %d\n", altno));
    264 		err = usbd_set_interface(iface, altno);
    265 		if (err) {
    266 			printf("%s: setting alternate interface failed\n",
    267 			       USBDEVNAME(sc->sc_dev));
    268 			sc->sc_dying = 1;
    269 			USB_ATTACH_ERROR_RETURN;
    270 		}
    271 	}
    272 
    273 	epcount = 0;
    274 	(void)usbd_endpoint_count(iface, &epcount);
    275 
    276 	sc->sc_in = -1;
    277 	sc->sc_out = -1;
    278 	for (i = 0; i < epcount; i++) {
    279 		ed = usbd_interface2endpoint_descriptor(iface, i);
    280 		if (ed == NULL) {
    281 			printf("%s: couldn't get ep %d\n",
    282 			    USBDEVNAME(sc->sc_dev), i);
    283 			USB_ATTACH_ERROR_RETURN;
    284 		}
    285 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
    286 		    UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
    287 			sc->sc_in = ed->bEndpointAddress;
    288 		} else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT &&
    289 			   UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK) {
    290 			sc->sc_out = ed->bEndpointAddress;
    291 		}
    292 	}
    293 	if (sc->sc_out == -1) {
    294 		printf("%s: could not find bulk out endpoint\n",
    295 		    USBDEVNAME(sc->sc_dev));
    296 		sc->sc_dying = 1;
    297 		USB_ATTACH_ERROR_RETURN;
    298 	}
    299 
    300 	if (usbd_get_quirks(dev)->uq_flags & UQ_BROKEN_BIDIR) {
    301 		/* This device doesn't handle reading properly. */
    302 		sc->sc_in = -1;
    303 	}
    304 
    305 	printf("%s: using %s-directional mode\n", USBDEVNAME(sc->sc_dev),
    306 	       sc->sc_in >= 0 ? "bi" : "uni");
    307 
    308 	sc->sc_iface = iface;
    309 	sc->sc_ifaceno = id->bInterfaceNumber;
    310 	sc->sc_udev = dev;
    311 
    312 #if 0
    313 /*
    314  * This code is disabled because for some mysterious reason it causes
    315  * printing not to work.  But only sometimes, and mostly with
    316  * UHCI and less often with OHCI.  *sigh*
    317  */
    318 	{
    319 	usb_config_descriptor_t *cd = usbd_get_config_descriptor(dev);
    320 	usb_device_request_t req;
    321 	int len, alen;
    322 
    323 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
    324 	req.bRequest = UR_GET_DEVICE_ID;
    325 	USETW(req.wValue, cd->bConfigurationValue);
    326 	USETW2(req.wIndex, id->bInterfaceNumber, id->bAlternateSetting);
    327 	USETW(req.wLength, DEVINFOSIZE - 1);
    328 	err = usbd_do_request_flags(dev, &req, devinfop, USBD_SHORT_XFER_OK,
    329 		  &alen, USBD_DEFAULT_TIMEOUT);
    330 	if (err) {
    331 		printf("%s: cannot get device id\n", USBDEVNAME(sc->sc_dev));
    332 	} else if (alen <= 2) {
    333 		printf("%s: empty device id, no printer connected?\n",
    334 		       USBDEVNAME(sc->sc_dev));
    335 	} else {
    336 		/* devinfop now contains an IEEE-1284 device ID */
    337 		len = ((devinfop[0] & 0xff) << 8) | (devinfop[1] & 0xff);
    338 		if (len > DEVINFOSIZE - 3)
    339 			len = DEVINFOSIZE - 3;
    340 		devinfop[len] = 0;
    341 		printf("%s: device id <", USBDEVNAME(sc->sc_dev));
    342 		ieee1284_print_id(devinfop+2);
    343 		printf(">\n");
    344 	}
    345 	}
    346 #endif
    347 
    348 #if defined(__FreeBSD__)
    349 	sc->dev = make_dev(&ulpt_cdevsw, device_get_unit(self),
    350 		UID_ROOT, GID_OPERATOR, 0644, "ulpt%d", device_get_unit(self));
    351 	sc->dev_noprime = make_dev(&ulpt_cdevsw,
    352 		device_get_unit(self)|ULPT_NOPRIME,
    353 		UID_ROOT, GID_OPERATOR, 0644, "unlpt%d", device_get_unit(self));
    354 #endif
    355 
    356 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev,
    357 			   USBDEV(sc->sc_dev));
    358 
    359 	DPRINTFN(1, ("ulpt_attach: sc=%p in=%d out=%d\n",
    360 		     sc, sc->sc_out, sc->sc_in));
    361 
    362 	USB_ATTACH_SUCCESS_RETURN;
    363 }
    364 
    365 #if defined(__NetBSD__) || defined(__OpenBSD__)
    366 int
    367 ulpt_activate(device_ptr_t self, enum devact act)
    368 {
    369 	struct ulpt_softc *sc = (struct ulpt_softc *)self;
    370 
    371 	switch (act) {
    372 	case DVACT_ACTIVATE:
    373 		return (EOPNOTSUPP);
    374 
    375 	case DVACT_DEACTIVATE:
    376 		sc->sc_dying = 1;
    377 		break;
    378 	}
    379 	return (0);
    380 }
    381 #endif
    382 
    383 USB_DETACH(ulpt)
    384 {
    385 	USB_DETACH_START(ulpt, sc);
    386 	int s;
    387 #if defined(__NetBSD__) || defined(__OpenBSD__)
    388 	int maj, mn;
    389 #elif defined(__FreeBSD__)
    390 	struct vnode *vp;
    391 #endif
    392 
    393 	DPRINTFN(1, ("ulpt_detach: sc=%p\n", sc));
    394 
    395 	sc->sc_dying = 1;
    396 	if (sc->sc_out_pipe != NULL)
    397 		usbd_abort_pipe(sc->sc_out_pipe);
    398 	if (sc->sc_in_pipe != NULL)
    399 		usbd_abort_pipe(sc->sc_in_pipe);
    400 
    401 	s = splusb();
    402 	if (--sc->sc_refcnt >= 0) {
    403 		/* There is noone to wake, aborting the pipe is enough */
    404 		/* Wait for processes to go away. */
    405 		usb_detach_wait(USBDEV(sc->sc_dev));
    406 	}
    407 	splx(s);
    408 
    409 #if defined(__NetBSD__) || defined(__OpenBSD__)
    410 	/* locate the major number */
    411 #if defined(__NetBSD__)
    412 	maj = cdevsw_lookup_major(&ulpt_cdevsw);
    413 #elif defined(__OpenBSD__)
    414 	for (maj = 0; maj < nchrdev; maj++)
    415 		if (cdevsw[maj].d_open == ulptopen)
    416 			break;
    417 #endif
    418 
    419 	/* Nuke the vnodes for any open instances (calls close). */
    420 	mn = device_unit(self);
    421 	vdevgone(maj, mn, mn, VCHR);
    422 	vdevgone(maj, mn | ULPT_NOPRIME , mn | ULPT_NOPRIME, VCHR);
    423 #elif defined(__FreeBSD__)
    424 	vp = SLIST_FIRST(&sc->dev->si_hlist);
    425 	if (vp)
    426 		VOP_REVOKE(vp, REVOKEALL);
    427 	vp = SLIST_FIRST(&sc->dev_noprime->si_hlist);
    428 	if (vp)
    429 		VOP_REVOKE(vp, REVOKEALL);
    430 
    431 	destroy_dev(sc->dev);
    432 	destroy_dev(sc->dev_noprime);
    433 #endif
    434 
    435 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev,
    436 			   USBDEV(sc->sc_dev));
    437 
    438 	return (0);
    439 }
    440 
    441 int
    442 ulpt_status(struct ulpt_softc *sc)
    443 {
    444 	usb_device_request_t req;
    445 	usbd_status err;
    446 	u_char status;
    447 
    448 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
    449 	req.bRequest = UR_GET_PORT_STATUS;
    450 	USETW(req.wValue, 0);
    451 	USETW(req.wIndex, sc->sc_ifaceno);
    452 	USETW(req.wLength, 1);
    453 	err = usbd_do_request(sc->sc_udev, &req, &status);
    454 	DPRINTFN(2, ("ulpt_status: status=0x%02x err=%d\n", status, err));
    455 	if (!err)
    456 		return (status);
    457 	else
    458 		return (0);
    459 }
    460 
    461 void
    462 ulpt_reset(struct ulpt_softc *sc)
    463 {
    464 	usb_device_request_t req;
    465 
    466 	DPRINTFN(2, ("ulpt_reset\n"));
    467 	req.bRequest = UR_SOFT_RESET;
    468 	USETW(req.wValue, 0);
    469 	USETW(req.wIndex, sc->sc_ifaceno);
    470 	USETW(req.wLength, 0);
    471 
    472 	/*
    473 	 * There was a mistake in the USB printer 1.0 spec that gave the
    474 	 * request type as UT_WRITE_CLASS_OTHER; it should have been
    475 	 * UT_WRITE_CLASS_INTERFACE.  Many printers use the old one,
    476 	 * so we try both.
    477 	 */
    478 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
    479 	if (usbd_do_request(sc->sc_udev, &req, 0)) {	/* 1.0 */
    480 		req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
    481 		(void)usbd_do_request(sc->sc_udev, &req, 0); /* 1.1 */
    482 	}
    483 }
    484 
    485 int ulptusein = 1;
    486 
    487 /*
    488  * Reset the printer, then wait until it's selected and not busy.
    489  */
    490 int
    491 ulptopen(dev_t dev, int flag, int mode, struct lwp *l)
    492 {
    493 	u_char flags = ULPTFLAGS(dev);
    494 	struct ulpt_softc *sc;
    495 	usbd_status err;
    496 	int spin, error;
    497 
    498 	USB_GET_SC_OPEN(ulpt, ULPTUNIT(dev), sc);
    499 
    500 	if (sc == NULL || sc->sc_iface == NULL || sc->sc_dying)
    501 		return (ENXIO);
    502 
    503 	if (sc->sc_state)
    504 		return (EBUSY);
    505 
    506 	sc->sc_state = ULPT_INIT;
    507 	sc->sc_flags = flags;
    508 	DPRINTFN(2, ("ulptopen: flags=0x%x\n", (unsigned)flags));
    509 
    510 #if defined(ULPT_DEBUG) && defined(__FreeBSD__)
    511 	/* Ignoring these flags might not be a good idea */
    512 	if ((flags & ~ULPT_NOPRIME) != 0)
    513 		printf("ulptopen: flags ignored: %b\n", flags,
    514 			"\20\3POS_INIT\4POS_ACK\6PRIME_OPEN\7AUTOLF\10BYPASS");
    515 #endif
    516 
    517 
    518 	error = 0;
    519 	sc->sc_refcnt++;
    520 
    521 #if 0 /* XXX causes some printers to disconnect */
    522 	if ((flags & ULPT_NOPRIME) == 0)
    523 		ulpt_reset(sc);
    524 #endif
    525 
    526 	for (spin = 0; (ulpt_status(sc) & LPS_SELECT) == 0; spin += STEP) {
    527 		DPRINTFN(2, ("ulpt_open: waiting a while\n"));
    528 		if (spin >= TIMEOUT) {
    529 			error = EBUSY;
    530 			sc->sc_state = 0;
    531 			goto done;
    532 		}
    533 
    534 		/* wait 1/4 second, give up if we get a signal */
    535 		error = tsleep((void *)sc, LPTPRI | PCATCH, "ulptop", STEP);
    536 		if (error != EWOULDBLOCK) {
    537 			sc->sc_state = 0;
    538 			goto done;
    539 		}
    540 
    541 		if (sc->sc_dying) {
    542 			error = ENXIO;
    543 			sc->sc_state = 0;
    544 			goto done;
    545 		}
    546 	}
    547 
    548 	err = usbd_open_pipe(sc->sc_iface, sc->sc_out, 0, &sc->sc_out_pipe);
    549 	if (err) {
    550 		error = EIO;
    551 		goto err0;
    552 	}
    553 	sc->sc_out_xfer = usbd_alloc_xfer(sc->sc_udev);
    554 	if (sc->sc_out_xfer == NULL) {
    555 		error = ENOMEM;
    556 		goto err1;
    557 	}
    558 	sc->sc_out_buf = usbd_alloc_buffer(sc->sc_out_xfer, ULPT_BSIZE);
    559 	if (sc->sc_out_buf == NULL) {
    560 		error = ENOMEM;
    561 		goto err2;
    562 	}
    563 
    564 	if (ulptusein && sc->sc_in != -1) {
    565 		DPRINTFN(2, ("ulpt_open: opening input pipe %d\n", sc->sc_in));
    566 		err = usbd_open_pipe(sc->sc_iface, sc->sc_in,0,&sc->sc_in_pipe);
    567 		if (err) {
    568 			error = EIO;
    569 			goto err2;
    570 		}
    571 		sc->sc_in_xfer = usbd_alloc_xfer(sc->sc_udev);
    572 		if (sc->sc_in_xfer == NULL) {
    573 			error = ENOMEM;
    574 			goto err3;
    575 		}
    576 		sc->sc_in_buf = usbd_alloc_buffer(sc->sc_in_xfer, ULPT_BSIZE);
    577 		if (sc->sc_in_buf == NULL) {
    578 			error = ENOMEM;
    579 			goto err4;
    580 		}
    581 
    582 		/* If it's not opened for read then set up a reader. */
    583 		if (!(flag & FREAD)) {
    584 			DPRINTFN(2, ("ulpt_open: start read callout\n"));
    585 			usb_callout_init(sc->sc_read_callout);
    586 			usb_callout(sc->sc_read_callout, hz/5, ulpt_tick, sc);
    587 			sc->sc_has_callout = 1;
    588 		}
    589 	}
    590 
    591 	sc->sc_state = ULPT_OPEN;
    592 	goto done;
    593 
    594  err4:
    595 	usbd_free_xfer(sc->sc_in_xfer);
    596 	sc->sc_in_xfer = NULL;
    597  err3:
    598 	usbd_close_pipe(sc->sc_in_pipe);
    599 	sc->sc_in_pipe = NULL;
    600  err2:
    601 	usbd_free_xfer(sc->sc_out_xfer);
    602 	sc->sc_out_xfer = NULL;
    603  err1:
    604 	usbd_close_pipe(sc->sc_out_pipe);
    605 	sc->sc_out_pipe = NULL;
    606  err0:
    607 	sc->sc_state = 0;
    608 
    609  done:
    610 	if (--sc->sc_refcnt < 0)
    611 		usb_detach_wakeup(USBDEV(sc->sc_dev));
    612 
    613 	DPRINTFN(2, ("ulptopen: done, error=%d\n", error));
    614 	return (error);
    615 }
    616 
    617 /*
    618  * XXX Document return value semantics.
    619  */
    620 int
    621 ulpt_statusmsg(u_char status, struct ulpt_softc *sc)
    622 {
    623 	u_char new;
    624 
    625 	status = (status ^ LPS_INVERT) & LPS_MASK;
    626 	new = status & ~sc->sc_laststatus;
    627 	sc->sc_laststatus = status;
    628 
    629 	if (new & LPS_SELECT)
    630 		log(LOG_NOTICE, "%s: offline\n", USBDEVNAME(sc->sc_dev));
    631 	if (new & LPS_NOPAPER)
    632 		log(LOG_NOTICE, "%s: out of paper\n", USBDEVNAME(sc->sc_dev));
    633 	if (new & LPS_NERR)
    634 		log(LOG_NOTICE, "%s: output error\n", USBDEVNAME(sc->sc_dev));
    635 
    636 	return (status);
    637 }
    638 
    639 int
    640 ulptclose(dev_t dev, int flag, int mode,
    641     struct lwp *l)
    642 {
    643 	struct ulpt_softc *sc;
    644 
    645 	USB_GET_SC(ulpt, ULPTUNIT(dev), sc);
    646 
    647 	if (sc->sc_state != ULPT_OPEN)
    648 		/* We are being forced to close before the open completed. */
    649 		return (0);
    650 
    651 	if (sc->sc_has_callout) {
    652 		DPRINTFN(2, ("ulptclose: stopping read callout\n"));
    653 		usb_uncallout(sc->sc_read_callout, ulpt_tick, sc);
    654 		sc->sc_has_callout = 0;
    655 	}
    656 
    657 	if (sc->sc_out_pipe != NULL) {
    658 		usbd_abort_pipe(sc->sc_out_pipe);
    659 		usbd_close_pipe(sc->sc_out_pipe);
    660 		sc->sc_out_pipe = NULL;
    661 	}
    662 	if (sc->sc_out_xfer != NULL) {
    663 		usbd_free_xfer(sc->sc_out_xfer);
    664 		sc->sc_out_xfer = NULL;
    665 	}
    666 
    667 	if (sc->sc_in_pipe != NULL) {
    668 		usbd_abort_pipe(sc->sc_in_pipe);
    669 		usbd_close_pipe(sc->sc_in_pipe);
    670 		sc->sc_in_pipe = NULL;
    671 	}
    672 	if (sc->sc_in_xfer != NULL) {
    673 		usbd_free_xfer(sc->sc_in_xfer);
    674 		sc->sc_in_xfer = NULL;
    675 	}
    676 
    677 	sc->sc_state = 0;
    678 
    679 	DPRINTFN(2, ("ulptclose: closed\n"));
    680 	return (0);
    681 }
    682 
    683 int
    684 ulpt_do_write(struct ulpt_softc *sc, struct uio *uio, int flags)
    685 {
    686 	u_int32_t n;
    687 	int error = 0;
    688 	void *bufp;
    689 	usbd_xfer_handle xfer;
    690 	usbd_status err;
    691 
    692 	DPRINTFN(3, ("ulptwrite\n"));
    693 	xfer = sc->sc_out_xfer;
    694 	bufp = sc->sc_out_buf;
    695 	while ((n = min(ULPT_BSIZE, uio->uio_resid)) != 0) {
    696 		ulpt_statusmsg(ulpt_status(sc), sc);
    697 		error = uiomove(bufp, n, uio);
    698 		if (error)
    699 			break;
    700 		DPRINTFN(4, ("ulptwrite: transfer %d bytes\n", n));
    701 		err = usbd_bulk_transfer(xfer, sc->sc_out_pipe, USBD_NO_COPY,
    702 			  USBD_NO_TIMEOUT, bufp, &n, "ulptwr");
    703 		if (err) {
    704 			DPRINTFN(3, ("ulptwrite: error=%d\n", err));
    705 			error = EIO;
    706 			break;
    707 		}
    708 	}
    709 
    710 	return (error);
    711 }
    712 
    713 int
    714 ulptwrite(dev_t dev, struct uio *uio, int flags)
    715 {
    716 	struct ulpt_softc *sc;
    717 	int error;
    718 
    719 	USB_GET_SC(ulpt, ULPTUNIT(dev), sc);
    720 
    721 	if (sc->sc_dying)
    722 		return (EIO);
    723 
    724 	sc->sc_refcnt++;
    725 	error = ulpt_do_write(sc, uio, flags);
    726 	if (--sc->sc_refcnt < 0)
    727 		usb_detach_wakeup(USBDEV(sc->sc_dev));
    728 	return (error);
    729 }
    730 
    731 /*
    732  * Perform a read operation according to the given uio.
    733  * This should respect nonblocking I/O status.
    734  *
    735  * XXX Doing a short read when more data is available seems to be
    736  * problematic.  See
    737  * http://www.freebsd.org/cgi/query-pr.cgi?pr=91538&cat= for a fix.
    738  * However, this will be unnecessary given a proper fix for the next
    739  * problem, and most actual callers read a lot.
    740  *
    741  * XXX This code should interact properly with select/poll, and that
    742  * requires the USB transactions to be queued and function before the
    743  * user does a read.  Read will then consume data from a buffer, and
    744  * not interact with the device. See ucom.c for an example of how to
    745  * do this.
    746  */
    747 int
    748 ulpt_do_read(struct ulpt_softc *sc, struct uio *uio, int flags)
    749 {
    750 	u_int32_t n, nread, nreq;
    751 	int error = 0, nonblocking, timeout;
    752 	void *bufp;
    753 	usbd_xfer_handle xfer;
    754 	usbd_status err = USBD_NORMAL_COMPLETION;
    755 
    756 	/* XXX Resolve with background reader process.  KASSERT? */
    757 	if (sc->sc_in_pipe == NULL)
    758 		return EIO;
    759 
    760 	if (flags & IO_NDELAY)
    761 		nonblocking = 1;
    762 	else
    763 		nonblocking = 0;
    764 
    765 	if (nonblocking)
    766 		timeout = USBD_DEFAULT_TIMEOUT; /* 5 ms */
    767 	else
    768 		timeout = USBD_NO_TIMEOUT;
    769 
    770 	DPRINTFN(3, ("ulptread nonblocking=%d uio_reside=%d timeout=%d\n",
    771 		     nonblocking, uio->uio_resid, timeout));
    772 
    773 	xfer = sc->sc_in_xfer;
    774 	bufp = sc->sc_in_buf;
    775 	nread = 0;
    776 	while ((nreq = min(ULPT_BSIZE, uio->uio_resid)) != 0) {
    777 		KASSERT(error == 0);
    778 		if (error != 0) {
    779 			printf("ulptread: pre-switch error %d != 0", error);
    780 			goto done;
    781 		}
    782 
    783 		/*
    784 		 * XXX Even with the short timeout, this will tsleep,
    785 		 * but it should be adequately prompt in practice.
    786 		 */
    787 		n = nreq;
    788 		DPRINTFN(4, ("ulptread: transfer %d bytes, nonblocking=%d timeout=%d\n",
    789 			     n, nonblocking, timeout));
    790 		err = usbd_bulk_transfer(xfer, sc->sc_in_pipe,
    791 			  USBD_NO_COPY | USBD_SHORT_XFER_OK,
    792 			  timeout, bufp, &n, "ulptrd");
    793 
    794 		DPRINTFN(4, ("ulptread: transfer complete nreq %d n %d nread %d err %d\n",
    795 			     nreq, n, nread, err));
    796 		/*
    797 		 * Process "err" return, jumping to done if we set "error".
    798 		 */
    799 		switch (err) {
    800 		case USBD_NORMAL_COMPLETION:
    801 			if (n == 0) {
    802 				DPRINTFN(3, ("ulptread: NORMAL n==0\n"));
    803 			}
    804 			break;
    805 
    806 		case USBD_SHORT_XFER:
    807 			/* We said SHORT_XFER_OK, so shouldn't happen. */
    808 			DPRINTFN(3, ("ulptread: SHORT n=%d\n", n));
    809 			break;
    810 
    811 		case USBD_TIMEOUT:
    812 			if (nonblocking == 0) {
    813 				/* XXX Cannot happen; perhaps KASSERT. */
    814 				printf("ulptread: timeout in blocking mode\n");
    815 				error = EIO;
    816 				goto done;
    817 			}
    818 
    819 			DPRINTFN(3, ("ulptread: TIMEOUT n %d nread %d error %d\n",
    820 				     n, nread, error));
    821 			/*
    822 			 * Don't set error until we understand why
    823 			 * this happens.
    824 			 */
    825 			break;
    826 
    827 		case USBD_INTERRUPTED:
    828 			/*
    829 			 * The tsleep in usbd_bulk_transfer was
    830 			 * interrupted.  Reflect it to the caller so
    831 			 * that reading can be interrupted.
    832 			 */
    833 			error = EINTR;
    834 			DPRINTFN(3, ("ulptread: EINTR error %d\n", error));
    835 			goto done;
    836 			break;
    837 
    838 		default:
    839 			/* Assume all other return codes are really errors. */
    840 			error = EIO;
    841 			DPRINTFN(3, ("ulptread: n %d err %d error %d\n",
    842 				     n, err, error));
    843 			goto done;
    844 			break;
    845 		}
    846 		/* XXX KASSERT */
    847 		if (error != 0) {
    848 			printf("ulptread: post-switch error %d != 0", error);
    849 			goto done;
    850 		}
    851 
    852 		if (n > 0) {
    853 			/*
    854 			 * Record progress to enable later choosing
    855 			 * between short reads and EWOULDBLOCK.
    856 			 */
    857 			nread += n;
    858 
    859 			/* Copy to userspace, giving up on any error. */
    860 			error = uiomove(bufp, n, uio);
    861 			if (error != 0)
    862 				break;
    863 		} else {
    864 			/*
    865 			 * We read 0 bytes, and therefore are done,
    866 			 * even if we aren't in nonblocking mode.
    867 			 */
    868 			if (error == 0 && nread == 0)
    869 				error = EWOULDBLOCK;
    870 			DPRINTFN(3, ("ulptread: read 0=>done error %d\n",
    871 				     error));
    872 			goto done;
    873 		}
    874 
    875 		/*
    876 		 * A short transfer indicates no more data will be
    877 		 * forthcoming.  Terminate this read regardless of
    878 		 * whether we are in nonblocking mode.  XXX Reconsider
    879 		 * for blocking mode; maybe we should continue to
    880 		 * block, but maybe it just doesn't make senes to do
    881 		 * blocking reads from devices like this.
    882 		 */
    883 		if (err == USBD_SHORT_XFER) {
    884 			DPRINTFN(3, ("ulptread: SHORT=>done n %d nread %d err %d error %d\n",
    885 				     n, nread, err, error));
    886 			break;
    887 		}
    888 	}
    889 
    890 done:
    891 	DPRINTFN(3, ("ulptread: finished n %d nread %d err %d error %d\n",
    892 			     n, nread, err, error));
    893 	return (error);
    894 }
    895 
    896 int
    897 ulptread(dev_t dev, struct uio *uio, int flags)
    898 {
    899 	struct ulpt_softc *sc;
    900 	int error;
    901 
    902 	USB_GET_SC(ulpt, ULPTUNIT(dev), sc);
    903 
    904 	if (sc->sc_dying)
    905 		return (EIO);
    906 
    907 	sc->sc_refcnt++;
    908 	error = ulpt_do_read(sc, uio, flags);
    909 	if (--sc->sc_refcnt < 0)
    910 		usb_detach_wakeup(USBDEV(sc->sc_dev));
    911 	return (error);
    912 }
    913 
    914 void
    915 ulpt_read_cb(usbd_xfer_handle xfer, usbd_private_handle priv,
    916 	     usbd_status status)
    917 {
    918 	usbd_status err;
    919 	u_int32_t n;
    920 	usbd_private_handle xsc;
    921 	struct ulpt_softc *sc;
    922 
    923 	usbd_get_xfer_status(xfer, &xsc, NULL, &n, &err);
    924 	sc = xsc;
    925 
    926 	DPRINTFN(4, ("ulpt_read_cb: start sc=%p, err=%d n=%d\n", sc, err, n));
    927 
    928 #ifdef ULPT_DEBUG
    929 	if (!err && n > 0)
    930 		DPRINTFN(3, ("ulpt_tick: discarding %d bytes\n", n));
    931 #endif
    932 	if (!err || err == USBD_TIMEOUT)
    933 		usb_callout(sc->sc_read_callout, hz / ULPT_READS_PER_SEC,
    934 			    ulpt_tick, sc);
    935 }
    936 
    937 /*
    938  * For devices which are not opened for reading, this function is
    939  * called continuously to start read bulk transfers to avoid the
    940  * printer overflowing its output buffer.
    941  *
    942  * XXX This should be adapted for continuous reads to allow select to
    943  * work; see do_ulpt_read().
    944  */
    945 void
    946 ulpt_tick(void *xsc)
    947 {
    948 	struct ulpt_softc *sc = xsc;
    949 	usbd_status err;
    950 
    951 	if (sc == NULL || sc->sc_dying)
    952 		return;
    953 
    954 	usbd_setup_xfer(sc->sc_in_xfer, sc->sc_in_pipe, sc, sc->sc_in_buf,
    955 			ULPT_BSIZE, USBD_NO_COPY | USBD_SHORT_XFER_OK,
    956 			ULPT_READ_TIMO, ulpt_read_cb);
    957 	err = usbd_transfer(sc->sc_in_xfer);
    958 	DPRINTFN(3, ("ulpt_tick: sc=%p err=%d\n", sc, err));
    959 }
    960 
    961 int
    962 ulptioctl(dev_t dev, u_long cmd, void *data,
    963     int flag, struct lwp *l)
    964 {
    965 	struct ulpt_softc *sc;
    966 
    967 	USB_GET_SC(ulpt, ULPTUNIT(dev), sc);
    968 
    969 	switch (cmd) {
    970 	case FIONBIO:
    971 		return 0;
    972 	}
    973 
    974 	return ENODEV;
    975 }
    976 
    977 #if 0
    978 /* XXX This does not belong here. */
    979 /*
    980  * Print select parts of a IEEE 1284 device ID.
    981  */
    982 void
    983 ieee1284_print_id(char *str)
    984 {
    985 	char *p, *q;
    986 
    987 	for (p = str-1; p; p = strchr(p, ';')) {
    988 		p++;		/* skip ';' */
    989 		if (strncmp(p, "MFG:", 4) == 0 ||
    990 		    strncmp(p, "MANUFACTURER:", 14) == 0 ||
    991 		    strncmp(p, "MDL:", 4) == 0 ||
    992 		    strncmp(p, "MODEL:", 6) == 0) {
    993 			q = strchr(p, ';');
    994 			if (q)
    995 				printf("%.*s", (int)(q - p + 1), p);
    996 		}
    997 	}
    998 }
    999 #endif
   1000 
   1001 #if defined(__FreeBSD__)
   1002 DRIVER_MODULE(ulpt, uhub, ulpt_driver, ulpt_devclass, usbd_driver_load, 0);
   1003 #endif
   1004