xref: /linux/drivers/usb/class/usblp.c (revision 5fd54ace4721fc5ce2bb5aef6318fcf17f421460)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * usblp.c
4  *
5  * Copyright (c) 1999 Michael Gee	<michael@linuxspecific.com>
6  * Copyright (c) 1999 Pavel Machek	<pavel@ucw.cz>
7  * Copyright (c) 2000 Randy Dunlap	<rdunlap@xenotime.net>
8  * Copyright (c) 2000 Vojtech Pavlik	<vojtech@suse.cz>
9  # Copyright (c) 2001 Pete Zaitcev	<zaitcev@redhat.com>
10  # Copyright (c) 2001 David Paschal	<paschal@rcsis.com>
11  * Copyright (c) 2006 Oliver Neukum	<oliver@neukum.name>
12  *
13  * USB Printer Device Class driver for USB printers and printer cables
14  *
15  * Sponsored by SuSE
16  *
17  * ChangeLog:
18  *	v0.1 - thorough cleaning, URBification, almost a rewrite
19  *	v0.2 - some more cleanups
20  *	v0.3 - cleaner again, waitqueue fixes
21  *	v0.4 - fixes in unidirectional mode
22  *	v0.5 - add DEVICE_ID string support
23  *	v0.6 - never time out
24  *	v0.7 - fixed bulk-IN read and poll (David Paschal)
25  *	v0.8 - add devfs support
26  *	v0.9 - fix unplug-while-open paths
27  *	v0.10- remove sleep_on, fix error on oom (oliver@neukum.org)
28  *	v0.11 - add proto_bias option (Pete Zaitcev)
29  *	v0.12 - add hpoj.sourceforge.net ioctls (David Paschal)
30  *	v0.13 - alloc space for statusbuf (<status> not on stack);
31  *		use usb_alloc_coherent() for read buf & write buf;
32  *      none  - Maintained in Linux kernel after v0.13
33  */
34 
35 /*
36  * This program is free software; you can redistribute it and/or modify
37  * it under the terms of the GNU General Public License as published by
38  * the Free Software Foundation; either version 2 of the License, or
39  * (at your option) any later version.
40  *
41  * This program is distributed in the hope that it will be useful,
42  * but WITHOUT ANY WARRANTY; without even the implied warranty of
43  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
44  * GNU General Public License for more details.
45  *
46  * You should have received a copy of the GNU General Public License
47  * along with this program; if not, write to the Free Software
48  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
49  */
50 
51 #include <linux/module.h>
52 #include <linux/kernel.h>
53 #include <linux/sched/signal.h>
54 #include <linux/signal.h>
55 #include <linux/poll.h>
56 #include <linux/slab.h>
57 #include <linux/lp.h>
58 #include <linux/mutex.h>
59 #undef DEBUG
60 #include <linux/usb.h>
61 #include <linux/usb/ch9.h>
62 #include <linux/ratelimit.h>
63 
64 /*
65  * Version Information
66  */
67 #define DRIVER_AUTHOR "Michael Gee, Pavel Machek, Vojtech Pavlik, Randy Dunlap, Pete Zaitcev, David Paschal"
68 #define DRIVER_DESC "USB Printer Device Class driver"
69 
70 #define USBLP_BUF_SIZE		8192
71 #define USBLP_BUF_SIZE_IN	1024
72 #define USBLP_DEVICE_ID_SIZE	1024
73 
74 /* ioctls: */
75 #define IOCNR_GET_DEVICE_ID		1
76 #define IOCNR_GET_PROTOCOLS		2
77 #define IOCNR_SET_PROTOCOL		3
78 #define IOCNR_HP_SET_CHANNEL		4
79 #define IOCNR_GET_BUS_ADDRESS		5
80 #define IOCNR_GET_VID_PID		6
81 #define IOCNR_SOFT_RESET		7
82 /* Get device_id string: */
83 #define LPIOC_GET_DEVICE_ID(len) _IOC(_IOC_READ, 'P', IOCNR_GET_DEVICE_ID, len)
84 /* The following ioctls were added for http://hpoj.sourceforge.net:
85  * Get two-int array:
86  * [0]=current protocol
87  *     (1=USB_CLASS_PRINTER/1/1, 2=USB_CLASS_PRINTER/1/2,
88  *         3=USB_CLASS_PRINTER/1/3),
89  * [1]=supported protocol mask (mask&(1<<n)!=0 means
90  *     USB_CLASS_PRINTER/1/n supported):
91  */
92 #define LPIOC_GET_PROTOCOLS(len) _IOC(_IOC_READ, 'P', IOCNR_GET_PROTOCOLS, len)
93 /*
94  * Set protocol
95  *     (arg: 1=USB_CLASS_PRINTER/1/1, 2=USB_CLASS_PRINTER/1/2,
96  *         3=USB_CLASS_PRINTER/1/3):
97  */
98 #define LPIOC_SET_PROTOCOL _IOC(_IOC_WRITE, 'P', IOCNR_SET_PROTOCOL, 0)
99 /* Set channel number (HP Vendor-specific command): */
100 #define LPIOC_HP_SET_CHANNEL _IOC(_IOC_WRITE, 'P', IOCNR_HP_SET_CHANNEL, 0)
101 /* Get two-int array: [0]=bus number, [1]=device address: */
102 #define LPIOC_GET_BUS_ADDRESS(len) _IOC(_IOC_READ, 'P', IOCNR_GET_BUS_ADDRESS, len)
103 /* Get two-int array: [0]=vendor ID, [1]=product ID: */
104 #define LPIOC_GET_VID_PID(len) _IOC(_IOC_READ, 'P', IOCNR_GET_VID_PID, len)
105 /* Perform class specific soft reset */
106 #define LPIOC_SOFT_RESET _IOC(_IOC_NONE, 'P', IOCNR_SOFT_RESET, 0);
107 
108 /*
109  * A DEVICE_ID string may include the printer's serial number.
110  * It should end with a semi-colon (';').
111  * An example from an HP 970C DeskJet printer is (this is one long string,
112  * with the serial number changed):
113 MFG:HEWLETT-PACKARD;MDL:DESKJET 970C;CMD:MLC,PCL,PML;CLASS:PRINTER;DESCRIPTION:Hewlett-Packard DeskJet 970C;SERN:US970CSEPROF;VSTATUS:$HB0$NC0,ff,DN,IDLE,CUT,K1,C0,DP,NR,KP000,CP027;VP:0800,FL,B0;VJ:                    ;
114  */
115 
116 /*
117  * USB Printer Requests
118  */
119 
120 #define USBLP_REQ_GET_ID			0x00
121 #define USBLP_REQ_GET_STATUS			0x01
122 #define USBLP_REQ_RESET				0x02
123 #define USBLP_REQ_HP_CHANNEL_CHANGE_REQUEST	0x00	/* HP Vendor-specific */
124 
125 #define USBLP_MINORS		16
126 #define USBLP_MINOR_BASE	0
127 
128 #define USBLP_CTL_TIMEOUT	5000			/* 5 seconds */
129 
130 #define USBLP_FIRST_PROTOCOL	1
131 #define USBLP_LAST_PROTOCOL	3
132 #define USBLP_MAX_PROTOCOLS	(USBLP_LAST_PROTOCOL+1)
133 
134 /*
135  * some arbitrary status buffer size;
136  * need a status buffer that is allocated via kmalloc(), not on stack
137  */
138 #define STATUS_BUF_SIZE		8
139 
140 /*
141  * Locks down the locking order:
142  * ->wmut locks wstatus.
143  * ->mut locks the whole usblp, except [rw]complete, and thus, by indirection,
144  * [rw]status. We only touch status when we know the side idle.
145  * ->lock locks what interrupt accesses.
146  */
147 struct usblp {
148 	struct usb_device	*dev;			/* USB device */
149 	struct mutex		wmut;
150 	struct mutex		mut;
151 	spinlock_t		lock;		/* locks rcomplete, wcomplete */
152 	char			*readbuf;		/* read transfer_buffer */
153 	char			*statusbuf;		/* status transfer_buffer */
154 	struct usb_anchor	urbs;
155 	wait_queue_head_t	rwait, wwait;
156 	int			readcount;		/* Counter for reads */
157 	int			ifnum;			/* Interface number */
158 	struct usb_interface	*intf;			/* The interface */
159 	/*
160 	 * Alternate-setting numbers and endpoints for each protocol
161 	 * (USB_CLASS_PRINTER/1/{index=1,2,3}) that the device supports:
162 	 */
163 	struct {
164 		int				alt_setting;
165 		struct usb_endpoint_descriptor	*epwrite;
166 		struct usb_endpoint_descriptor	*epread;
167 	}			protocol[USBLP_MAX_PROTOCOLS];
168 	int			current_protocol;
169 	int			minor;			/* minor number of device */
170 	int			wcomplete, rcomplete;
171 	int			wstatus;	/* bytes written or error */
172 	int			rstatus;	/* bytes ready or error */
173 	unsigned int		quirks;			/* quirks flags */
174 	unsigned int		flags;			/* mode flags */
175 	unsigned char		used;			/* True if open */
176 	unsigned char		present;		/* True if not disconnected */
177 	unsigned char		bidir;			/* interface is bidirectional */
178 	unsigned char		no_paper;		/* Paper Out happened */
179 	unsigned char		*device_id_string;	/* IEEE 1284 DEVICE ID string (ptr) */
180 							/* first 2 bytes are (big-endian) length */
181 };
182 
183 #ifdef DEBUG
184 static void usblp_dump(struct usblp *usblp)
185 {
186 	struct device *dev = &usblp->intf->dev;
187 	int p;
188 
189 	dev_dbg(dev, "usblp=0x%p\n", usblp);
190 	dev_dbg(dev, "dev=0x%p\n", usblp->dev);
191 	dev_dbg(dev, "present=%d\n", usblp->present);
192 	dev_dbg(dev, "readbuf=0x%p\n", usblp->readbuf);
193 	dev_dbg(dev, "readcount=%d\n", usblp->readcount);
194 	dev_dbg(dev, "ifnum=%d\n", usblp->ifnum);
195 	for (p = USBLP_FIRST_PROTOCOL; p <= USBLP_LAST_PROTOCOL; p++) {
196 		dev_dbg(dev, "protocol[%d].alt_setting=%d\n", p,
197 			usblp->protocol[p].alt_setting);
198 		dev_dbg(dev, "protocol[%d].epwrite=%p\n", p,
199 			usblp->protocol[p].epwrite);
200 		dev_dbg(dev, "protocol[%d].epread=%p\n", p,
201 			usblp->protocol[p].epread);
202 	}
203 	dev_dbg(dev, "current_protocol=%d\n", usblp->current_protocol);
204 	dev_dbg(dev, "minor=%d\n", usblp->minor);
205 	dev_dbg(dev, "wstatus=%d\n", usblp->wstatus);
206 	dev_dbg(dev, "rstatus=%d\n", usblp->rstatus);
207 	dev_dbg(dev, "quirks=%d\n", usblp->quirks);
208 	dev_dbg(dev, "used=%d\n", usblp->used);
209 	dev_dbg(dev, "bidir=%d\n", usblp->bidir);
210 	dev_dbg(dev, "device_id_string=\"%s\"\n",
211 		usblp->device_id_string ?
212 			usblp->device_id_string + 2 :
213 			(unsigned char *)"(null)");
214 }
215 #endif
216 
217 /* Quirks: various printer quirks are handled by this table & its flags. */
218 
219 struct quirk_printer_struct {
220 	__u16 vendorId;
221 	__u16 productId;
222 	unsigned int quirks;
223 };
224 
225 #define USBLP_QUIRK_BIDIR	0x1	/* reports bidir but requires unidirectional mode (no INs/reads) */
226 #define USBLP_QUIRK_USB_INIT	0x2	/* needs vendor USB init string */
227 #define USBLP_QUIRK_BAD_CLASS	0x4	/* descriptor uses vendor-specific Class or SubClass */
228 
229 static const struct quirk_printer_struct quirk_printers[] = {
230 	{ 0x03f0, 0x0004, USBLP_QUIRK_BIDIR }, /* HP DeskJet 895C */
231 	{ 0x03f0, 0x0104, USBLP_QUIRK_BIDIR }, /* HP DeskJet 880C */
232 	{ 0x03f0, 0x0204, USBLP_QUIRK_BIDIR }, /* HP DeskJet 815C */
233 	{ 0x03f0, 0x0304, USBLP_QUIRK_BIDIR }, /* HP DeskJet 810C/812C */
234 	{ 0x03f0, 0x0404, USBLP_QUIRK_BIDIR }, /* HP DeskJet 830C */
235 	{ 0x03f0, 0x0504, USBLP_QUIRK_BIDIR }, /* HP DeskJet 885C */
236 	{ 0x03f0, 0x0604, USBLP_QUIRK_BIDIR }, /* HP DeskJet 840C */
237 	{ 0x03f0, 0x0804, USBLP_QUIRK_BIDIR }, /* HP DeskJet 816C */
238 	{ 0x03f0, 0x1104, USBLP_QUIRK_BIDIR }, /* HP Deskjet 959C */
239 	{ 0x0409, 0xefbe, USBLP_QUIRK_BIDIR }, /* NEC Picty900 (HP OEM) */
240 	{ 0x0409, 0xbef4, USBLP_QUIRK_BIDIR }, /* NEC Picty760 (HP OEM) */
241 	{ 0x0409, 0xf0be, USBLP_QUIRK_BIDIR }, /* NEC Picty920 (HP OEM) */
242 	{ 0x0409, 0xf1be, USBLP_QUIRK_BIDIR }, /* NEC Picty800 (HP OEM) */
243 	{ 0x0482, 0x0010, USBLP_QUIRK_BIDIR }, /* Kyocera Mita FS 820, by zut <kernel@zut.de> */
244 	{ 0x04f9, 0x000d, USBLP_QUIRK_BIDIR }, /* Brother Industries, Ltd HL-1440 Laser Printer */
245 	{ 0x04b8, 0x0202, USBLP_QUIRK_BAD_CLASS }, /* Seiko Epson Receipt Printer M129C */
246 	{ 0, 0 }
247 };
248 
249 static int usblp_wwait(struct usblp *usblp, int nonblock);
250 static int usblp_wtest(struct usblp *usblp, int nonblock);
251 static int usblp_rwait_and_lock(struct usblp *usblp, int nonblock);
252 static int usblp_rtest(struct usblp *usblp, int nonblock);
253 static int usblp_submit_read(struct usblp *usblp);
254 static int usblp_select_alts(struct usblp *usblp);
255 static int usblp_set_protocol(struct usblp *usblp, int protocol);
256 static int usblp_cache_device_id_string(struct usblp *usblp);
257 
258 /* forward reference to make our lives easier */
259 static struct usb_driver usblp_driver;
260 static DEFINE_MUTEX(usblp_mutex);	/* locks the existence of usblp's */
261 
262 /*
263  * Functions for usblp control messages.
264  */
265 
266 static int usblp_ctrl_msg(struct usblp *usblp, int request, int type, int dir, int recip, int value, void *buf, int len)
267 {
268 	int retval;
269 	int index = usblp->ifnum;
270 
271 	/* High byte has the interface index.
272 	   Low byte has the alternate setting.
273 	 */
274 	if ((request == USBLP_REQ_GET_ID) && (type == USB_TYPE_CLASS))
275 		index = (usblp->ifnum<<8)|usblp->protocol[usblp->current_protocol].alt_setting;
276 
277 	retval = usb_control_msg(usblp->dev,
278 		dir ? usb_rcvctrlpipe(usblp->dev, 0) : usb_sndctrlpipe(usblp->dev, 0),
279 		request, type | dir | recip, value, index, buf, len, USBLP_CTL_TIMEOUT);
280 	dev_dbg(&usblp->intf->dev,
281 		"usblp_control_msg: rq: 0x%02x dir: %d recip: %d value: %d idx: %d len: %#x result: %d\n",
282 		request, !!dir, recip, value, index, len, retval);
283 	return retval < 0 ? retval : 0;
284 }
285 
286 #define usblp_read_status(usblp, status)\
287 	usblp_ctrl_msg(usblp, USBLP_REQ_GET_STATUS, USB_TYPE_CLASS, USB_DIR_IN, USB_RECIP_INTERFACE, 0, status, 1)
288 #define usblp_get_id(usblp, config, id, maxlen)\
289 	usblp_ctrl_msg(usblp, USBLP_REQ_GET_ID, USB_TYPE_CLASS, USB_DIR_IN, USB_RECIP_INTERFACE, config, id, maxlen)
290 #define usblp_reset(usblp)\
291 	usblp_ctrl_msg(usblp, USBLP_REQ_RESET, USB_TYPE_CLASS, USB_DIR_OUT, USB_RECIP_OTHER, 0, NULL, 0)
292 
293 #define usblp_hp_channel_change_request(usblp, channel, buffer) \
294 	usblp_ctrl_msg(usblp, USBLP_REQ_HP_CHANNEL_CHANGE_REQUEST, USB_TYPE_VENDOR, USB_DIR_IN, USB_RECIP_INTERFACE, channel, buffer, 1)
295 
296 /*
297  * See the description for usblp_select_alts() below for the usage
298  * explanation.  Look into your /sys/kernel/debug/usb/devices and dmesg in
299  * case of any trouble.
300  */
301 static int proto_bias = -1;
302 
303 /*
304  * URB callback.
305  */
306 
307 static void usblp_bulk_read(struct urb *urb)
308 {
309 	struct usblp *usblp = urb->context;
310 	int status = urb->status;
311 
312 	if (usblp->present && usblp->used) {
313 		if (status)
314 			printk(KERN_WARNING "usblp%d: "
315 			    "nonzero read bulk status received: %d\n",
316 			    usblp->minor, status);
317 	}
318 	spin_lock(&usblp->lock);
319 	if (status < 0)
320 		usblp->rstatus = status;
321 	else
322 		usblp->rstatus = urb->actual_length;
323 	usblp->rcomplete = 1;
324 	wake_up(&usblp->rwait);
325 	spin_unlock(&usblp->lock);
326 
327 	usb_free_urb(urb);
328 }
329 
330 static void usblp_bulk_write(struct urb *urb)
331 {
332 	struct usblp *usblp = urb->context;
333 	int status = urb->status;
334 
335 	if (usblp->present && usblp->used) {
336 		if (status)
337 			printk(KERN_WARNING "usblp%d: "
338 			    "nonzero write bulk status received: %d\n",
339 			    usblp->minor, status);
340 	}
341 	spin_lock(&usblp->lock);
342 	if (status < 0)
343 		usblp->wstatus = status;
344 	else
345 		usblp->wstatus = urb->actual_length;
346 	usblp->no_paper = 0;
347 	usblp->wcomplete = 1;
348 	wake_up(&usblp->wwait);
349 	spin_unlock(&usblp->lock);
350 
351 	usb_free_urb(urb);
352 }
353 
354 /*
355  * Get and print printer errors.
356  */
357 
358 static const char *usblp_messages[] = { "ok", "out of paper", "off-line", "on fire" };
359 
360 static int usblp_check_status(struct usblp *usblp, int err)
361 {
362 	unsigned char status, newerr = 0;
363 	int error;
364 
365 	mutex_lock(&usblp->mut);
366 	if ((error = usblp_read_status(usblp, usblp->statusbuf)) < 0) {
367 		mutex_unlock(&usblp->mut);
368 		printk_ratelimited(KERN_ERR
369 				"usblp%d: error %d reading printer status\n",
370 				usblp->minor, error);
371 		return 0;
372 	}
373 	status = *usblp->statusbuf;
374 	mutex_unlock(&usblp->mut);
375 
376 	if (~status & LP_PERRORP)
377 		newerr = 3;
378 	if (status & LP_POUTPA)
379 		newerr = 1;
380 	if (~status & LP_PSELECD)
381 		newerr = 2;
382 
383 	if (newerr != err) {
384 		printk(KERN_INFO "usblp%d: %s\n",
385 		   usblp->minor, usblp_messages[newerr]);
386 	}
387 
388 	return newerr;
389 }
390 
391 static int handle_bidir(struct usblp *usblp)
392 {
393 	if (usblp->bidir && usblp->used) {
394 		if (usblp_submit_read(usblp) < 0)
395 			return -EIO;
396 	}
397 	return 0;
398 }
399 
400 /*
401  * File op functions.
402  */
403 
404 static int usblp_open(struct inode *inode, struct file *file)
405 {
406 	int minor = iminor(inode);
407 	struct usblp *usblp;
408 	struct usb_interface *intf;
409 	int retval;
410 
411 	if (minor < 0)
412 		return -ENODEV;
413 
414 	mutex_lock(&usblp_mutex);
415 
416 	retval = -ENODEV;
417 	intf = usb_find_interface(&usblp_driver, minor);
418 	if (!intf)
419 		goto out;
420 	usblp = usb_get_intfdata(intf);
421 	if (!usblp || !usblp->dev || !usblp->present)
422 		goto out;
423 
424 	retval = -EBUSY;
425 	if (usblp->used)
426 		goto out;
427 
428 	/*
429 	 * We do not implement LP_ABORTOPEN/LPABORTOPEN for two reasons:
430 	 *  - We do not want persistent state which close(2) does not clear
431 	 *  - It is not used anyway, according to CUPS people
432 	 */
433 
434 	retval = usb_autopm_get_interface(intf);
435 	if (retval < 0)
436 		goto out;
437 	usblp->used = 1;
438 	file->private_data = usblp;
439 
440 	usblp->wcomplete = 1; /* we begin writeable */
441 	usblp->wstatus = 0;
442 	usblp->rcomplete = 0;
443 
444 	if (handle_bidir(usblp) < 0) {
445 		usb_autopm_put_interface(intf);
446 		usblp->used = 0;
447 		file->private_data = NULL;
448 		retval = -EIO;
449 	}
450 out:
451 	mutex_unlock(&usblp_mutex);
452 	return retval;
453 }
454 
455 static void usblp_cleanup(struct usblp *usblp)
456 {
457 	printk(KERN_INFO "usblp%d: removed\n", usblp->minor);
458 
459 	kfree(usblp->readbuf);
460 	kfree(usblp->device_id_string);
461 	kfree(usblp->statusbuf);
462 	kfree(usblp);
463 }
464 
465 static void usblp_unlink_urbs(struct usblp *usblp)
466 {
467 	usb_kill_anchored_urbs(&usblp->urbs);
468 }
469 
470 static int usblp_release(struct inode *inode, struct file *file)
471 {
472 	struct usblp *usblp = file->private_data;
473 
474 	usblp->flags &= ~LP_ABORT;
475 
476 	mutex_lock(&usblp_mutex);
477 	usblp->used = 0;
478 	if (usblp->present) {
479 		usblp_unlink_urbs(usblp);
480 		usb_autopm_put_interface(usblp->intf);
481 	} else		/* finish cleanup from disconnect */
482 		usblp_cleanup(usblp);
483 	mutex_unlock(&usblp_mutex);
484 	return 0;
485 }
486 
487 /* No kernel lock - fine */
488 static unsigned int usblp_poll(struct file *file, struct poll_table_struct *wait)
489 {
490 	int ret;
491 	unsigned long flags;
492 
493 	struct usblp *usblp = file->private_data;
494 	/* Should we check file->f_mode & FMODE_WRITE before poll_wait()? */
495 	poll_wait(file, &usblp->rwait, wait);
496 	poll_wait(file, &usblp->wwait, wait);
497 	spin_lock_irqsave(&usblp->lock, flags);
498 	ret = ((usblp->bidir && usblp->rcomplete) ? POLLIN  | POLLRDNORM : 0) |
499 	   ((usblp->no_paper || usblp->wcomplete) ? POLLOUT | POLLWRNORM : 0);
500 	spin_unlock_irqrestore(&usblp->lock, flags);
501 	return ret;
502 }
503 
504 static long usblp_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
505 {
506 	struct usblp *usblp = file->private_data;
507 	int length, err, i;
508 	unsigned char newChannel;
509 	int status;
510 	int twoints[2];
511 	int retval = 0;
512 
513 	mutex_lock(&usblp->mut);
514 	if (!usblp->present) {
515 		retval = -ENODEV;
516 		goto done;
517 	}
518 
519 	dev_dbg(&usblp->intf->dev,
520 		"usblp_ioctl: cmd=0x%x (%c nr=%d len=%d dir=%d)\n", cmd,
521 		_IOC_TYPE(cmd), _IOC_NR(cmd), _IOC_SIZE(cmd), _IOC_DIR(cmd));
522 
523 	if (_IOC_TYPE(cmd) == 'P')	/* new-style ioctl number */
524 
525 		switch (_IOC_NR(cmd)) {
526 
527 		case IOCNR_GET_DEVICE_ID: /* get the DEVICE_ID string */
528 			if (_IOC_DIR(cmd) != _IOC_READ) {
529 				retval = -EINVAL;
530 				goto done;
531 			}
532 
533 			length = usblp_cache_device_id_string(usblp);
534 			if (length < 0) {
535 				retval = length;
536 				goto done;
537 			}
538 			if (length > _IOC_SIZE(cmd))
539 				length = _IOC_SIZE(cmd); /* truncate */
540 
541 			if (copy_to_user((void __user *) arg,
542 					usblp->device_id_string,
543 					(unsigned long) length)) {
544 				retval = -EFAULT;
545 				goto done;
546 			}
547 
548 			break;
549 
550 		case IOCNR_GET_PROTOCOLS:
551 			if (_IOC_DIR(cmd) != _IOC_READ ||
552 			    _IOC_SIZE(cmd) < sizeof(twoints)) {
553 				retval = -EINVAL;
554 				goto done;
555 			}
556 
557 			twoints[0] = usblp->current_protocol;
558 			twoints[1] = 0;
559 			for (i = USBLP_FIRST_PROTOCOL;
560 			     i <= USBLP_LAST_PROTOCOL; i++) {
561 				if (usblp->protocol[i].alt_setting >= 0)
562 					twoints[1] |= (1<<i);
563 			}
564 
565 			if (copy_to_user((void __user *)arg,
566 					(unsigned char *)twoints,
567 					sizeof(twoints))) {
568 				retval = -EFAULT;
569 				goto done;
570 			}
571 
572 			break;
573 
574 		case IOCNR_SET_PROTOCOL:
575 			if (_IOC_DIR(cmd) != _IOC_WRITE) {
576 				retval = -EINVAL;
577 				goto done;
578 			}
579 
580 #ifdef DEBUG
581 			if (arg == -10) {
582 				usblp_dump(usblp);
583 				break;
584 			}
585 #endif
586 
587 			usblp_unlink_urbs(usblp);
588 			retval = usblp_set_protocol(usblp, arg);
589 			if (retval < 0) {
590 				usblp_set_protocol(usblp,
591 					usblp->current_protocol);
592 			}
593 			break;
594 
595 		case IOCNR_HP_SET_CHANNEL:
596 			if (_IOC_DIR(cmd) != _IOC_WRITE ||
597 			    le16_to_cpu(usblp->dev->descriptor.idVendor) != 0x03F0 ||
598 			    usblp->quirks & USBLP_QUIRK_BIDIR) {
599 				retval = -EINVAL;
600 				goto done;
601 			}
602 
603 			err = usblp_hp_channel_change_request(usblp,
604 				arg, &newChannel);
605 			if (err < 0) {
606 				dev_err(&usblp->dev->dev,
607 					"usblp%d: error = %d setting "
608 					"HP channel\n",
609 					usblp->minor, err);
610 				retval = -EIO;
611 				goto done;
612 			}
613 
614 			dev_dbg(&usblp->intf->dev,
615 				"usblp%d requested/got HP channel %ld/%d\n",
616 				usblp->minor, arg, newChannel);
617 			break;
618 
619 		case IOCNR_GET_BUS_ADDRESS:
620 			if (_IOC_DIR(cmd) != _IOC_READ ||
621 			    _IOC_SIZE(cmd) < sizeof(twoints)) {
622 				retval = -EINVAL;
623 				goto done;
624 			}
625 
626 			twoints[0] = usblp->dev->bus->busnum;
627 			twoints[1] = usblp->dev->devnum;
628 			if (copy_to_user((void __user *)arg,
629 					(unsigned char *)twoints,
630 					sizeof(twoints))) {
631 				retval = -EFAULT;
632 				goto done;
633 			}
634 
635 			dev_dbg(&usblp->intf->dev,
636 				"usblp%d is bus=%d, device=%d\n",
637 				usblp->minor, twoints[0], twoints[1]);
638 			break;
639 
640 		case IOCNR_GET_VID_PID:
641 			if (_IOC_DIR(cmd) != _IOC_READ ||
642 			    _IOC_SIZE(cmd) < sizeof(twoints)) {
643 				retval = -EINVAL;
644 				goto done;
645 			}
646 
647 			twoints[0] = le16_to_cpu(usblp->dev->descriptor.idVendor);
648 			twoints[1] = le16_to_cpu(usblp->dev->descriptor.idProduct);
649 			if (copy_to_user((void __user *)arg,
650 					(unsigned char *)twoints,
651 					sizeof(twoints))) {
652 				retval = -EFAULT;
653 				goto done;
654 			}
655 
656 			dev_dbg(&usblp->intf->dev,
657 				"usblp%d is VID=0x%4.4X, PID=0x%4.4X\n",
658 				usblp->minor, twoints[0], twoints[1]);
659 			break;
660 
661 		case IOCNR_SOFT_RESET:
662 			if (_IOC_DIR(cmd) != _IOC_NONE) {
663 				retval = -EINVAL;
664 				goto done;
665 			}
666 			retval = usblp_reset(usblp);
667 			break;
668 		default:
669 			retval = -ENOTTY;
670 		}
671 	else	/* old-style ioctl value */
672 		switch (cmd) {
673 
674 		case LPGETSTATUS:
675 			retval = usblp_read_status(usblp, usblp->statusbuf);
676 			if (retval) {
677 				printk_ratelimited(KERN_ERR "usblp%d:"
678 					    "failed reading printer status (%d)\n",
679 					    usblp->minor, retval);
680 				retval = -EIO;
681 				goto done;
682 			}
683 			status = *usblp->statusbuf;
684 			if (copy_to_user((void __user *)arg, &status, sizeof(int)))
685 				retval = -EFAULT;
686 			break;
687 
688 		case LPABORT:
689 			if (arg)
690 				usblp->flags |= LP_ABORT;
691 			else
692 				usblp->flags &= ~LP_ABORT;
693 			break;
694 
695 		default:
696 			retval = -ENOTTY;
697 		}
698 
699 done:
700 	mutex_unlock(&usblp->mut);
701 	return retval;
702 }
703 
704 static struct urb *usblp_new_writeurb(struct usblp *usblp, int transfer_length)
705 {
706 	struct urb *urb;
707 	char *writebuf;
708 
709 	writebuf = kmalloc(transfer_length, GFP_KERNEL);
710 	if (writebuf == NULL)
711 		return NULL;
712 	urb = usb_alloc_urb(0, GFP_KERNEL);
713 	if (urb == NULL) {
714 		kfree(writebuf);
715 		return NULL;
716 	}
717 
718 	usb_fill_bulk_urb(urb, usblp->dev,
719 		usb_sndbulkpipe(usblp->dev,
720 		 usblp->protocol[usblp->current_protocol].epwrite->bEndpointAddress),
721 		writebuf, transfer_length, usblp_bulk_write, usblp);
722 	urb->transfer_flags |= URB_FREE_BUFFER;
723 
724 	return urb;
725 }
726 
727 static ssize_t usblp_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos)
728 {
729 	struct usblp *usblp = file->private_data;
730 	struct urb *writeurb;
731 	int rv;
732 	int transfer_length;
733 	ssize_t writecount = 0;
734 
735 	if (mutex_lock_interruptible(&usblp->wmut)) {
736 		rv = -EINTR;
737 		goto raise_biglock;
738 	}
739 	if ((rv = usblp_wwait(usblp, !!(file->f_flags & O_NONBLOCK))) < 0)
740 		goto raise_wait;
741 
742 	while (writecount < count) {
743 		/*
744 		 * Step 1: Submit next block.
745 		 */
746 		if ((transfer_length = count - writecount) > USBLP_BUF_SIZE)
747 			transfer_length = USBLP_BUF_SIZE;
748 
749 		rv = -ENOMEM;
750 		writeurb = usblp_new_writeurb(usblp, transfer_length);
751 		if (writeurb == NULL)
752 			goto raise_urb;
753 		usb_anchor_urb(writeurb, &usblp->urbs);
754 
755 		if (copy_from_user(writeurb->transfer_buffer,
756 				   buffer + writecount, transfer_length)) {
757 			rv = -EFAULT;
758 			goto raise_badaddr;
759 		}
760 
761 		spin_lock_irq(&usblp->lock);
762 		usblp->wcomplete = 0;
763 		spin_unlock_irq(&usblp->lock);
764 		if ((rv = usb_submit_urb(writeurb, GFP_KERNEL)) < 0) {
765 			usblp->wstatus = 0;
766 			spin_lock_irq(&usblp->lock);
767 			usblp->no_paper = 0;
768 			usblp->wcomplete = 1;
769 			wake_up(&usblp->wwait);
770 			spin_unlock_irq(&usblp->lock);
771 			if (rv != -ENOMEM)
772 				rv = -EIO;
773 			goto raise_submit;
774 		}
775 
776 		/*
777 		 * Step 2: Wait for transfer to end, collect results.
778 		 */
779 		rv = usblp_wwait(usblp, !!(file->f_flags&O_NONBLOCK));
780 		if (rv < 0) {
781 			if (rv == -EAGAIN) {
782 				/* Presume that it's going to complete well. */
783 				writecount += transfer_length;
784 			}
785 			if (rv == -ENOSPC) {
786 				spin_lock_irq(&usblp->lock);
787 				usblp->no_paper = 1;	/* Mark for poll(2) */
788 				spin_unlock_irq(&usblp->lock);
789 				writecount += transfer_length;
790 			}
791 			/* Leave URB dangling, to be cleaned on close. */
792 			goto collect_error;
793 		}
794 
795 		if (usblp->wstatus < 0) {
796 			rv = -EIO;
797 			goto collect_error;
798 		}
799 		/*
800 		 * This is critical: it must be our URB, not other writer's.
801 		 * The wmut exists mainly to cover us here.
802 		 */
803 		writecount += usblp->wstatus;
804 	}
805 
806 	mutex_unlock(&usblp->wmut);
807 	return writecount;
808 
809 raise_submit:
810 raise_badaddr:
811 	usb_unanchor_urb(writeurb);
812 	usb_free_urb(writeurb);
813 raise_urb:
814 raise_wait:
815 collect_error:		/* Out of raise sequence */
816 	mutex_unlock(&usblp->wmut);
817 raise_biglock:
818 	return writecount ? writecount : rv;
819 }
820 
821 /*
822  * Notice that we fail to restart in a few cases: on EFAULT, on restart
823  * error, etc. This is the historical behaviour. In all such cases we return
824  * EIO, and applications loop in order to get the new read going.
825  */
826 static ssize_t usblp_read(struct file *file, char __user *buffer, size_t len, loff_t *ppos)
827 {
828 	struct usblp *usblp = file->private_data;
829 	ssize_t count;
830 	ssize_t avail;
831 	int rv;
832 
833 	if (!usblp->bidir)
834 		return -EINVAL;
835 
836 	rv = usblp_rwait_and_lock(usblp, !!(file->f_flags & O_NONBLOCK));
837 	if (rv < 0)
838 		return rv;
839 
840 	if ((avail = usblp->rstatus) < 0) {
841 		printk(KERN_ERR "usblp%d: error %d reading from printer\n",
842 		    usblp->minor, (int)avail);
843 		usblp_submit_read(usblp);
844 		count = -EIO;
845 		goto done;
846 	}
847 
848 	count = len < avail - usblp->readcount ? len : avail - usblp->readcount;
849 	if (count != 0 &&
850 	    copy_to_user(buffer, usblp->readbuf + usblp->readcount, count)) {
851 		count = -EFAULT;
852 		goto done;
853 	}
854 
855 	if ((usblp->readcount += count) == avail) {
856 		if (usblp_submit_read(usblp) < 0) {
857 			/* We don't want to leak USB return codes into errno. */
858 			if (count == 0)
859 				count = -EIO;
860 			goto done;
861 		}
862 	}
863 
864 done:
865 	mutex_unlock(&usblp->mut);
866 	return count;
867 }
868 
869 /*
870  * Wait for the write path to come idle.
871  * This is called under the ->wmut, so the idle path stays idle.
872  *
873  * Our write path has a peculiar property: it does not buffer like a tty,
874  * but waits for the write to succeed. This allows our ->release to bug out
875  * without waiting for writes to drain. But it obviously does not work
876  * when O_NONBLOCK is set. So, applications setting O_NONBLOCK must use
877  * select(2) or poll(2) to wait for the buffer to drain before closing.
878  * Alternatively, set blocking mode with fcntl and issue a zero-size write.
879  */
880 static int usblp_wwait(struct usblp *usblp, int nonblock)
881 {
882 	DECLARE_WAITQUEUE(waita, current);
883 	int rc;
884 	int err = 0;
885 
886 	add_wait_queue(&usblp->wwait, &waita);
887 	for (;;) {
888 		if (mutex_lock_interruptible(&usblp->mut)) {
889 			rc = -EINTR;
890 			break;
891 		}
892 		set_current_state(TASK_INTERRUPTIBLE);
893 		rc = usblp_wtest(usblp, nonblock);
894 		mutex_unlock(&usblp->mut);
895 		if (rc <= 0)
896 			break;
897 
898 		if (schedule_timeout(msecs_to_jiffies(1500)) == 0) {
899 			if (usblp->flags & LP_ABORT) {
900 				err = usblp_check_status(usblp, err);
901 				if (err == 1) {	/* Paper out */
902 					rc = -ENOSPC;
903 					break;
904 				}
905 			} else {
906 				/* Prod the printer, Gentoo#251237. */
907 				mutex_lock(&usblp->mut);
908 				usblp_read_status(usblp, usblp->statusbuf);
909 				mutex_unlock(&usblp->mut);
910 			}
911 		}
912 	}
913 	set_current_state(TASK_RUNNING);
914 	remove_wait_queue(&usblp->wwait, &waita);
915 	return rc;
916 }
917 
918 static int usblp_wtest(struct usblp *usblp, int nonblock)
919 {
920 	unsigned long flags;
921 
922 	if (!usblp->present)
923 		return -ENODEV;
924 	if (signal_pending(current))
925 		return -EINTR;
926 	spin_lock_irqsave(&usblp->lock, flags);
927 	if (usblp->wcomplete) {
928 		spin_unlock_irqrestore(&usblp->lock, flags);
929 		return 0;
930 	}
931 	spin_unlock_irqrestore(&usblp->lock, flags);
932 	if (nonblock)
933 		return -EAGAIN;
934 	return 1;
935 }
936 
937 /*
938  * Wait for read bytes to become available. This probably should have been
939  * called usblp_r_lock_and_wait(), because we lock first. But it's a traditional
940  * name for functions which lock and return.
941  *
942  * We do not use wait_event_interruptible because it makes locking iffy.
943  */
944 static int usblp_rwait_and_lock(struct usblp *usblp, int nonblock)
945 {
946 	DECLARE_WAITQUEUE(waita, current);
947 	int rc;
948 
949 	add_wait_queue(&usblp->rwait, &waita);
950 	for (;;) {
951 		if (mutex_lock_interruptible(&usblp->mut)) {
952 			rc = -EINTR;
953 			break;
954 		}
955 		set_current_state(TASK_INTERRUPTIBLE);
956 		if ((rc = usblp_rtest(usblp, nonblock)) < 0) {
957 			mutex_unlock(&usblp->mut);
958 			break;
959 		}
960 		if (rc == 0)	/* Keep it locked */
961 			break;
962 		mutex_unlock(&usblp->mut);
963 		schedule();
964 	}
965 	set_current_state(TASK_RUNNING);
966 	remove_wait_queue(&usblp->rwait, &waita);
967 	return rc;
968 }
969 
970 static int usblp_rtest(struct usblp *usblp, int nonblock)
971 {
972 	unsigned long flags;
973 
974 	if (!usblp->present)
975 		return -ENODEV;
976 	if (signal_pending(current))
977 		return -EINTR;
978 	spin_lock_irqsave(&usblp->lock, flags);
979 	if (usblp->rcomplete) {
980 		spin_unlock_irqrestore(&usblp->lock, flags);
981 		return 0;
982 	}
983 	spin_unlock_irqrestore(&usblp->lock, flags);
984 	if (nonblock)
985 		return -EAGAIN;
986 	return 1;
987 }
988 
989 /*
990  * Please check ->bidir and other such things outside for now.
991  */
992 static int usblp_submit_read(struct usblp *usblp)
993 {
994 	struct urb *urb;
995 	unsigned long flags;
996 	int rc;
997 
998 	rc = -ENOMEM;
999 	urb = usb_alloc_urb(0, GFP_KERNEL);
1000 	if (urb == NULL)
1001 		goto raise_urb;
1002 
1003 	usb_fill_bulk_urb(urb, usblp->dev,
1004 		usb_rcvbulkpipe(usblp->dev,
1005 		  usblp->protocol[usblp->current_protocol].epread->bEndpointAddress),
1006 		usblp->readbuf, USBLP_BUF_SIZE_IN,
1007 		usblp_bulk_read, usblp);
1008 	usb_anchor_urb(urb, &usblp->urbs);
1009 
1010 	spin_lock_irqsave(&usblp->lock, flags);
1011 	usblp->readcount = 0; /* XXX Why here? */
1012 	usblp->rcomplete = 0;
1013 	spin_unlock_irqrestore(&usblp->lock, flags);
1014 	if ((rc = usb_submit_urb(urb, GFP_KERNEL)) < 0) {
1015 		dev_dbg(&usblp->intf->dev, "error submitting urb (%d)\n", rc);
1016 		spin_lock_irqsave(&usblp->lock, flags);
1017 		usblp->rstatus = rc;
1018 		usblp->rcomplete = 1;
1019 		spin_unlock_irqrestore(&usblp->lock, flags);
1020 		goto raise_submit;
1021 	}
1022 
1023 	return 0;
1024 
1025 raise_submit:
1026 	usb_unanchor_urb(urb);
1027 	usb_free_urb(urb);
1028 raise_urb:
1029 	return rc;
1030 }
1031 
1032 /*
1033  * Checks for printers that have quirks, such as requiring unidirectional
1034  * communication but reporting bidirectional; currently some HP printers
1035  * have this flaw (HP 810, 880, 895, etc.), or needing an init string
1036  * sent at each open (like some Epsons).
1037  * Returns 1 if found, 0 if not found.
1038  *
1039  * HP recommended that we use the bidirectional interface but
1040  * don't attempt any bulk IN transfers from the IN endpoint.
1041  * Here's some more detail on the problem:
1042  * The problem is not that it isn't bidirectional though. The problem
1043  * is that if you request a device ID, or status information, while
1044  * the buffers are full, the return data will end up in the print data
1045  * buffer. For example if you make sure you never request the device ID
1046  * while you are sending print data, and you don't try to query the
1047  * printer status every couple of milliseconds, you will probably be OK.
1048  */
1049 static unsigned int usblp_quirks(__u16 vendor, __u16 product)
1050 {
1051 	int i;
1052 
1053 	for (i = 0; quirk_printers[i].vendorId; i++) {
1054 		if (vendor == quirk_printers[i].vendorId &&
1055 		    product == quirk_printers[i].productId)
1056 			return quirk_printers[i].quirks;
1057 	}
1058 	return 0;
1059 }
1060 
1061 static const struct file_operations usblp_fops = {
1062 	.owner =	THIS_MODULE,
1063 	.read =		usblp_read,
1064 	.write =	usblp_write,
1065 	.poll =		usblp_poll,
1066 	.unlocked_ioctl =	usblp_ioctl,
1067 	.compat_ioctl =		usblp_ioctl,
1068 	.open =		usblp_open,
1069 	.release =	usblp_release,
1070 	.llseek =	noop_llseek,
1071 };
1072 
1073 static char *usblp_devnode(struct device *dev, umode_t *mode)
1074 {
1075 	return kasprintf(GFP_KERNEL, "usb/%s", dev_name(dev));
1076 }
1077 
1078 static struct usb_class_driver usblp_class = {
1079 	.name =		"lp%d",
1080 	.devnode =	usblp_devnode,
1081 	.fops =		&usblp_fops,
1082 	.minor_base =	USBLP_MINOR_BASE,
1083 };
1084 
1085 static ssize_t usblp_show_ieee1284_id(struct device *dev, struct device_attribute *attr, char *buf)
1086 {
1087 	struct usb_interface *intf = to_usb_interface(dev);
1088 	struct usblp *usblp = usb_get_intfdata(intf);
1089 
1090 	if (usblp->device_id_string[0] == 0 &&
1091 	    usblp->device_id_string[1] == 0)
1092 		return 0;
1093 
1094 	return sprintf(buf, "%s", usblp->device_id_string+2);
1095 }
1096 
1097 static DEVICE_ATTR(ieee1284_id, S_IRUGO, usblp_show_ieee1284_id, NULL);
1098 
1099 static int usblp_probe(struct usb_interface *intf,
1100 		       const struct usb_device_id *id)
1101 {
1102 	struct usb_device *dev = interface_to_usbdev(intf);
1103 	struct usblp *usblp;
1104 	int protocol;
1105 	int retval;
1106 
1107 	/* Malloc and start initializing usblp structure so we can use it
1108 	 * directly. */
1109 	usblp = kzalloc(sizeof(struct usblp), GFP_KERNEL);
1110 	if (!usblp) {
1111 		retval = -ENOMEM;
1112 		goto abort_ret;
1113 	}
1114 	usblp->dev = dev;
1115 	mutex_init(&usblp->wmut);
1116 	mutex_init(&usblp->mut);
1117 	spin_lock_init(&usblp->lock);
1118 	init_waitqueue_head(&usblp->rwait);
1119 	init_waitqueue_head(&usblp->wwait);
1120 	init_usb_anchor(&usblp->urbs);
1121 	usblp->ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
1122 	usblp->intf = intf;
1123 
1124 	/* Malloc device ID string buffer to the largest expected length,
1125 	 * since we can re-query it on an ioctl and a dynamic string
1126 	 * could change in length. */
1127 	if (!(usblp->device_id_string = kmalloc(USBLP_DEVICE_ID_SIZE, GFP_KERNEL))) {
1128 		retval = -ENOMEM;
1129 		goto abort;
1130 	}
1131 
1132 	/*
1133 	 * Allocate read buffer. We somewhat wastefully
1134 	 * malloc both regardless of bidirectionality, because the
1135 	 * alternate setting can be changed later via an ioctl.
1136 	 */
1137 	if (!(usblp->readbuf = kmalloc(USBLP_BUF_SIZE_IN, GFP_KERNEL))) {
1138 		retval = -ENOMEM;
1139 		goto abort;
1140 	}
1141 
1142 	/* Allocate buffer for printer status */
1143 	usblp->statusbuf = kmalloc(STATUS_BUF_SIZE, GFP_KERNEL);
1144 	if (!usblp->statusbuf) {
1145 		retval = -ENOMEM;
1146 		goto abort;
1147 	}
1148 
1149 	/* Lookup quirks for this printer. */
1150 	usblp->quirks = usblp_quirks(
1151 		le16_to_cpu(dev->descriptor.idVendor),
1152 		le16_to_cpu(dev->descriptor.idProduct));
1153 
1154 	/* Analyze and pick initial alternate settings and endpoints. */
1155 	protocol = usblp_select_alts(usblp);
1156 	if (protocol < 0) {
1157 		dev_dbg(&intf->dev,
1158 			"incompatible printer-class device 0x%4.4X/0x%4.4X\n",
1159 			le16_to_cpu(dev->descriptor.idVendor),
1160 			le16_to_cpu(dev->descriptor.idProduct));
1161 		retval = -ENODEV;
1162 		goto abort;
1163 	}
1164 
1165 	/* Setup the selected alternate setting and endpoints. */
1166 	if (usblp_set_protocol(usblp, protocol) < 0) {
1167 		retval = -ENODEV;	/* ->probe isn't ->ioctl */
1168 		goto abort;
1169 	}
1170 
1171 	/* Retrieve and store the device ID string. */
1172 	usblp_cache_device_id_string(usblp);
1173 	retval = device_create_file(&intf->dev, &dev_attr_ieee1284_id);
1174 	if (retval)
1175 		goto abort_intfdata;
1176 
1177 #ifdef DEBUG
1178 	usblp_check_status(usblp, 0);
1179 #endif
1180 
1181 	usb_set_intfdata(intf, usblp);
1182 
1183 	usblp->present = 1;
1184 
1185 	retval = usb_register_dev(intf, &usblp_class);
1186 	if (retval) {
1187 		dev_err(&intf->dev,
1188 			"usblp: Not able to get a minor (base %u, slice default): %d\n",
1189 			USBLP_MINOR_BASE, retval);
1190 		goto abort_intfdata;
1191 	}
1192 	usblp->minor = intf->minor;
1193 	dev_info(&intf->dev,
1194 		"usblp%d: USB %sdirectional printer dev %d if %d alt %d proto %d vid 0x%4.4X pid 0x%4.4X\n",
1195 		usblp->minor, usblp->bidir ? "Bi" : "Uni", dev->devnum,
1196 		usblp->ifnum,
1197 		usblp->protocol[usblp->current_protocol].alt_setting,
1198 		usblp->current_protocol,
1199 		le16_to_cpu(usblp->dev->descriptor.idVendor),
1200 		le16_to_cpu(usblp->dev->descriptor.idProduct));
1201 
1202 	return 0;
1203 
1204 abort_intfdata:
1205 	usb_set_intfdata(intf, NULL);
1206 	device_remove_file(&intf->dev, &dev_attr_ieee1284_id);
1207 abort:
1208 	kfree(usblp->readbuf);
1209 	kfree(usblp->statusbuf);
1210 	kfree(usblp->device_id_string);
1211 	kfree(usblp);
1212 abort_ret:
1213 	return retval;
1214 }
1215 
1216 /*
1217  * We are a "new" style driver with usb_device_id table,
1218  * but our requirements are too intricate for simple match to handle.
1219  *
1220  * The "proto_bias" option may be used to specify the preferred protocol
1221  * for all USB printers (1=USB_CLASS_PRINTER/1/1, 2=USB_CLASS_PRINTER/1/2,
1222  * 3=USB_CLASS_PRINTER/1/3).  If the device supports the preferred protocol,
1223  * then we bind to it.
1224  *
1225  * The best interface for us is USB_CLASS_PRINTER/1/2, because it
1226  * is compatible with a stream of characters. If we find it, we bind to it.
1227  *
1228  * Note that the people from hpoj.sourceforge.net need to be able to
1229  * bind to USB_CLASS_PRINTER/1/3 (MLC/1284.4), so we provide them ioctls
1230  * for this purpose.
1231  *
1232  * Failing USB_CLASS_PRINTER/1/2, we look for USB_CLASS_PRINTER/1/3,
1233  * even though it's probably not stream-compatible, because this matches
1234  * the behaviour of the old code.
1235  *
1236  * If nothing else, we bind to USB_CLASS_PRINTER/1/1
1237  * - the unidirectional interface.
1238  */
1239 static int usblp_select_alts(struct usblp *usblp)
1240 {
1241 	struct usb_interface *if_alt;
1242 	struct usb_host_interface *ifd;
1243 	struct usb_endpoint_descriptor *epwrite, *epread;
1244 	int p, i;
1245 	int res;
1246 
1247 	if_alt = usblp->intf;
1248 
1249 	for (p = 0; p < USBLP_MAX_PROTOCOLS; p++)
1250 		usblp->protocol[p].alt_setting = -1;
1251 
1252 	/* Find out what we have. */
1253 	for (i = 0; i < if_alt->num_altsetting; i++) {
1254 		ifd = &if_alt->altsetting[i];
1255 
1256 		if (ifd->desc.bInterfaceClass != USB_CLASS_PRINTER ||
1257 		    ifd->desc.bInterfaceSubClass != 1)
1258 			if (!(usblp->quirks & USBLP_QUIRK_BAD_CLASS))
1259 				continue;
1260 
1261 		if (ifd->desc.bInterfaceProtocol < USBLP_FIRST_PROTOCOL ||
1262 		    ifd->desc.bInterfaceProtocol > USBLP_LAST_PROTOCOL)
1263 			continue;
1264 
1265 		/* Look for the expected bulk endpoints. */
1266 		if (ifd->desc.bInterfaceProtocol > 1) {
1267 			res = usb_find_common_endpoints(ifd,
1268 					&epread, &epwrite, NULL, NULL);
1269 		} else {
1270 			epread = NULL;
1271 			res = usb_find_bulk_out_endpoint(ifd, &epwrite);
1272 		}
1273 
1274 		/* Ignore buggy hardware without the right endpoints. */
1275 		if (res)
1276 			continue;
1277 
1278 		/* Turn off reads for buggy bidirectional printers. */
1279 		if (usblp->quirks & USBLP_QUIRK_BIDIR) {
1280 			printk(KERN_INFO "usblp%d: Disabling reads from "
1281 			    "problematic bidirectional printer\n",
1282 			    usblp->minor);
1283 			epread = NULL;
1284 		}
1285 
1286 		usblp->protocol[ifd->desc.bInterfaceProtocol].alt_setting =
1287 				ifd->desc.bAlternateSetting;
1288 		usblp->protocol[ifd->desc.bInterfaceProtocol].epwrite = epwrite;
1289 		usblp->protocol[ifd->desc.bInterfaceProtocol].epread = epread;
1290 	}
1291 
1292 	/* If our requested protocol is supported, then use it. */
1293 	if (proto_bias >= USBLP_FIRST_PROTOCOL &&
1294 	    proto_bias <= USBLP_LAST_PROTOCOL &&
1295 	    usblp->protocol[proto_bias].alt_setting != -1)
1296 		return proto_bias;
1297 
1298 	/* Ordering is important here. */
1299 	if (usblp->protocol[2].alt_setting != -1)
1300 		return 2;
1301 	if (usblp->protocol[1].alt_setting != -1)
1302 		return 1;
1303 	if (usblp->protocol[3].alt_setting != -1)
1304 		return 3;
1305 
1306 	/* If nothing is available, then don't bind to this device. */
1307 	return -1;
1308 }
1309 
1310 static int usblp_set_protocol(struct usblp *usblp, int protocol)
1311 {
1312 	int r, alts;
1313 
1314 	if (protocol < USBLP_FIRST_PROTOCOL || protocol > USBLP_LAST_PROTOCOL)
1315 		return -EINVAL;
1316 
1317 	alts = usblp->protocol[protocol].alt_setting;
1318 	if (alts < 0)
1319 		return -EINVAL;
1320 	r = usb_set_interface(usblp->dev, usblp->ifnum, alts);
1321 	if (r < 0) {
1322 		printk(KERN_ERR "usblp: can't set desired altsetting %d on interface %d\n",
1323 			alts, usblp->ifnum);
1324 		return r;
1325 	}
1326 
1327 	usblp->bidir = (usblp->protocol[protocol].epread != NULL);
1328 	usblp->current_protocol = protocol;
1329 	dev_dbg(&usblp->intf->dev, "usblp%d set protocol %d\n",
1330 		usblp->minor, protocol);
1331 	return 0;
1332 }
1333 
1334 /* Retrieves and caches device ID string.
1335  * Returns length, including length bytes but not null terminator.
1336  * On error, returns a negative errno value. */
1337 static int usblp_cache_device_id_string(struct usblp *usblp)
1338 {
1339 	int err, length;
1340 
1341 	err = usblp_get_id(usblp, 0, usblp->device_id_string, USBLP_DEVICE_ID_SIZE - 1);
1342 	if (err < 0) {
1343 		dev_dbg(&usblp->intf->dev,
1344 			"usblp%d: error = %d reading IEEE-1284 Device ID string\n",
1345 			usblp->minor, err);
1346 		usblp->device_id_string[0] = usblp->device_id_string[1] = '\0';
1347 		return -EIO;
1348 	}
1349 
1350 	/* First two bytes are length in big-endian.
1351 	 * They count themselves, and we copy them into
1352 	 * the user's buffer. */
1353 	length = be16_to_cpu(*((__be16 *)usblp->device_id_string));
1354 	if (length < 2)
1355 		length = 2;
1356 	else if (length >= USBLP_DEVICE_ID_SIZE)
1357 		length = USBLP_DEVICE_ID_SIZE - 1;
1358 	usblp->device_id_string[length] = '\0';
1359 
1360 	dev_dbg(&usblp->intf->dev, "usblp%d Device ID string [len=%d]=\"%s\"\n",
1361 		usblp->minor, length, &usblp->device_id_string[2]);
1362 
1363 	return length;
1364 }
1365 
1366 static void usblp_disconnect(struct usb_interface *intf)
1367 {
1368 	struct usblp *usblp = usb_get_intfdata(intf);
1369 
1370 	usb_deregister_dev(intf, &usblp_class);
1371 
1372 	if (!usblp || !usblp->dev) {
1373 		dev_err(&intf->dev, "bogus disconnect\n");
1374 		BUG();
1375 	}
1376 
1377 	device_remove_file(&intf->dev, &dev_attr_ieee1284_id);
1378 
1379 	mutex_lock(&usblp_mutex);
1380 	mutex_lock(&usblp->mut);
1381 	usblp->present = 0;
1382 	wake_up(&usblp->wwait);
1383 	wake_up(&usblp->rwait);
1384 	usb_set_intfdata(intf, NULL);
1385 
1386 	usblp_unlink_urbs(usblp);
1387 	mutex_unlock(&usblp->mut);
1388 
1389 	if (!usblp->used)
1390 		usblp_cleanup(usblp);
1391 	mutex_unlock(&usblp_mutex);
1392 }
1393 
1394 static int usblp_suspend(struct usb_interface *intf, pm_message_t message)
1395 {
1396 	struct usblp *usblp = usb_get_intfdata(intf);
1397 
1398 	usblp_unlink_urbs(usblp);
1399 #if 0 /* XXX Do we want this? What if someone is reading, should we fail? */
1400 	/* not strictly necessary, but just in case */
1401 	wake_up(&usblp->wwait);
1402 	wake_up(&usblp->rwait);
1403 #endif
1404 
1405 	return 0;
1406 }
1407 
1408 static int usblp_resume(struct usb_interface *intf)
1409 {
1410 	struct usblp *usblp = usb_get_intfdata(intf);
1411 	int r;
1412 
1413 	r = handle_bidir(usblp);
1414 
1415 	return r;
1416 }
1417 
1418 static const struct usb_device_id usblp_ids[] = {
1419 	{ USB_DEVICE_INFO(USB_CLASS_PRINTER, 1, 1) },
1420 	{ USB_DEVICE_INFO(USB_CLASS_PRINTER, 1, 2) },
1421 	{ USB_DEVICE_INFO(USB_CLASS_PRINTER, 1, 3) },
1422 	{ USB_INTERFACE_INFO(USB_CLASS_PRINTER, 1, 1) },
1423 	{ USB_INTERFACE_INFO(USB_CLASS_PRINTER, 1, 2) },
1424 	{ USB_INTERFACE_INFO(USB_CLASS_PRINTER, 1, 3) },
1425 	{ USB_DEVICE(0x04b8, 0x0202) },	/* Seiko Epson Receipt Printer M129C */
1426 	{ }						/* Terminating entry */
1427 };
1428 
1429 MODULE_DEVICE_TABLE(usb, usblp_ids);
1430 
1431 static struct usb_driver usblp_driver = {
1432 	.name =		"usblp",
1433 	.probe =	usblp_probe,
1434 	.disconnect =	usblp_disconnect,
1435 	.suspend =	usblp_suspend,
1436 	.resume =	usblp_resume,
1437 	.id_table =	usblp_ids,
1438 	.supports_autosuspend =	1,
1439 };
1440 
1441 module_usb_driver(usblp_driver);
1442 
1443 MODULE_AUTHOR(DRIVER_AUTHOR);
1444 MODULE_DESCRIPTION(DRIVER_DESC);
1445 module_param(proto_bias, int, S_IRUGO | S_IWUSR);
1446 MODULE_PARM_DESC(proto_bias, "Favourite protocol number");
1447 MODULE_LICENSE("GPL");
1448