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