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