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