[PATCH] USB: Fix race condition in usblp_write
[linux-2.6] / drivers / usb / class / usblp.c
1 /*
2  * usblp.c  Version 0.13
3  *
4  * Copyright (c) 1999 Michael Gee       <michael@linuxspecific.com>
5  * Copyright (c) 1999 Pavel Machek      <pavel@suse.cz>
6  * Copyright (c) 2000 Randy Dunlap      <rddunlap@osdl.org>
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  *
11  * USB Printer Device Class driver for USB printers and printer cables
12  *
13  * Sponsored by SuSE
14  *
15  * ChangeLog:
16  *      v0.1 - thorough cleaning, URBification, almost a rewrite
17  *      v0.2 - some more cleanups
18  *      v0.3 - cleaner again, waitqueue fixes
19  *      v0.4 - fixes in unidirectional mode
20  *      v0.5 - add DEVICE_ID string support
21  *      v0.6 - never time out
22  *      v0.7 - fixed bulk-IN read and poll (David Paschal)
23  *      v0.8 - add devfs support
24  *      v0.9 - fix unplug-while-open paths
25  *      v0.10- remove sleep_on, fix error on oom (oliver@neukum.org)
26  *      v0.11 - add proto_bias option (Pete Zaitcev)
27  *      v0.12 - add hpoj.sourceforge.net ioctls (David Paschal)
28  *      v0.13 - alloc space for statusbuf (<status> not on stack);
29  *              use usb_buffer_alloc() for read buf & write buf;
30  */
31
32 /*
33  * This program is free software; you can redistribute it and/or modify
34  * it under the terms of the GNU General Public License as published by
35  * the Free Software Foundation; either version 2 of the License, or
36  * (at your option) any later version.
37  *
38  * This program is distributed in the hope that it will be useful,
39  * but WITHOUT ANY WARRANTY; without even the implied warranty of
40  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
41  * GNU General Public License for more details.
42  *
43  * You should have received a copy of the GNU General Public License
44  * along with this program; if not, write to the Free Software
45  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
46  */
47
48 #include <linux/module.h>
49 #include <linux/kernel.h>
50 #include <linux/sched.h>
51 #include <linux/smp_lock.h>
52 #include <linux/signal.h>
53 #include <linux/poll.h>
54 #include <linux/init.h>
55 #include <linux/slab.h>
56 #include <linux/lp.h>
57 #undef DEBUG
58 #include <linux/usb.h>
59
60 /*
61  * Version Information
62  */
63 #define DRIVER_VERSION "v0.13"
64 #define DRIVER_AUTHOR "Michael Gee, Pavel Machek, Vojtech Pavlik, Randy Dunlap, Pete Zaitcev, David Paschal"
65 #define DRIVER_DESC "USB Printer Device Class driver"
66
67 #define USBLP_BUF_SIZE          8192
68 #define USBLP_DEVICE_ID_SIZE    1024
69
70 /* ioctls: */
71 #define LPGETSTATUS             0x060b          /* same as in drivers/char/lp.c */
72 #define IOCNR_GET_DEVICE_ID             1
73 #define IOCNR_GET_PROTOCOLS             2
74 #define IOCNR_SET_PROTOCOL              3
75 #define IOCNR_HP_SET_CHANNEL            4
76 #define IOCNR_GET_BUS_ADDRESS           5
77 #define IOCNR_GET_VID_PID               6
78 #define IOCNR_SOFT_RESET                7
79 /* Get device_id string: */
80 #define LPIOC_GET_DEVICE_ID(len) _IOC(_IOC_READ, 'P', IOCNR_GET_DEVICE_ID, len)
81 /* The following ioctls were added for http://hpoj.sourceforge.net: */
82 /* Get two-int array:
83  * [0]=current protocol (1=7/1/1, 2=7/1/2, 3=7/1/3),
84  * [1]=supported protocol mask (mask&(1<<n)!=0 means 7/1/n supported): */
85 #define LPIOC_GET_PROTOCOLS(len) _IOC(_IOC_READ, 'P', IOCNR_GET_PROTOCOLS, len)
86 /* Set protocol (arg: 1=7/1/1, 2=7/1/2, 3=7/1/3): */
87 #define LPIOC_SET_PROTOCOL _IOC(_IOC_WRITE, 'P', IOCNR_SET_PROTOCOL, 0)
88 /* Set channel number (HP Vendor-specific command): */
89 #define LPIOC_HP_SET_CHANNEL _IOC(_IOC_WRITE, 'P', IOCNR_HP_SET_CHANNEL, 0)
90 /* Get two-int array: [0]=bus number, [1]=device address: */
91 #define LPIOC_GET_BUS_ADDRESS(len) _IOC(_IOC_READ, 'P', IOCNR_GET_BUS_ADDRESS, len)
92 /* Get two-int array: [0]=vendor ID, [1]=product ID: */
93 #define LPIOC_GET_VID_PID(len) _IOC(_IOC_READ, 'P', IOCNR_GET_VID_PID, len)
94 /* Perform class specific soft reset */
95 #define LPIOC_SOFT_RESET _IOC(_IOC_NONE, 'P', IOCNR_SOFT_RESET, 0);
96
97 /*
98  * A DEVICE_ID string may include the printer's serial number.
99  * It should end with a semi-colon (';').
100  * An example from an HP 970C DeskJet printer is (this is one long string,
101  * with the serial number changed):
102 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:                    ;
103  */
104
105 /*
106  * USB Printer Requests
107  */
108
109 #define USBLP_REQ_GET_ID                        0x00
110 #define USBLP_REQ_GET_STATUS                    0x01
111 #define USBLP_REQ_RESET                         0x02
112 #define USBLP_REQ_HP_CHANNEL_CHANGE_REQUEST     0x00    /* HP Vendor-specific */
113
114 #define USBLP_MINORS            16
115 #define USBLP_MINOR_BASE        0
116
117 #define USBLP_WRITE_TIMEOUT     (5000)                  /* 5 seconds */
118
119 #define USBLP_FIRST_PROTOCOL    1
120 #define USBLP_LAST_PROTOCOL     3
121 #define USBLP_MAX_PROTOCOLS     (USBLP_LAST_PROTOCOL+1)
122
123 /*
124  * some arbitrary status buffer size;
125  * need a status buffer that is allocated via kmalloc(), not on stack
126  */
127 #define STATUS_BUF_SIZE         8
128
129 struct usblp {
130         struct usb_device       *dev;                   /* USB device */
131         struct semaphore        sem;                    /* locks this struct, especially "dev" */
132         char                    *writebuf;              /* write transfer_buffer */
133         char                    *readbuf;               /* read transfer_buffer */
134         char                    *statusbuf;             /* status transfer_buffer */
135         struct urb              *readurb, *writeurb;    /* The urbs */
136         wait_queue_head_t       wait;                   /* Zzzzz ... */
137         int                     readcount;              /* Counter for reads */
138         int                     ifnum;                  /* Interface number */
139         struct usb_interface    *intf;                  /* The interface */
140         /* Alternate-setting numbers and endpoints for each protocol
141          * (7/1/{index=1,2,3}) that the device supports: */
142         struct {
143                 int                             alt_setting;
144                 struct usb_endpoint_descriptor  *epwrite;
145                 struct usb_endpoint_descriptor  *epread;
146         }                       protocol[USBLP_MAX_PROTOCOLS];
147         int                     current_protocol;
148         int                     minor;                  /* minor number of device */
149         int                     wcomplete;              /* writing is completed */
150         int                     rcomplete;              /* reading is completed */
151         unsigned int            quirks;                 /* quirks flags */
152         unsigned char           used;                   /* True if open */
153         unsigned char           present;                /* True if not disconnected */
154         unsigned char           bidir;                  /* interface is bidirectional */
155         unsigned char           *device_id_string;      /* IEEE 1284 DEVICE ID string (ptr) */
156                                                         /* first 2 bytes are (big-endian) length */
157 };
158
159 #ifdef DEBUG
160 static void usblp_dump(struct usblp *usblp) {
161         int p;
162
163         dbg("usblp=0x%p", usblp);
164         dbg("dev=0x%p", usblp->dev);
165         dbg("present=%d", usblp->present);
166         dbg("readbuf=0x%p", usblp->readbuf);
167         dbg("writebuf=0x%p", usblp->writebuf);
168         dbg("readurb=0x%p", usblp->readurb);
169         dbg("writeurb=0x%p", usblp->writeurb);
170         dbg("readcount=%d", usblp->readcount);
171         dbg("ifnum=%d", usblp->ifnum);
172     for (p = USBLP_FIRST_PROTOCOL; p <= USBLP_LAST_PROTOCOL; p++) {
173         dbg("protocol[%d].alt_setting=%d", p, usblp->protocol[p].alt_setting);
174         dbg("protocol[%d].epwrite=%p", p, usblp->protocol[p].epwrite);
175         dbg("protocol[%d].epread=%p", p, usblp->protocol[p].epread);
176     }
177         dbg("current_protocol=%d", usblp->current_protocol);
178         dbg("minor=%d", usblp->minor);
179         dbg("wcomplete=%d", usblp->wcomplete);
180         dbg("rcomplete=%d", usblp->rcomplete);
181         dbg("quirks=%d", usblp->quirks);
182         dbg("used=%d", usblp->used);
183         dbg("bidir=%d", usblp->bidir);
184         dbg("device_id_string=\"%s\"",
185                 usblp->device_id_string ?
186                         usblp->device_id_string + 2 :
187                         (unsigned char *)"(null)");
188 }
189 #endif
190
191 /* Quirks: various printer quirks are handled by this table & its flags. */
192
193 struct quirk_printer_struct {
194         __u16 vendorId;
195         __u16 productId;
196         unsigned int quirks;
197 };
198
199 #define USBLP_QUIRK_BIDIR       0x1     /* reports bidir but requires unidirectional mode (no INs/reads) */
200 #define USBLP_QUIRK_USB_INIT    0x2     /* needs vendor USB init string */
201
202 static struct quirk_printer_struct quirk_printers[] = {
203         { 0x03f0, 0x0004, USBLP_QUIRK_BIDIR }, /* HP DeskJet 895C */
204         { 0x03f0, 0x0104, USBLP_QUIRK_BIDIR }, /* HP DeskJet 880C */
205         { 0x03f0, 0x0204, USBLP_QUIRK_BIDIR }, /* HP DeskJet 815C */
206         { 0x03f0, 0x0304, USBLP_QUIRK_BIDIR }, /* HP DeskJet 810C/812C */
207         { 0x03f0, 0x0404, USBLP_QUIRK_BIDIR }, /* HP DeskJet 830C */
208         { 0x03f0, 0x0504, USBLP_QUIRK_BIDIR }, /* HP DeskJet 885C */
209         { 0x03f0, 0x0604, USBLP_QUIRK_BIDIR }, /* HP DeskJet 840C */   
210         { 0x03f0, 0x0804, USBLP_QUIRK_BIDIR }, /* HP DeskJet 816C */   
211         { 0x03f0, 0x1104, USBLP_QUIRK_BIDIR }, /* HP Deskjet 959C */
212         { 0x0409, 0xefbe, USBLP_QUIRK_BIDIR }, /* NEC Picty900 (HP OEM) */
213         { 0x0409, 0xbef4, USBLP_QUIRK_BIDIR }, /* NEC Picty760 (HP OEM) */
214         { 0x0409, 0xf0be, USBLP_QUIRK_BIDIR }, /* NEC Picty920 (HP OEM) */
215         { 0x0409, 0xf1be, USBLP_QUIRK_BIDIR }, /* NEC Picty800 (HP OEM) */
216         { 0, 0 }
217 };
218
219 static int usblp_select_alts(struct usblp *usblp);
220 static int usblp_set_protocol(struct usblp *usblp, int protocol);
221 static int usblp_cache_device_id_string(struct usblp *usblp);
222
223 /* forward reference to make our lives easier */
224 static struct usb_driver usblp_driver;
225 static DECLARE_MUTEX(usblp_sem);        /* locks the existence of usblp's */
226
227 /*
228  * Functions for usblp control messages.
229  */
230
231 static int usblp_ctrl_msg(struct usblp *usblp, int request, int type, int dir, int recip, int value, void *buf, int len)
232 {
233         int retval;
234         int index = usblp->ifnum;
235
236         /* High byte has the interface index.
237            Low byte has the alternate setting.
238          */
239         if ((request == USBLP_REQ_GET_ID) && (type == USB_TYPE_CLASS)) {
240           index = (usblp->ifnum<<8)|usblp->protocol[usblp->current_protocol].alt_setting;
241         }
242
243         retval = usb_control_msg(usblp->dev,
244                 dir ? usb_rcvctrlpipe(usblp->dev, 0) : usb_sndctrlpipe(usblp->dev, 0),
245                 request, type | dir | recip, value, index, buf, len, USBLP_WRITE_TIMEOUT);
246         dbg("usblp_control_msg: rq: 0x%02x dir: %d recip: %d value: %d idx: %d len: %#x result: %d",
247                 request, !!dir, recip, value, index, len, retval);
248         return retval < 0 ? retval : 0;
249 }
250
251 #define usblp_read_status(usblp, status)\
252         usblp_ctrl_msg(usblp, USBLP_REQ_GET_STATUS, USB_TYPE_CLASS, USB_DIR_IN, USB_RECIP_INTERFACE, 0, status, 1)
253 #define usblp_get_id(usblp, config, id, maxlen)\
254         usblp_ctrl_msg(usblp, USBLP_REQ_GET_ID, USB_TYPE_CLASS, USB_DIR_IN, USB_RECIP_INTERFACE, config, id, maxlen)
255 #define usblp_reset(usblp)\
256         usblp_ctrl_msg(usblp, USBLP_REQ_RESET, USB_TYPE_CLASS, USB_DIR_OUT, USB_RECIP_OTHER, 0, NULL, 0)
257
258 #define usblp_hp_channel_change_request(usblp, channel, buffer) \
259         usblp_ctrl_msg(usblp, USBLP_REQ_HP_CHANNEL_CHANGE_REQUEST, USB_TYPE_VENDOR, USB_DIR_IN, USB_RECIP_INTERFACE, channel, buffer, 1)
260
261 /*
262  * See the description for usblp_select_alts() below for the usage
263  * explanation.  Look into your /proc/bus/usb/devices and dmesg in
264  * case of any trouble.
265  */
266 static int proto_bias = -1;
267
268 /*
269  * URB callback.
270  */
271
272 static void usblp_bulk_read(struct urb *urb, struct pt_regs *regs)
273 {
274         struct usblp *usblp = urb->context;
275
276         if (!usblp || !usblp->dev || !usblp->used || !usblp->present)
277                 return;
278
279         if (unlikely(urb->status))
280                 warn("usblp%d: nonzero read/write bulk status received: %d",
281                         usblp->minor, urb->status);
282         usblp->rcomplete = 1;
283         wake_up_interruptible(&usblp->wait);
284 }
285
286 static void usblp_bulk_write(struct urb *urb, struct pt_regs *regs)
287 {
288         struct usblp *usblp = urb->context;
289
290         if (!usblp || !usblp->dev || !usblp->used || !usblp->present)
291                 return;
292
293         if (unlikely(urb->status))
294                 warn("usblp%d: nonzero read/write bulk status received: %d",
295                         usblp->minor, urb->status);
296         usblp->wcomplete = 1;
297         wake_up_interruptible(&usblp->wait);
298 }
299
300 /*
301  * Get and print printer errors.
302  */
303
304 static char *usblp_messages[] = { "ok", "out of paper", "off-line", "on fire" };
305
306 static int usblp_check_status(struct usblp *usblp, int err)
307 {
308         unsigned char status, newerr = 0;
309         int error;
310
311         error = usblp_read_status (usblp, usblp->statusbuf);
312         if (error < 0) {
313                 err("usblp%d: error %d reading printer status",
314                         usblp->minor, error);
315                 return 0;
316         }
317
318         status = *usblp->statusbuf;
319
320         if (~status & LP_PERRORP)
321                 newerr = 3;
322         if (status & LP_POUTPA)
323                 newerr = 1;
324         if (~status & LP_PSELECD)
325                 newerr = 2;
326
327         if (newerr != err)
328                 info("usblp%d: %s", usblp->minor, usblp_messages[newerr]);
329
330         return newerr;
331 }
332
333 /*
334  * File op functions.
335  */
336
337 static int usblp_open(struct inode *inode, struct file *file)
338 {
339         int minor = iminor(inode);
340         struct usblp *usblp;
341         struct usb_interface *intf;
342         int retval;
343
344         if (minor < 0)
345                 return -ENODEV;
346
347         down (&usblp_sem);
348
349         retval = -ENODEV;
350         intf = usb_find_interface(&usblp_driver, minor);
351         if (!intf) {
352                 goto out;
353         }
354         usblp = usb_get_intfdata (intf);
355         if (!usblp || !usblp->dev || !usblp->present)
356                 goto out;
357
358         retval = -EBUSY;
359         if (usblp->used)
360                 goto out;
361
362         /*
363          * TODO: need to implement LP_ABORTOPEN + O_NONBLOCK as in drivers/char/lp.c ???
364          * This is #if 0-ed because we *don't* want to fail an open
365          * just because the printer is off-line.
366          */
367 #if 0
368         if ((retval = usblp_check_status(usblp, 0))) {
369                 retval = retval > 1 ? -EIO : -ENOSPC;
370                 goto out;
371         }
372 #else
373         retval = 0;
374 #endif
375
376         usblp->used = 1;
377         file->private_data = usblp;
378
379         usblp->writeurb->transfer_buffer_length = 0;
380         usblp->wcomplete = 1; /* we begin writeable */
381         usblp->rcomplete = 0;
382         usblp->writeurb->status = 0;
383         usblp->readurb->status = 0;
384
385         if (usblp->bidir) {
386                 usblp->readcount = 0;
387                 usblp->readurb->dev = usblp->dev;
388                 if (usb_submit_urb(usblp->readurb, GFP_KERNEL) < 0) {
389                         retval = -EIO;
390                         usblp->used = 0;
391                         file->private_data = NULL;
392                 }
393         }
394 out:
395         up (&usblp_sem);
396         return retval;
397 }
398
399 static void usblp_cleanup (struct usblp *usblp)
400 {
401         info("usblp%d: removed", usblp->minor);
402
403         kfree (usblp->device_id_string);
404         kfree (usblp->statusbuf);
405         usb_free_urb(usblp->writeurb);
406         usb_free_urb(usblp->readurb);
407         kfree (usblp);
408 }
409
410 static void usblp_unlink_urbs(struct usblp *usblp)
411 {
412         usb_kill_urb(usblp->writeurb);
413         if (usblp->bidir)
414                 usb_kill_urb(usblp->readurb);
415 }
416
417 static int usblp_release(struct inode *inode, struct file *file)
418 {
419         struct usblp *usblp = file->private_data;
420
421         down (&usblp_sem);
422         usblp->used = 0;
423         if (usblp->present) {
424                 usblp_unlink_urbs(usblp);
425         } else          /* finish cleanup from disconnect */
426                 usblp_cleanup (usblp);
427         up (&usblp_sem);
428         return 0;
429 }
430
431 /* No kernel lock - fine */
432 static unsigned int usblp_poll(struct file *file, struct poll_table_struct *wait)
433 {
434         struct usblp *usblp = file->private_data;
435         poll_wait(file, &usblp->wait, wait);
436         return ((!usblp->bidir || !usblp->rcomplete) ? 0 : POLLIN  | POLLRDNORM)
437                                | (!usblp->wcomplete ? 0 : POLLOUT | POLLWRNORM);
438 }
439
440 static int usblp_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
441 {
442         struct usblp *usblp = file->private_data;
443         int length, err, i;
444         unsigned char newChannel;
445         int status;
446         int twoints[2];
447         int retval = 0;
448
449         down (&usblp->sem);
450         if (!usblp->present) {
451                 retval = -ENODEV;
452                 goto done;
453         }
454
455         dbg("usblp_ioctl: cmd=0x%x (%c nr=%d len=%d dir=%d)", cmd, _IOC_TYPE(cmd),
456                 _IOC_NR(cmd), _IOC_SIZE(cmd), _IOC_DIR(cmd) );
457
458         if (_IOC_TYPE(cmd) == 'P')      /* new-style ioctl number */
459
460                 switch (_IOC_NR(cmd)) {
461
462                         case IOCNR_GET_DEVICE_ID: /* get the DEVICE_ID string */
463                                 if (_IOC_DIR(cmd) != _IOC_READ) {
464                                         retval = -EINVAL;
465                                         goto done;
466                                 }
467
468                                 length = usblp_cache_device_id_string(usblp);
469                                 if (length < 0) {
470                                         retval = length;
471                                         goto done;
472                                 }
473                                 if (length > _IOC_SIZE(cmd))
474                                         length = _IOC_SIZE(cmd); /* truncate */
475
476                                 if (copy_to_user((void __user *) arg,
477                                                 usblp->device_id_string,
478                                                 (unsigned long) length)) {
479                                         retval = -EFAULT;
480                                         goto done;
481                                 }
482
483                                 break;
484
485                         case IOCNR_GET_PROTOCOLS:
486                                 if (_IOC_DIR(cmd) != _IOC_READ ||
487                                     _IOC_SIZE(cmd) < sizeof(twoints)) {
488                                         retval = -EINVAL;
489                                         goto done;
490                                 }
491
492                                 twoints[0] = usblp->current_protocol;
493                                 twoints[1] = 0;
494                                 for (i = USBLP_FIRST_PROTOCOL;
495                                      i <= USBLP_LAST_PROTOCOL; i++) {
496                                         if (usblp->protocol[i].alt_setting >= 0)
497                                                 twoints[1] |= (1<<i);
498                                 }
499
500                                 if (copy_to_user((void __user *)arg,
501                                                 (unsigned char *)twoints,
502                                                 sizeof(twoints))) {
503                                         retval = -EFAULT;
504                                         goto done;
505                                 }
506
507                                 break;
508
509                         case IOCNR_SET_PROTOCOL:
510                                 if (_IOC_DIR(cmd) != _IOC_WRITE) {
511                                         retval = -EINVAL;
512                                         goto done;
513                                 }
514
515 #ifdef DEBUG
516                                 if (arg == -10) {
517                                         usblp_dump(usblp);
518                                         break;
519                                 }
520 #endif
521
522                                 usblp_unlink_urbs(usblp);
523                                 retval = usblp_set_protocol(usblp, arg);
524                                 if (retval < 0) {
525                                         usblp_set_protocol(usblp,
526                                                 usblp->current_protocol);
527                                 }
528                                 break;
529
530                         case IOCNR_HP_SET_CHANNEL:
531                                 if (_IOC_DIR(cmd) != _IOC_WRITE ||
532                                     le16_to_cpu(usblp->dev->descriptor.idVendor) != 0x03F0 ||
533                                     usblp->quirks & USBLP_QUIRK_BIDIR) {
534                                         retval = -EINVAL;
535                                         goto done;
536                                 }
537
538                                 err = usblp_hp_channel_change_request(usblp,
539                                         arg, &newChannel);
540                                 if (err < 0) {
541                                         err("usblp%d: error = %d setting "
542                                                 "HP channel",
543                                                 usblp->minor, err);
544                                         retval = -EIO;
545                                         goto done;
546                                 }
547
548                                 dbg("usblp%d requested/got HP channel %ld/%d",
549                                         usblp->minor, arg, newChannel);
550                                 break;
551
552                         case IOCNR_GET_BUS_ADDRESS:
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->dev->bus->busnum;
560                                 twoints[1] = usblp->dev->devnum;
561                                 if (copy_to_user((void __user *)arg,
562                                                 (unsigned char *)twoints,
563                                                 sizeof(twoints))) {
564                                         retval = -EFAULT;
565                                         goto done;
566                                 }
567
568                                 dbg("usblp%d is bus=%d, device=%d",
569                                         usblp->minor, twoints[0], twoints[1]);
570                                 break;
571
572                         case IOCNR_GET_VID_PID:
573                                 if (_IOC_DIR(cmd) != _IOC_READ ||
574                                     _IOC_SIZE(cmd) < sizeof(twoints)) {
575                                         retval = -EINVAL;
576                                         goto done;
577                                 }
578
579                                 twoints[0] = le16_to_cpu(usblp->dev->descriptor.idVendor);
580                                 twoints[1] = le16_to_cpu(usblp->dev->descriptor.idProduct);
581                                 if (copy_to_user((void __user *)arg,
582                                                 (unsigned char *)twoints,
583                                                 sizeof(twoints))) {
584                                         retval = -EFAULT;
585                                         goto done;
586                                 }
587
588                                 dbg("usblp%d is VID=0x%4.4X, PID=0x%4.4X",
589                                         usblp->minor, twoints[0], twoints[1]);
590                                 break;
591
592                         case IOCNR_SOFT_RESET:
593                                 if (_IOC_DIR(cmd) != _IOC_NONE) {
594                                         retval = -EINVAL;
595                                         goto done;
596                                 }
597                                 retval = usblp_reset(usblp);
598                                 break;
599                         default:
600                                 retval = -ENOTTY;
601                 }
602         else    /* old-style ioctl value */
603                 switch (cmd) {
604
605                         case LPGETSTATUS:
606                                 if (usblp_read_status(usblp, usblp->statusbuf)) {
607                                         err("usblp%d: failed reading printer status", usblp->minor);
608                                         retval = -EIO;
609                                         goto done;
610                                 }
611                                 status = *usblp->statusbuf;
612                                 if (copy_to_user ((void __user *)arg, &status, sizeof(int)))
613                                         retval = -EFAULT;
614                                 break;
615
616                         default:
617                                 retval = -ENOTTY;
618                 }
619
620 done:
621         up (&usblp->sem);
622         return retval;
623 }
624
625 static ssize_t usblp_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos)
626 {
627         DECLARE_WAITQUEUE(wait, current);
628         struct usblp *usblp = file->private_data;
629         int timeout, err = 0, transfer_length = 0;
630         size_t writecount = 0;
631
632         while (writecount < count) {
633                 if (!usblp->wcomplete) {
634                         barrier();
635                         if (file->f_flags & O_NONBLOCK) {
636                                 writecount += transfer_length;
637                                 return writecount ? writecount : -EAGAIN;
638                         }
639
640                         timeout = USBLP_WRITE_TIMEOUT;
641                         add_wait_queue(&usblp->wait, &wait);
642                         while ( 1==1 ) {
643
644                                 if (signal_pending(current)) {
645                                         remove_wait_queue(&usblp->wait, &wait);
646                                         return writecount ? writecount : -EINTR;
647                                 }
648                                 set_current_state(TASK_INTERRUPTIBLE);
649                                 if (timeout && !usblp->wcomplete) {
650                                         timeout = schedule_timeout(timeout);
651                                 } else {
652                                         set_current_state(TASK_RUNNING);
653                                         break;
654                                 }
655                         }
656                         remove_wait_queue(&usblp->wait, &wait);
657                 }
658
659                 down (&usblp->sem);
660                 if (!usblp->present) {
661                         up (&usblp->sem);
662                         return -ENODEV;
663                 }
664
665                 if (usblp->writeurb->status != 0) {
666                         if (usblp->quirks & USBLP_QUIRK_BIDIR) {
667                                 if (!usblp->wcomplete)
668                                         err("usblp%d: error %d writing to printer",
669                                                 usblp->minor, usblp->writeurb->status);
670                                 err = usblp->writeurb->status;
671                         } else
672                                 err = usblp_check_status(usblp, err);
673                         up (&usblp->sem);
674
675                         /* if the fault was due to disconnect, let khubd's
676                          * call to usblp_disconnect() grab usblp->sem ...
677                          */
678                         schedule ();
679                         continue;
680                 }
681
682                 /* We must increment writecount here, and not at the
683                  * end of the loop. Otherwise, the final loop iteration may
684                  * be skipped, leading to incomplete printer output.
685                  */
686                 writecount += transfer_length;
687                 if (writecount == count) {
688                         up(&usblp->sem);
689                         break;
690                 }
691
692                 transfer_length=(count - writecount);
693                 if (transfer_length > USBLP_BUF_SIZE)
694                         transfer_length = USBLP_BUF_SIZE;
695
696                 usblp->writeurb->transfer_buffer_length = transfer_length;
697
698                 if (copy_from_user(usblp->writeurb->transfer_buffer, 
699                                    buffer + writecount, transfer_length)) {
700                         up(&usblp->sem);
701                         return writecount ? writecount : -EFAULT;
702                 }
703
704                 usblp->writeurb->dev = usblp->dev;
705                 usblp->wcomplete = 0;
706                 err = usb_submit_urb(usblp->writeurb, GFP_KERNEL);
707                 if (err) {
708                         if (err != -ENOMEM)
709                                 count = -EIO;
710                         else
711                                 count = writecount ? writecount : -ENOMEM;
712                         up (&usblp->sem);
713                         break;
714                 }
715                 up (&usblp->sem);
716         }
717
718         return count;
719 }
720
721 static ssize_t usblp_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos)
722 {
723         struct usblp *usblp = file->private_data;
724         DECLARE_WAITQUEUE(wait, current);
725
726         if (!usblp->bidir)
727                 return -EINVAL;
728
729         down (&usblp->sem);
730         if (!usblp->present) {
731                 count = -ENODEV;
732                 goto done;
733         }
734
735         if (!usblp->rcomplete) {
736                 barrier();
737
738                 if (file->f_flags & O_NONBLOCK) {
739                         count = -EAGAIN;
740                         goto done;
741                 }
742
743                 add_wait_queue(&usblp->wait, &wait);
744                 while (1==1) {
745                         if (signal_pending(current)) {
746                                 count = -EINTR;
747                                 remove_wait_queue(&usblp->wait, &wait);
748                                 goto done;
749                         }
750                         up (&usblp->sem);
751                         set_current_state(TASK_INTERRUPTIBLE);
752                         if (!usblp->rcomplete) {
753                                 schedule();
754                         } else {
755                                 set_current_state(TASK_RUNNING);
756                                 break;
757                         }
758                         down (&usblp->sem);
759                 }
760                 remove_wait_queue(&usblp->wait, &wait);
761         }
762
763         if (!usblp->present) {
764                 count = -ENODEV;
765                 goto done;
766         }
767
768         if (usblp->readurb->status) {
769                 err("usblp%d: error %d reading from printer",
770                         usblp->minor, usblp->readurb->status);
771                 usblp->readurb->dev = usblp->dev;
772                 usblp->readcount = 0;
773                 usblp->rcomplete = 0;
774                 if (usb_submit_urb(usblp->readurb, GFP_KERNEL) < 0)
775                         dbg("error submitting urb");
776                 count = -EIO;
777                 goto done;
778         }
779
780         count = count < usblp->readurb->actual_length - usblp->readcount ?
781                 count : usblp->readurb->actual_length - usblp->readcount;
782
783         if (copy_to_user(buffer, usblp->readurb->transfer_buffer + usblp->readcount, count)) {
784                 count = -EFAULT;
785                 goto done;
786         }
787
788         if ((usblp->readcount += count) == usblp->readurb->actual_length) {
789                 usblp->readcount = 0;
790                 usblp->readurb->dev = usblp->dev;
791                 usblp->rcomplete = 0;
792                 if (usb_submit_urb(usblp->readurb, GFP_KERNEL)) {
793                         count = -EIO;
794                         goto done;
795                 }
796         }
797
798 done:
799         up (&usblp->sem);
800         return count;
801 }
802
803 /*
804  * Checks for printers that have quirks, such as requiring unidirectional
805  * communication but reporting bidirectional; currently some HP printers
806  * have this flaw (HP 810, 880, 895, etc.), or needing an init string
807  * sent at each open (like some Epsons).
808  * Returns 1 if found, 0 if not found.
809  *
810  * HP recommended that we use the bidirectional interface but
811  * don't attempt any bulk IN transfers from the IN endpoint.
812  * Here's some more detail on the problem:
813  * The problem is not that it isn't bidirectional though. The problem
814  * is that if you request a device ID, or status information, while
815  * the buffers are full, the return data will end up in the print data
816  * buffer. For example if you make sure you never request the device ID
817  * while you are sending print data, and you don't try to query the
818  * printer status every couple of milliseconds, you will probably be OK.
819  */
820 static unsigned int usblp_quirks (__u16 vendor, __u16 product)
821 {
822         int i;
823
824         for (i = 0; quirk_printers[i].vendorId; i++) {
825                 if (vendor == quirk_printers[i].vendorId &&
826                     product == quirk_printers[i].productId)
827                         return quirk_printers[i].quirks;
828         }
829         return 0;
830 }
831
832 static struct file_operations usblp_fops = {
833         .owner =        THIS_MODULE,
834         .read =         usblp_read,
835         .write =        usblp_write,
836         .poll =         usblp_poll,
837         .ioctl =        usblp_ioctl,
838         .open =         usblp_open,
839         .release =      usblp_release,
840 };
841
842 static struct usb_class_driver usblp_class = {
843         .name =         "usb/lp%d",
844         .fops =         &usblp_fops,
845         .mode =         S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP,
846         .minor_base =   USBLP_MINOR_BASE,
847 };
848
849 static int usblp_probe(struct usb_interface *intf,
850                        const struct usb_device_id *id)
851 {
852         struct usb_device *dev = interface_to_usbdev (intf);
853         struct usblp *usblp = NULL;
854         int protocol;
855         int retval;
856
857         /* Malloc and start initializing usblp structure so we can use it
858          * directly. */
859         if (!(usblp = kmalloc(sizeof(struct usblp), GFP_KERNEL))) {
860                 err("out of memory for usblp");
861                 goto abort;
862         }
863         memset(usblp, 0, sizeof(struct usblp));
864         usblp->dev = dev;
865         init_MUTEX (&usblp->sem);
866         init_waitqueue_head(&usblp->wait);
867         usblp->ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
868         usblp->intf = intf;
869
870         usblp->writeurb = usb_alloc_urb(0, GFP_KERNEL);
871         if (!usblp->writeurb) {
872                 err("out of memory");
873                 goto abort;
874         }
875         usblp->readurb = usb_alloc_urb(0, GFP_KERNEL);
876         if (!usblp->readurb) {
877                 err("out of memory");
878                 goto abort;
879         }
880
881         /* Malloc device ID string buffer to the largest expected length,
882          * since we can re-query it on an ioctl and a dynamic string
883          * could change in length. */
884         if (!(usblp->device_id_string = kmalloc(USBLP_DEVICE_ID_SIZE, GFP_KERNEL))) {
885                 err("out of memory for device_id_string");
886                 goto abort;
887         }
888
889         usblp->writebuf = usblp->readbuf = NULL;
890         usblp->writeurb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
891         usblp->readurb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
892         /* Malloc write & read buffers.  We somewhat wastefully
893          * malloc both regardless of bidirectionality, because the
894          * alternate setting can be changed later via an ioctl. */
895         if (!(usblp->writebuf = usb_buffer_alloc(dev, USBLP_BUF_SIZE,
896                                 GFP_KERNEL, &usblp->writeurb->transfer_dma))) {
897                 err("out of memory for write buf");
898                 goto abort;
899         }
900         if (!(usblp->readbuf = usb_buffer_alloc(dev, USBLP_BUF_SIZE,
901                                 GFP_KERNEL, &usblp->readurb->transfer_dma))) {
902                 err("out of memory for read buf");
903                 goto abort;
904         }
905
906         /* Allocate buffer for printer status */
907         usblp->statusbuf = kmalloc(STATUS_BUF_SIZE, GFP_KERNEL);
908         if (!usblp->statusbuf) {
909                 err("out of memory for statusbuf");
910                 goto abort;
911         }
912
913         /* Lookup quirks for this printer. */
914         usblp->quirks = usblp_quirks(
915                 le16_to_cpu(dev->descriptor.idVendor),
916                 le16_to_cpu(dev->descriptor.idProduct));
917
918         /* Analyze and pick initial alternate settings and endpoints. */
919         protocol = usblp_select_alts(usblp);
920         if (protocol < 0) {
921                 dbg("incompatible printer-class device 0x%4.4X/0x%4.4X",
922                         le16_to_cpu(dev->descriptor.idVendor),
923                         le16_to_cpu(dev->descriptor.idProduct));
924                 goto abort;
925         }
926
927         /* Setup the selected alternate setting and endpoints. */
928         if (usblp_set_protocol(usblp, protocol) < 0)
929                 goto abort;
930
931         /* Retrieve and store the device ID string. */
932         usblp_cache_device_id_string(usblp);
933
934 #ifdef DEBUG
935         usblp_check_status(usblp, 0);
936 #endif
937
938         info("usblp%d: USB %sdirectional printer dev %d "
939                 "if %d alt %d proto %d vid 0x%4.4X pid 0x%4.4X",
940                 usblp->minor, usblp->bidir ? "Bi" : "Uni", dev->devnum,
941                 usblp->ifnum,
942                 usblp->protocol[usblp->current_protocol].alt_setting,
943                 usblp->current_protocol,
944                 le16_to_cpu(usblp->dev->descriptor.idVendor),
945                 le16_to_cpu(usblp->dev->descriptor.idProduct));
946
947         usb_set_intfdata (intf, usblp);
948
949         usblp->present = 1;
950
951         retval = usb_register_dev(intf, &usblp_class);
952         if (retval) {
953                 err("Not able to get a minor for this device.");
954                 goto abort_intfdata;
955         }
956         usblp->minor = intf->minor;
957
958         return 0;
959
960 abort_intfdata:
961         usb_set_intfdata (intf, NULL);
962 abort:
963         if (usblp) {
964                 if (usblp->writebuf)
965                         usb_buffer_free (usblp->dev, USBLP_BUF_SIZE,
966                                 usblp->writebuf, usblp->writeurb->transfer_dma);
967                 if (usblp->readbuf)
968                         usb_buffer_free (usblp->dev, USBLP_BUF_SIZE,
969                                 usblp->readbuf, usblp->writeurb->transfer_dma);
970                 kfree(usblp->statusbuf);
971                 kfree(usblp->device_id_string);
972                 usb_free_urb(usblp->writeurb);
973                 usb_free_urb(usblp->readurb);
974                 kfree(usblp);
975         }
976         return -EIO;
977 }
978
979 /*
980  * We are a "new" style driver with usb_device_id table,
981  * but our requirements are too intricate for simple match to handle.
982  *
983  * The "proto_bias" option may be used to specify the preferred protocol
984  * for all USB printers (1=7/1/1, 2=7/1/2, 3=7/1/3).  If the device
985  * supports the preferred protocol, then we bind to it.
986  *
987  * The best interface for us is 7/1/2, because it is compatible
988  * with a stream of characters. If we find it, we bind to it.
989  *
990  * Note that the people from hpoj.sourceforge.net need to be able to
991  * bind to 7/1/3 (MLC/1284.4), so we provide them ioctls for this purpose.
992  *
993  * Failing 7/1/2, we look for 7/1/3, even though it's probably not
994  * stream-compatible, because this matches the behaviour of the old code.
995  *
996  * If nothing else, we bind to 7/1/1 - the unidirectional interface.
997  */
998 static int usblp_select_alts(struct usblp *usblp)
999 {
1000         struct usb_interface *if_alt;
1001         struct usb_host_interface *ifd;
1002         struct usb_endpoint_descriptor *epd, *epwrite, *epread;
1003         int p, i, e;
1004
1005         if_alt = usblp->intf;
1006
1007         for (p = 0; p < USBLP_MAX_PROTOCOLS; p++)
1008                 usblp->protocol[p].alt_setting = -1;
1009
1010         /* Find out what we have. */
1011         for (i = 0; i < if_alt->num_altsetting; i++) {
1012                 ifd = &if_alt->altsetting[i];
1013
1014                 if (ifd->desc.bInterfaceClass != 7 || ifd->desc.bInterfaceSubClass != 1)
1015                         continue;
1016
1017                 if (ifd->desc.bInterfaceProtocol < USBLP_FIRST_PROTOCOL ||
1018                     ifd->desc.bInterfaceProtocol > USBLP_LAST_PROTOCOL)
1019                         continue;
1020
1021                 /* Look for bulk OUT and IN endpoints. */
1022                 epwrite = epread = NULL;
1023                 for (e = 0; e < ifd->desc.bNumEndpoints; e++) {
1024                         epd = &ifd->endpoint[e].desc;
1025
1026                         if ((epd->bmAttributes&USB_ENDPOINT_XFERTYPE_MASK)!=
1027                             USB_ENDPOINT_XFER_BULK)
1028                                 continue;
1029
1030                         if (!(epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK)) {
1031                                 if (!epwrite)
1032                                         epwrite = epd;
1033
1034                         } else {
1035                                 if (!epread)
1036                                         epread = epd;
1037                         }
1038                 }
1039
1040                 /* Ignore buggy hardware without the right endpoints. */
1041                 if (!epwrite || (ifd->desc.bInterfaceProtocol > 1 && !epread))
1042                         continue;
1043
1044                 /* Turn off reads for 7/1/1 (unidirectional) interfaces
1045                  * and buggy bidirectional printers. */
1046                 if (ifd->desc.bInterfaceProtocol == 1) {
1047                         epread = NULL;
1048                 } else if (usblp->quirks & USBLP_QUIRK_BIDIR) {
1049                         info("Disabling reads from problem bidirectional "
1050                                 "printer on usblp%d", usblp->minor);
1051                         epread = NULL;
1052                 }
1053
1054                 usblp->protocol[ifd->desc.bInterfaceProtocol].alt_setting =
1055                                 ifd->desc.bAlternateSetting;
1056                 usblp->protocol[ifd->desc.bInterfaceProtocol].epwrite = epwrite;
1057                 usblp->protocol[ifd->desc.bInterfaceProtocol].epread = epread;
1058         }
1059
1060         /* If our requested protocol is supported, then use it. */
1061         if (proto_bias >= USBLP_FIRST_PROTOCOL &&
1062             proto_bias <= USBLP_LAST_PROTOCOL &&
1063             usblp->protocol[proto_bias].alt_setting != -1)
1064                 return proto_bias;
1065
1066         /* Ordering is important here. */
1067         if (usblp->protocol[2].alt_setting != -1)
1068                 return 2;
1069         if (usblp->protocol[1].alt_setting != -1)
1070                 return 1;
1071         if (usblp->protocol[3].alt_setting != -1)
1072                 return 3;
1073
1074         /* If nothing is available, then don't bind to this device. */
1075         return -1;
1076 }
1077
1078 static int usblp_set_protocol(struct usblp *usblp, int protocol)
1079 {
1080         int r, alts;
1081
1082         if (protocol < USBLP_FIRST_PROTOCOL || protocol > USBLP_LAST_PROTOCOL)
1083                 return -EINVAL;
1084
1085         alts = usblp->protocol[protocol].alt_setting;
1086         if (alts < 0)
1087                 return -EINVAL;
1088         r = usb_set_interface(usblp->dev, usblp->ifnum, alts);
1089         if (r < 0) {
1090                 err("can't set desired altsetting %d on interface %d",
1091                         alts, usblp->ifnum);
1092                 return r;
1093         }
1094
1095         usb_fill_bulk_urb(usblp->writeurb, usblp->dev,
1096                 usb_sndbulkpipe(usblp->dev,
1097                   usblp->protocol[protocol].epwrite->bEndpointAddress),
1098                 usblp->writebuf, 0,
1099                 usblp_bulk_write, usblp);
1100
1101         usblp->bidir = (usblp->protocol[protocol].epread != NULL);
1102         if (usblp->bidir)
1103                 usb_fill_bulk_urb(usblp->readurb, usblp->dev,
1104                         usb_rcvbulkpipe(usblp->dev,
1105                           usblp->protocol[protocol].epread->bEndpointAddress),
1106                         usblp->readbuf, USBLP_BUF_SIZE,
1107                         usblp_bulk_read, usblp);
1108
1109         usblp->current_protocol = protocol;
1110         dbg("usblp%d set protocol %d", usblp->minor, protocol);
1111         return 0;
1112 }
1113
1114 /* Retrieves and caches device ID string.
1115  * Returns length, including length bytes but not null terminator.
1116  * On error, returns a negative errno value. */
1117 static int usblp_cache_device_id_string(struct usblp *usblp)
1118 {
1119         int err, length;
1120
1121         err = usblp_get_id(usblp, 0, usblp->device_id_string, USBLP_DEVICE_ID_SIZE - 1);
1122         if (err < 0) {
1123                 dbg("usblp%d: error = %d reading IEEE-1284 Device ID string",
1124                         usblp->minor, err);
1125                 usblp->device_id_string[0] = usblp->device_id_string[1] = '\0';
1126                 return -EIO;
1127         }
1128
1129         /* First two bytes are length in big-endian.
1130          * They count themselves, and we copy them into
1131          * the user's buffer. */
1132         length = be16_to_cpu(*((__be16 *)usblp->device_id_string));
1133         if (length < 2)
1134                 length = 2;
1135         else if (length >= USBLP_DEVICE_ID_SIZE)
1136                 length = USBLP_DEVICE_ID_SIZE - 1;
1137         usblp->device_id_string[length] = '\0';
1138
1139         dbg("usblp%d Device ID string [len=%d]=\"%s\"",
1140                 usblp->minor, length, &usblp->device_id_string[2]);
1141
1142         return length;
1143 }
1144
1145 static void usblp_disconnect(struct usb_interface *intf)
1146 {
1147         struct usblp *usblp = usb_get_intfdata (intf);
1148
1149         usb_deregister_dev(intf, &usblp_class);
1150
1151         if (!usblp || !usblp->dev) {
1152                 err("bogus disconnect");
1153                 BUG ();
1154         }
1155
1156         down (&usblp_sem);
1157         down (&usblp->sem);
1158         usblp->present = 0;
1159         usb_set_intfdata (intf, NULL);
1160
1161         usblp_unlink_urbs(usblp);
1162         usb_buffer_free (usblp->dev, USBLP_BUF_SIZE,
1163                         usblp->writebuf, usblp->writeurb->transfer_dma);
1164         usb_buffer_free (usblp->dev, USBLP_BUF_SIZE,
1165                         usblp->readbuf, usblp->readurb->transfer_dma);
1166         up (&usblp->sem);
1167
1168         if (!usblp->used)
1169                 usblp_cleanup (usblp);
1170         up (&usblp_sem);
1171 }
1172
1173 static struct usb_device_id usblp_ids [] = {
1174         { USB_DEVICE_INFO(7, 1, 1) },
1175         { USB_DEVICE_INFO(7, 1, 2) },
1176         { USB_DEVICE_INFO(7, 1, 3) },
1177         { USB_INTERFACE_INFO(7, 1, 1) },
1178         { USB_INTERFACE_INFO(7, 1, 2) },
1179         { USB_INTERFACE_INFO(7, 1, 3) },
1180         { }                                             /* Terminating entry */
1181 };
1182
1183 MODULE_DEVICE_TABLE (usb, usblp_ids);
1184
1185 static struct usb_driver usblp_driver = {
1186         .owner =        THIS_MODULE,
1187         .name =         "usblp",
1188         .probe =        usblp_probe,
1189         .disconnect =   usblp_disconnect,
1190         .id_table =     usblp_ids,
1191 };
1192
1193 static int __init usblp_init(void)
1194 {
1195         int retval;
1196         retval = usb_register(&usblp_driver);
1197         if (retval)
1198                 goto out;
1199         info(DRIVER_VERSION ": " DRIVER_DESC);
1200 out:
1201         return retval;
1202 }
1203
1204 static void __exit usblp_exit(void)
1205 {
1206         usb_deregister(&usblp_driver);
1207 }
1208
1209 module_init(usblp_init);
1210 module_exit(usblp_exit);
1211
1212 MODULE_AUTHOR( DRIVER_AUTHOR );
1213 MODULE_DESCRIPTION( DRIVER_DESC );
1214 module_param(proto_bias, int, S_IRUGO | S_IWUSR);
1215 MODULE_PARM_DESC(proto_bias, "Favourite protocol number");
1216 MODULE_LICENSE("GPL");