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