GNU Linux-libre 4.9.337-gnu1
[releases.git] / drivers / usb / class / usblp.c
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.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
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
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 static int usblp_hp_channel_change_request(struct usblp *usblp, int channel, u8 *new_channel)
293 {
294         u8 *buf;
295         int ret;
296
297         buf = kzalloc(1, GFP_KERNEL);
298         if (!buf)
299                 return -ENOMEM;
300
301         ret = usblp_ctrl_msg(usblp, USBLP_REQ_HP_CHANNEL_CHANGE_REQUEST,
302                         USB_TYPE_VENDOR, USB_DIR_IN, USB_RECIP_INTERFACE,
303                         channel, buf, 1);
304         if (ret == 0)
305                 *new_channel = buf[0];
306
307         kfree(buf);
308
309         return ret;
310 }
311
312 /*
313  * See the description for usblp_select_alts() below for the usage
314  * explanation.  Look into your /proc/bus/usb/devices and dmesg in
315  * case of any trouble.
316  */
317 static int proto_bias = -1;
318
319 /*
320  * URB callback.
321  */
322
323 static void usblp_bulk_read(struct urb *urb)
324 {
325         struct usblp *usblp = urb->context;
326         int status = urb->status;
327
328         if (usblp->present && usblp->used) {
329                 if (status)
330                         printk(KERN_WARNING "usblp%d: "
331                             "nonzero read bulk status received: %d\n",
332                             usblp->minor, status);
333         }
334         spin_lock(&usblp->lock);
335         if (status < 0)
336                 usblp->rstatus = status;
337         else
338                 usblp->rstatus = urb->actual_length;
339         usblp->rcomplete = 1;
340         wake_up(&usblp->rwait);
341         spin_unlock(&usblp->lock);
342
343         usb_free_urb(urb);
344 }
345
346 static void usblp_bulk_write(struct urb *urb)
347 {
348         struct usblp *usblp = urb->context;
349         int status = urb->status;
350
351         if (usblp->present && usblp->used) {
352                 if (status)
353                         printk(KERN_WARNING "usblp%d: "
354                             "nonzero write bulk status received: %d\n",
355                             usblp->minor, status);
356         }
357         spin_lock(&usblp->lock);
358         if (status < 0)
359                 usblp->wstatus = status;
360         else
361                 usblp->wstatus = urb->actual_length;
362         usblp->no_paper = 0;
363         usblp->wcomplete = 1;
364         wake_up(&usblp->wwait);
365         spin_unlock(&usblp->lock);
366
367         usb_free_urb(urb);
368 }
369
370 /*
371  * Get and print printer errors.
372  */
373
374 static const char *usblp_messages[] = { "ok", "out of paper", "off-line", "on fire" };
375
376 static int usblp_check_status(struct usblp *usblp, int err)
377 {
378         unsigned char status, newerr = 0;
379         int error;
380
381         mutex_lock(&usblp->mut);
382         if ((error = usblp_read_status(usblp, usblp->statusbuf)) < 0) {
383                 mutex_unlock(&usblp->mut);
384                 printk_ratelimited(KERN_ERR
385                                 "usblp%d: error %d reading printer status\n",
386                                 usblp->minor, error);
387                 return 0;
388         }
389         status = *usblp->statusbuf;
390         mutex_unlock(&usblp->mut);
391
392         if (~status & LP_PERRORP)
393                 newerr = 3;
394         if (status & LP_POUTPA)
395                 newerr = 1;
396         if (~status & LP_PSELECD)
397                 newerr = 2;
398
399         if (newerr != err) {
400                 printk(KERN_INFO "usblp%d: %s\n",
401                    usblp->minor, usblp_messages[newerr]);
402         }
403
404         return newerr;
405 }
406
407 static int handle_bidir(struct usblp *usblp)
408 {
409         if (usblp->bidir && usblp->used) {
410                 if (usblp_submit_read(usblp) < 0)
411                         return -EIO;
412         }
413         return 0;
414 }
415
416 /*
417  * File op functions.
418  */
419
420 static int usblp_open(struct inode *inode, struct file *file)
421 {
422         int minor = iminor(inode);
423         struct usblp *usblp;
424         struct usb_interface *intf;
425         int retval;
426
427         if (minor < 0)
428                 return -ENODEV;
429
430         mutex_lock(&usblp_mutex);
431
432         retval = -ENODEV;
433         intf = usb_find_interface(&usblp_driver, minor);
434         if (!intf)
435                 goto out;
436         usblp = usb_get_intfdata(intf);
437         if (!usblp || !usblp->dev || !usblp->present)
438                 goto out;
439
440         retval = -EBUSY;
441         if (usblp->used)
442                 goto out;
443
444         /*
445          * We do not implement LP_ABORTOPEN/LPABORTOPEN for two reasons:
446          *  - We do not want persistent state which close(2) does not clear
447          *  - It is not used anyway, according to CUPS people
448          */
449
450         retval = usb_autopm_get_interface(intf);
451         if (retval < 0)
452                 goto out;
453         usblp->used = 1;
454         file->private_data = usblp;
455
456         usblp->wcomplete = 1; /* we begin writeable */
457         usblp->wstatus = 0;
458         usblp->rcomplete = 0;
459
460         if (handle_bidir(usblp) < 0) {
461                 usb_autopm_put_interface(intf);
462                 usblp->used = 0;
463                 file->private_data = NULL;
464                 retval = -EIO;
465         }
466 out:
467         mutex_unlock(&usblp_mutex);
468         return retval;
469 }
470
471 static void usblp_cleanup(struct usblp *usblp)
472 {
473         printk(KERN_INFO "usblp%d: removed\n", usblp->minor);
474
475         kfree(usblp->readbuf);
476         kfree(usblp->device_id_string);
477         kfree(usblp->statusbuf);
478         usb_put_intf(usblp->intf);
479         kfree(usblp);
480 }
481
482 static void usblp_unlink_urbs(struct usblp *usblp)
483 {
484         usb_kill_anchored_urbs(&usblp->urbs);
485 }
486
487 static int usblp_release(struct inode *inode, struct file *file)
488 {
489         struct usblp *usblp = file->private_data;
490
491         usblp->flags &= ~LP_ABORT;
492
493         mutex_lock(&usblp_mutex);
494         usblp->used = 0;
495         if (usblp->present)
496                 usblp_unlink_urbs(usblp);
497
498         usb_autopm_put_interface(usblp->intf);
499
500         if (!usblp->present)            /* finish cleanup from disconnect */
501                 usblp_cleanup(usblp);   /* any URBs must be dead */
502
503         mutex_unlock(&usblp_mutex);
504         return 0;
505 }
506
507 /* No kernel lock - fine */
508 static unsigned int usblp_poll(struct file *file, struct poll_table_struct *wait)
509 {
510         int ret;
511         unsigned long flags;
512
513         struct usblp *usblp = file->private_data;
514         /* Should we check file->f_mode & FMODE_WRITE before poll_wait()? */
515         poll_wait(file, &usblp->rwait, wait);
516         poll_wait(file, &usblp->wwait, wait);
517         spin_lock_irqsave(&usblp->lock, flags);
518         ret = ((usblp->bidir && usblp->rcomplete) ? POLLIN  | POLLRDNORM : 0) |
519            ((usblp->no_paper || usblp->wcomplete) ? POLLOUT | POLLWRNORM : 0);
520         spin_unlock_irqrestore(&usblp->lock, flags);
521         return ret;
522 }
523
524 static long usblp_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
525 {
526         struct usblp *usblp = file->private_data;
527         int length, err, i;
528         unsigned char newChannel;
529         int status;
530         int twoints[2];
531         int retval = 0;
532
533         mutex_lock(&usblp->mut);
534         if (!usblp->present) {
535                 retval = -ENODEV;
536                 goto done;
537         }
538
539         dev_dbg(&usblp->intf->dev,
540                 "usblp_ioctl: cmd=0x%x (%c nr=%d len=%d dir=%d)\n", cmd,
541                 _IOC_TYPE(cmd), _IOC_NR(cmd), _IOC_SIZE(cmd), _IOC_DIR(cmd));
542
543         if (_IOC_TYPE(cmd) == 'P')      /* new-style ioctl number */
544
545                 switch (_IOC_NR(cmd)) {
546
547                 case IOCNR_GET_DEVICE_ID: /* get the DEVICE_ID string */
548                         if (_IOC_DIR(cmd) != _IOC_READ) {
549                                 retval = -EINVAL;
550                                 goto done;
551                         }
552
553                         length = usblp_cache_device_id_string(usblp);
554                         if (length < 0) {
555                                 retval = length;
556                                 goto done;
557                         }
558                         if (length > _IOC_SIZE(cmd))
559                                 length = _IOC_SIZE(cmd); /* truncate */
560
561                         if (copy_to_user((void __user *) arg,
562                                         usblp->device_id_string,
563                                         (unsigned long) length)) {
564                                 retval = -EFAULT;
565                                 goto done;
566                         }
567
568                         break;
569
570                 case IOCNR_GET_PROTOCOLS:
571                         if (_IOC_DIR(cmd) != _IOC_READ ||
572                             _IOC_SIZE(cmd) < sizeof(twoints)) {
573                                 retval = -EINVAL;
574                                 goto done;
575                         }
576
577                         twoints[0] = usblp->current_protocol;
578                         twoints[1] = 0;
579                         for (i = USBLP_FIRST_PROTOCOL;
580                              i <= USBLP_LAST_PROTOCOL; i++) {
581                                 if (usblp->protocol[i].alt_setting >= 0)
582                                         twoints[1] |= (1<<i);
583                         }
584
585                         if (copy_to_user((void __user *)arg,
586                                         (unsigned char *)twoints,
587                                         sizeof(twoints))) {
588                                 retval = -EFAULT;
589                                 goto done;
590                         }
591
592                         break;
593
594                 case IOCNR_SET_PROTOCOL:
595                         if (_IOC_DIR(cmd) != _IOC_WRITE) {
596                                 retval = -EINVAL;
597                                 goto done;
598                         }
599
600 #ifdef DEBUG
601                         if (arg == -10) {
602                                 usblp_dump(usblp);
603                                 break;
604                         }
605 #endif
606
607                         usblp_unlink_urbs(usblp);
608                         retval = usblp_set_protocol(usblp, arg);
609                         if (retval < 0) {
610                                 usblp_set_protocol(usblp,
611                                         usblp->current_protocol);
612                         }
613                         break;
614
615                 case IOCNR_HP_SET_CHANNEL:
616                         if (_IOC_DIR(cmd) != _IOC_WRITE ||
617                             le16_to_cpu(usblp->dev->descriptor.idVendor) != 0x03F0 ||
618                             usblp->quirks & USBLP_QUIRK_BIDIR) {
619                                 retval = -EINVAL;
620                                 goto done;
621                         }
622
623                         err = usblp_hp_channel_change_request(usblp,
624                                 arg, &newChannel);
625                         if (err < 0) {
626                                 dev_err(&usblp->dev->dev,
627                                         "usblp%d: error = %d setting "
628                                         "HP channel\n",
629                                         usblp->minor, err);
630                                 retval = -EIO;
631                                 goto done;
632                         }
633
634                         dev_dbg(&usblp->intf->dev,
635                                 "usblp%d requested/got HP channel %ld/%d\n",
636                                 usblp->minor, arg, newChannel);
637                         break;
638
639                 case IOCNR_GET_BUS_ADDRESS:
640                         if (_IOC_DIR(cmd) != _IOC_READ ||
641                             _IOC_SIZE(cmd) < sizeof(twoints)) {
642                                 retval = -EINVAL;
643                                 goto done;
644                         }
645
646                         twoints[0] = usblp->dev->bus->busnum;
647                         twoints[1] = usblp->dev->devnum;
648                         if (copy_to_user((void __user *)arg,
649                                         (unsigned char *)twoints,
650                                         sizeof(twoints))) {
651                                 retval = -EFAULT;
652                                 goto done;
653                         }
654
655                         dev_dbg(&usblp->intf->dev,
656                                 "usblp%d is bus=%d, device=%d\n",
657                                 usblp->minor, twoints[0], twoints[1]);
658                         break;
659
660                 case IOCNR_GET_VID_PID:
661                         if (_IOC_DIR(cmd) != _IOC_READ ||
662                             _IOC_SIZE(cmd) < sizeof(twoints)) {
663                                 retval = -EINVAL;
664                                 goto done;
665                         }
666
667                         twoints[0] = le16_to_cpu(usblp->dev->descriptor.idVendor);
668                         twoints[1] = le16_to_cpu(usblp->dev->descriptor.idProduct);
669                         if (copy_to_user((void __user *)arg,
670                                         (unsigned char *)twoints,
671                                         sizeof(twoints))) {
672                                 retval = -EFAULT;
673                                 goto done;
674                         }
675
676                         dev_dbg(&usblp->intf->dev,
677                                 "usblp%d is VID=0x%4.4X, PID=0x%4.4X\n",
678                                 usblp->minor, twoints[0], twoints[1]);
679                         break;
680
681                 case IOCNR_SOFT_RESET:
682                         if (_IOC_DIR(cmd) != _IOC_NONE) {
683                                 retval = -EINVAL;
684                                 goto done;
685                         }
686                         retval = usblp_reset(usblp);
687                         break;
688                 default:
689                         retval = -ENOTTY;
690                 }
691         else    /* old-style ioctl value */
692                 switch (cmd) {
693
694                 case LPGETSTATUS:
695                         retval = usblp_read_status(usblp, usblp->statusbuf);
696                         if (retval) {
697                                 printk_ratelimited(KERN_ERR "usblp%d:"
698                                             "failed reading printer status (%d)\n",
699                                             usblp->minor, retval);
700                                 retval = -EIO;
701                                 goto done;
702                         }
703                         status = *usblp->statusbuf;
704                         if (copy_to_user((void __user *)arg, &status, sizeof(int)))
705                                 retval = -EFAULT;
706                         break;
707
708                 case LPABORT:
709                         if (arg)
710                                 usblp->flags |= LP_ABORT;
711                         else
712                                 usblp->flags &= ~LP_ABORT;
713                         break;
714
715                 default:
716                         retval = -ENOTTY;
717                 }
718
719 done:
720         mutex_unlock(&usblp->mut);
721         return retval;
722 }
723
724 static struct urb *usblp_new_writeurb(struct usblp *usblp, int transfer_length)
725 {
726         struct urb *urb;
727         char *writebuf;
728
729         writebuf = kmalloc(transfer_length, GFP_KERNEL);
730         if (writebuf == NULL)
731                 return NULL;
732         urb = usb_alloc_urb(0, GFP_KERNEL);
733         if (urb == NULL) {
734                 kfree(writebuf);
735                 return NULL;
736         }
737
738         usb_fill_bulk_urb(urb, usblp->dev,
739                 usb_sndbulkpipe(usblp->dev,
740                  usblp->protocol[usblp->current_protocol].epwrite->bEndpointAddress),
741                 writebuf, transfer_length, usblp_bulk_write, usblp);
742         urb->transfer_flags |= URB_FREE_BUFFER;
743
744         return urb;
745 }
746
747 static ssize_t usblp_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos)
748 {
749         struct usblp *usblp = file->private_data;
750         struct urb *writeurb;
751         int rv;
752         int transfer_length;
753         ssize_t writecount = 0;
754
755         if (mutex_lock_interruptible(&usblp->wmut)) {
756                 rv = -EINTR;
757                 goto raise_biglock;
758         }
759         if ((rv = usblp_wwait(usblp, !!(file->f_flags & O_NONBLOCK))) < 0)
760                 goto raise_wait;
761
762         while (writecount < count) {
763                 /*
764                  * Step 1: Submit next block.
765                  */
766                 if ((transfer_length = count - writecount) > USBLP_BUF_SIZE)
767                         transfer_length = USBLP_BUF_SIZE;
768
769                 rv = -ENOMEM;
770                 writeurb = usblp_new_writeurb(usblp, transfer_length);
771                 if (writeurb == NULL)
772                         goto raise_urb;
773                 usb_anchor_urb(writeurb, &usblp->urbs);
774
775                 if (copy_from_user(writeurb->transfer_buffer,
776                                    buffer + writecount, transfer_length)) {
777                         rv = -EFAULT;
778                         goto raise_badaddr;
779                 }
780
781                 spin_lock_irq(&usblp->lock);
782                 usblp->wcomplete = 0;
783                 spin_unlock_irq(&usblp->lock);
784                 if ((rv = usb_submit_urb(writeurb, GFP_KERNEL)) < 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  */
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         if ((avail = usblp->rstatus) < 0) {
866                 printk(KERN_ERR "usblp%d: error %d reading from printer\n",
867                     usblp->minor, (int)avail);
868                 usblp_submit_read(usblp);
869                 count = -EIO;
870                 goto done;
871         }
872
873         count = len < avail - usblp->readcount ? len : avail - usblp->readcount;
874         if (count != 0 &&
875             copy_to_user(buffer, usblp->readbuf + usblp->readcount, count)) {
876                 count = -EFAULT;
877                 goto done;
878         }
879
880         if ((usblp->readcount += count) == avail) {
881                 if (usblp_submit_read(usblp) < 0) {
882                         /* We don't want to leak USB return codes into errno. */
883                         if (count == 0)
884                                 count = -EIO;
885                         goto done;
886                 }
887         }
888
889 done:
890         mutex_unlock(&usblp->mut);
891         return count;
892 }
893
894 /*
895  * Wait for the write path to come idle.
896  * This is called under the ->wmut, so the idle path stays idle.
897  *
898  * Our write path has a peculiar property: it does not buffer like a tty,
899  * but waits for the write to succeed. This allows our ->release to bug out
900  * without waiting for writes to drain. But it obviously does not work
901  * when O_NONBLOCK is set. So, applications setting O_NONBLOCK must use
902  * select(2) or poll(2) to wait for the buffer to drain before closing.
903  * Alternatively, set blocking mode with fcntl and issue a zero-size write.
904  */
905 static int usblp_wwait(struct usblp *usblp, int nonblock)
906 {
907         DECLARE_WAITQUEUE(waita, current);
908         int rc;
909         int err = 0;
910
911         add_wait_queue(&usblp->wwait, &waita);
912         for (;;) {
913                 if (mutex_lock_interruptible(&usblp->mut)) {
914                         rc = -EINTR;
915                         break;
916                 }
917                 set_current_state(TASK_INTERRUPTIBLE);
918                 rc = usblp_wtest(usblp, nonblock);
919                 mutex_unlock(&usblp->mut);
920                 if (rc <= 0)
921                         break;
922
923                 if (schedule_timeout(msecs_to_jiffies(1500)) == 0) {
924                         if (usblp->flags & LP_ABORT) {
925                                 err = usblp_check_status(usblp, err);
926                                 if (err == 1) { /* Paper out */
927                                         rc = -ENOSPC;
928                                         break;
929                                 }
930                         } else {
931                                 /* Prod the printer, Gentoo#251237. */
932                                 mutex_lock(&usblp->mut);
933                                 usblp_read_status(usblp, usblp->statusbuf);
934                                 mutex_unlock(&usblp->mut);
935                         }
936                 }
937         }
938         set_current_state(TASK_RUNNING);
939         remove_wait_queue(&usblp->wwait, &waita);
940         return rc;
941 }
942
943 static int usblp_wtest(struct usblp *usblp, int nonblock)
944 {
945         unsigned long flags;
946
947         if (!usblp->present)
948                 return -ENODEV;
949         if (signal_pending(current))
950                 return -EINTR;
951         spin_lock_irqsave(&usblp->lock, flags);
952         if (usblp->wcomplete) {
953                 spin_unlock_irqrestore(&usblp->lock, flags);
954                 return 0;
955         }
956         spin_unlock_irqrestore(&usblp->lock, flags);
957         if (nonblock)
958                 return -EAGAIN;
959         return 1;
960 }
961
962 /*
963  * Wait for read bytes to become available. This probably should have been
964  * called usblp_r_lock_and_wait(), because we lock first. But it's a traditional
965  * name for functions which lock and return.
966  *
967  * We do not use wait_event_interruptible because it makes locking iffy.
968  */
969 static int usblp_rwait_and_lock(struct usblp *usblp, int nonblock)
970 {
971         DECLARE_WAITQUEUE(waita, current);
972         int rc;
973
974         add_wait_queue(&usblp->rwait, &waita);
975         for (;;) {
976                 if (mutex_lock_interruptible(&usblp->mut)) {
977                         rc = -EINTR;
978                         break;
979                 }
980                 set_current_state(TASK_INTERRUPTIBLE);
981                 if ((rc = usblp_rtest(usblp, nonblock)) < 0) {
982                         mutex_unlock(&usblp->mut);
983                         break;
984                 }
985                 if (rc == 0)    /* Keep it locked */
986                         break;
987                 mutex_unlock(&usblp->mut);
988                 schedule();
989         }
990         set_current_state(TASK_RUNNING);
991         remove_wait_queue(&usblp->rwait, &waita);
992         return rc;
993 }
994
995 static int usblp_rtest(struct usblp *usblp, int nonblock)
996 {
997         unsigned long flags;
998
999         if (!usblp->present)
1000                 return -ENODEV;
1001         if (signal_pending(current))
1002                 return -EINTR;
1003         spin_lock_irqsave(&usblp->lock, flags);
1004         if (usblp->rcomplete) {
1005                 spin_unlock_irqrestore(&usblp->lock, flags);
1006                 return 0;
1007         }
1008         spin_unlock_irqrestore(&usblp->lock, flags);
1009         if (nonblock)
1010                 return -EAGAIN;
1011         return 1;
1012 }
1013
1014 /*
1015  * Please check ->bidir and other such things outside for now.
1016  */
1017 static int usblp_submit_read(struct usblp *usblp)
1018 {
1019         struct urb *urb;
1020         unsigned long flags;
1021         int rc;
1022
1023         rc = -ENOMEM;
1024         urb = usb_alloc_urb(0, GFP_KERNEL);
1025         if (urb == NULL)
1026                 goto raise_urb;
1027
1028         usb_fill_bulk_urb(urb, usblp->dev,
1029                 usb_rcvbulkpipe(usblp->dev,
1030                   usblp->protocol[usblp->current_protocol].epread->bEndpointAddress),
1031                 usblp->readbuf, USBLP_BUF_SIZE_IN,
1032                 usblp_bulk_read, usblp);
1033         usb_anchor_urb(urb, &usblp->urbs);
1034
1035         spin_lock_irqsave(&usblp->lock, flags);
1036         usblp->readcount = 0; /* XXX Why here? */
1037         usblp->rcomplete = 0;
1038         spin_unlock_irqrestore(&usblp->lock, flags);
1039         if ((rc = usb_submit_urb(urb, GFP_KERNEL)) < 0) {
1040                 dev_dbg(&usblp->intf->dev, "error submitting urb (%d)\n", rc);
1041                 spin_lock_irqsave(&usblp->lock, flags);
1042                 usblp->rstatus = rc;
1043                 usblp->rcomplete = 1;
1044                 spin_unlock_irqrestore(&usblp->lock, flags);
1045                 goto raise_submit;
1046         }
1047
1048         return 0;
1049
1050 raise_submit:
1051         usb_unanchor_urb(urb);
1052         usb_free_urb(urb);
1053 raise_urb:
1054         return rc;
1055 }
1056
1057 /*
1058  * Checks for printers that have quirks, such as requiring unidirectional
1059  * communication but reporting bidirectional; currently some HP printers
1060  * have this flaw (HP 810, 880, 895, etc.), or needing an init string
1061  * sent at each open (like some Epsons).
1062  * Returns 1 if found, 0 if not found.
1063  *
1064  * HP recommended that we use the bidirectional interface but
1065  * don't attempt any bulk IN transfers from the IN endpoint.
1066  * Here's some more detail on the problem:
1067  * The problem is not that it isn't bidirectional though. The problem
1068  * is that if you request a device ID, or status information, while
1069  * the buffers are full, the return data will end up in the print data
1070  * buffer. For example if you make sure you never request the device ID
1071  * while you are sending print data, and you don't try to query the
1072  * printer status every couple of milliseconds, you will probably be OK.
1073  */
1074 static unsigned int usblp_quirks(__u16 vendor, __u16 product)
1075 {
1076         int i;
1077
1078         for (i = 0; quirk_printers[i].vendorId; i++) {
1079                 if (vendor == quirk_printers[i].vendorId &&
1080                     product == quirk_printers[i].productId)
1081                         return quirk_printers[i].quirks;
1082         }
1083         return 0;
1084 }
1085
1086 static const struct file_operations usblp_fops = {
1087         .owner =        THIS_MODULE,
1088         .read =         usblp_read,
1089         .write =        usblp_write,
1090         .poll =         usblp_poll,
1091         .unlocked_ioctl =       usblp_ioctl,
1092         .compat_ioctl =         usblp_ioctl,
1093         .open =         usblp_open,
1094         .release =      usblp_release,
1095         .llseek =       noop_llseek,
1096 };
1097
1098 static char *usblp_devnode(struct device *dev, umode_t *mode)
1099 {
1100         return kasprintf(GFP_KERNEL, "usb/%s", dev_name(dev));
1101 }
1102
1103 static struct usb_class_driver usblp_class = {
1104         .name =         "lp%d",
1105         .devnode =      usblp_devnode,
1106         .fops =         &usblp_fops,
1107         .minor_base =   USBLP_MINOR_BASE,
1108 };
1109
1110 static ssize_t usblp_show_ieee1284_id(struct device *dev, struct device_attribute *attr, char *buf)
1111 {
1112         struct usb_interface *intf = to_usb_interface(dev);
1113         struct usblp *usblp = usb_get_intfdata(intf);
1114
1115         if (usblp->device_id_string[0] == 0 &&
1116             usblp->device_id_string[1] == 0)
1117                 return 0;
1118
1119         return sprintf(buf, "%s", usblp->device_id_string+2);
1120 }
1121
1122 static DEVICE_ATTR(ieee1284_id, S_IRUGO, usblp_show_ieee1284_id, NULL);
1123
1124 static int usblp_probe(struct usb_interface *intf,
1125                        const struct usb_device_id *id)
1126 {
1127         struct usb_device *dev = interface_to_usbdev(intf);
1128         struct usblp *usblp;
1129         int protocol;
1130         int retval;
1131
1132         /* Malloc and start initializing usblp structure so we can use it
1133          * directly. */
1134         usblp = kzalloc(sizeof(struct usblp), GFP_KERNEL);
1135         if (!usblp) {
1136                 retval = -ENOMEM;
1137                 goto abort_ret;
1138         }
1139         usblp->dev = dev;
1140         mutex_init(&usblp->wmut);
1141         mutex_init(&usblp->mut);
1142         spin_lock_init(&usblp->lock);
1143         init_waitqueue_head(&usblp->rwait);
1144         init_waitqueue_head(&usblp->wwait);
1145         init_usb_anchor(&usblp->urbs);
1146         usblp->ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
1147         usblp->intf = usb_get_intf(intf);
1148
1149         /* Malloc device ID string buffer to the largest expected length,
1150          * since we can re-query it on an ioctl and a dynamic string
1151          * could change in length. */
1152         if (!(usblp->device_id_string = kmalloc(USBLP_DEVICE_ID_SIZE, GFP_KERNEL))) {
1153                 retval = -ENOMEM;
1154                 goto abort;
1155         }
1156
1157         /*
1158          * Allocate read buffer. We somewhat wastefully
1159          * malloc both regardless of bidirectionality, because the
1160          * alternate setting can be changed later via an ioctl.
1161          */
1162         if (!(usblp->readbuf = kmalloc(USBLP_BUF_SIZE_IN, GFP_KERNEL))) {
1163                 retval = -ENOMEM;
1164                 goto abort;
1165         }
1166
1167         /* Allocate buffer for printer status */
1168         usblp->statusbuf = kmalloc(STATUS_BUF_SIZE, GFP_KERNEL);
1169         if (!usblp->statusbuf) {
1170                 retval = -ENOMEM;
1171                 goto abort;
1172         }
1173
1174         /* Lookup quirks for this printer. */
1175         usblp->quirks = usblp_quirks(
1176                 le16_to_cpu(dev->descriptor.idVendor),
1177                 le16_to_cpu(dev->descriptor.idProduct));
1178
1179         /* Analyze and pick initial alternate settings and endpoints. */
1180         protocol = usblp_select_alts(usblp);
1181         if (protocol < 0) {
1182                 dev_dbg(&intf->dev,
1183                         "incompatible printer-class device 0x%4.4X/0x%4.4X\n",
1184                         le16_to_cpu(dev->descriptor.idVendor),
1185                         le16_to_cpu(dev->descriptor.idProduct));
1186                 retval = -ENODEV;
1187                 goto abort;
1188         }
1189
1190         /* Setup the selected alternate setting and endpoints. */
1191         if (usblp_set_protocol(usblp, protocol) < 0) {
1192                 retval = -ENODEV;       /* ->probe isn't ->ioctl */
1193                 goto abort;
1194         }
1195
1196         /* Retrieve and store the device ID string. */
1197         usblp_cache_device_id_string(usblp);
1198         retval = device_create_file(&intf->dev, &dev_attr_ieee1284_id);
1199         if (retval)
1200                 goto abort_intfdata;
1201
1202 #ifdef DEBUG
1203         usblp_check_status(usblp, 0);
1204 #endif
1205
1206         usb_set_intfdata(intf, usblp);
1207
1208         usblp->present = 1;
1209
1210         retval = usb_register_dev(intf, &usblp_class);
1211         if (retval) {
1212                 dev_err(&intf->dev,
1213                         "usblp: Not able to get a minor (base %u, slice default): %d\n",
1214                         USBLP_MINOR_BASE, retval);
1215                 goto abort_intfdata;
1216         }
1217         usblp->minor = intf->minor;
1218         dev_info(&intf->dev,
1219                 "usblp%d: USB %sdirectional printer dev %d if %d alt %d proto %d vid 0x%4.4X pid 0x%4.4X\n",
1220                 usblp->minor, usblp->bidir ? "Bi" : "Uni", dev->devnum,
1221                 usblp->ifnum,
1222                 usblp->protocol[usblp->current_protocol].alt_setting,
1223                 usblp->current_protocol,
1224                 le16_to_cpu(usblp->dev->descriptor.idVendor),
1225                 le16_to_cpu(usblp->dev->descriptor.idProduct));
1226
1227         return 0;
1228
1229 abort_intfdata:
1230         usb_set_intfdata(intf, NULL);
1231         device_remove_file(&intf->dev, &dev_attr_ieee1284_id);
1232 abort:
1233         kfree(usblp->readbuf);
1234         kfree(usblp->statusbuf);
1235         kfree(usblp->device_id_string);
1236         usb_put_intf(usblp->intf);
1237         kfree(usblp);
1238 abort_ret:
1239         return retval;
1240 }
1241
1242 /*
1243  * We are a "new" style driver with usb_device_id table,
1244  * but our requirements are too intricate for simple match to handle.
1245  *
1246  * The "proto_bias" option may be used to specify the preferred protocol
1247  * for all USB printers (1=USB_CLASS_PRINTER/1/1, 2=USB_CLASS_PRINTER/1/2,
1248  * 3=USB_CLASS_PRINTER/1/3).  If the device supports the preferred protocol,
1249  * then we bind to it.
1250  *
1251  * The best interface for us is USB_CLASS_PRINTER/1/2, because it
1252  * is compatible with a stream of characters. If we find it, we bind to it.
1253  *
1254  * Note that the people from hpoj.sourceforge.net need to be able to
1255  * bind to USB_CLASS_PRINTER/1/3 (MLC/1284.4), so we provide them ioctls
1256  * for this purpose.
1257  *
1258  * Failing USB_CLASS_PRINTER/1/2, we look for USB_CLASS_PRINTER/1/3,
1259  * even though it's probably not stream-compatible, because this matches
1260  * the behaviour of the old code.
1261  *
1262  * If nothing else, we bind to USB_CLASS_PRINTER/1/1
1263  * - the unidirectional interface.
1264  */
1265 static int usblp_select_alts(struct usblp *usblp)
1266 {
1267         struct usb_interface *if_alt;
1268         struct usb_host_interface *ifd;
1269         struct usb_endpoint_descriptor *epd, *epwrite, *epread;
1270         int p, i, e;
1271
1272         if_alt = usblp->intf;
1273
1274         for (p = 0; p < USBLP_MAX_PROTOCOLS; p++)
1275                 usblp->protocol[p].alt_setting = -1;
1276
1277         /* Find out what we have. */
1278         for (i = 0; i < if_alt->num_altsetting; i++) {
1279                 ifd = &if_alt->altsetting[i];
1280
1281                 if (ifd->desc.bInterfaceClass != USB_CLASS_PRINTER ||
1282                     ifd->desc.bInterfaceSubClass != 1)
1283                         if (!(usblp->quirks & USBLP_QUIRK_BAD_CLASS))
1284                                 continue;
1285
1286                 if (ifd->desc.bInterfaceProtocol < USBLP_FIRST_PROTOCOL ||
1287                     ifd->desc.bInterfaceProtocol > USBLP_LAST_PROTOCOL)
1288                         continue;
1289
1290                 /* Look for bulk OUT and IN endpoints. */
1291                 epwrite = epread = NULL;
1292                 for (e = 0; e < ifd->desc.bNumEndpoints; e++) {
1293                         epd = &ifd->endpoint[e].desc;
1294
1295                         if (usb_endpoint_is_bulk_out(epd))
1296                                 if (!epwrite)
1297                                         epwrite = epd;
1298
1299                         if (usb_endpoint_is_bulk_in(epd))
1300                                 if (!epread)
1301                                         epread = epd;
1302                 }
1303
1304                 /* Ignore buggy hardware without the right endpoints. */
1305                 if (!epwrite || (ifd->desc.bInterfaceProtocol > 1 && !epread))
1306                         continue;
1307
1308                 /*
1309                  * Turn off reads for USB_CLASS_PRINTER/1/1 (unidirectional)
1310                  * interfaces and buggy bidirectional printers.
1311                  */
1312                 if (ifd->desc.bInterfaceProtocol == 1) {
1313                         epread = NULL;
1314                 } else if (usblp->quirks & USBLP_QUIRK_BIDIR) {
1315                         printk(KERN_INFO "usblp%d: Disabling reads from "
1316                             "problematic bidirectional printer\n",
1317                             usblp->minor);
1318                         epread = NULL;
1319                 }
1320
1321                 usblp->protocol[ifd->desc.bInterfaceProtocol].alt_setting =
1322                                 ifd->desc.bAlternateSetting;
1323                 usblp->protocol[ifd->desc.bInterfaceProtocol].epwrite = epwrite;
1324                 usblp->protocol[ifd->desc.bInterfaceProtocol].epread = epread;
1325         }
1326
1327         /* If our requested protocol is supported, then use it. */
1328         if (proto_bias >= USBLP_FIRST_PROTOCOL &&
1329             proto_bias <= USBLP_LAST_PROTOCOL &&
1330             usblp->protocol[proto_bias].alt_setting != -1)
1331                 return proto_bias;
1332
1333         /* Ordering is important here. */
1334         if (usblp->protocol[2].alt_setting != -1)
1335                 return 2;
1336         if (usblp->protocol[1].alt_setting != -1)
1337                 return 1;
1338         if (usblp->protocol[3].alt_setting != -1)
1339                 return 3;
1340
1341         /* If nothing is available, then don't bind to this device. */
1342         return -1;
1343 }
1344
1345 static int usblp_set_protocol(struct usblp *usblp, int protocol)
1346 {
1347         int r, alts;
1348
1349         if (protocol < USBLP_FIRST_PROTOCOL || protocol > USBLP_LAST_PROTOCOL)
1350                 return -EINVAL;
1351
1352         /* Don't unnecessarily set the interface if there's a single alt. */
1353         if (usblp->intf->num_altsetting > 1) {
1354                 alts = usblp->protocol[protocol].alt_setting;
1355                 if (alts < 0)
1356                         return -EINVAL;
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. */
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
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         device_remove_file(&intf->dev, &dev_attr_ieee1284_id);
1416
1417         mutex_lock(&usblp_mutex);
1418         mutex_lock(&usblp->mut);
1419         usblp->present = 0;
1420         wake_up(&usblp->wwait);
1421         wake_up(&usblp->rwait);
1422         usb_set_intfdata(intf, NULL);
1423
1424         usblp_unlink_urbs(usblp);
1425         mutex_unlock(&usblp->mut);
1426         usb_poison_anchored_urbs(&usblp->urbs);
1427
1428         if (!usblp->used)
1429                 usblp_cleanup(usblp);
1430
1431         mutex_unlock(&usblp_mutex);
1432 }
1433
1434 static int usblp_suspend(struct usb_interface *intf, pm_message_t message)
1435 {
1436         struct usblp *usblp = usb_get_intfdata(intf);
1437
1438         usblp_unlink_urbs(usblp);
1439 #if 0 /* XXX Do we want this? What if someone is reading, should we fail? */
1440         /* not strictly necessary, but just in case */
1441         wake_up(&usblp->wwait);
1442         wake_up(&usblp->rwait);
1443 #endif
1444
1445         return 0;
1446 }
1447
1448 static int usblp_resume(struct usb_interface *intf)
1449 {
1450         struct usblp *usblp = usb_get_intfdata(intf);
1451         int r;
1452
1453         r = handle_bidir(usblp);
1454
1455         return r;
1456 }
1457
1458 static const struct usb_device_id usblp_ids[] = {
1459         { USB_DEVICE_INFO(USB_CLASS_PRINTER, 1, 1) },
1460         { USB_DEVICE_INFO(USB_CLASS_PRINTER, 1, 2) },
1461         { USB_DEVICE_INFO(USB_CLASS_PRINTER, 1, 3) },
1462         { USB_INTERFACE_INFO(USB_CLASS_PRINTER, 1, 1) },
1463         { USB_INTERFACE_INFO(USB_CLASS_PRINTER, 1, 2) },
1464         { USB_INTERFACE_INFO(USB_CLASS_PRINTER, 1, 3) },
1465         { USB_DEVICE(0x04b8, 0x0202) }, /* Seiko Epson Receipt Printer M129C */
1466         { }                                             /* Terminating entry */
1467 };
1468
1469 MODULE_DEVICE_TABLE(usb, usblp_ids);
1470
1471 static struct usb_driver usblp_driver = {
1472         .name =         "usblp",
1473         .probe =        usblp_probe,
1474         .disconnect =   usblp_disconnect,
1475         .suspend =      usblp_suspend,
1476         .resume =       usblp_resume,
1477         .id_table =     usblp_ids,
1478         .supports_autosuspend = 1,
1479 };
1480
1481 module_usb_driver(usblp_driver);
1482
1483 MODULE_AUTHOR(DRIVER_AUTHOR);
1484 MODULE_DESCRIPTION(DRIVER_DESC);
1485 module_param(proto_bias, int, S_IRUGO | S_IWUSR);
1486 MODULE_PARM_DESC(proto_bias, "Favourite protocol number");
1487 MODULE_LICENSE("GPL");