vserver 1.9.3
[linux-2.6.git] / 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     (5*HZ)                  /* 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
226 /*
227  * Functions for usblp control messages.
228  */
229
230 static int usblp_ctrl_msg(struct usblp *usblp, int request, int type, int dir, int recip, int value, void *buf, int len)
231 {
232         int retval;
233         int index = usblp->ifnum;
234
235         /* High byte has the interface index.
236            Low byte has the alternate setting.
237          */
238         if ((request == USBLP_REQ_GET_ID) && (type == USB_TYPE_CLASS)) {
239           index = (usblp->ifnum<<8)|usblp->protocol[usblp->current_protocol].alt_setting;
240         }
241
242         retval = usb_control_msg(usblp->dev,
243                 dir ? usb_rcvctrlpipe(usblp->dev, 0) : usb_sndctrlpipe(usblp->dev, 0),
244                 request, type | dir | recip, value, index, buf, len, USBLP_WRITE_TIMEOUT);
245         dbg("usblp_control_msg: rq: 0x%02x dir: %d recip: %d value: %d idx: %d len: %#x result: %d",
246                 request, !!dir, recip, value, index, len, retval);
247         return retval < 0 ? retval : 0;
248 }
249
250 #define usblp_read_status(usblp, status)\
251         usblp_ctrl_msg(usblp, USBLP_REQ_GET_STATUS, USB_TYPE_CLASS, USB_DIR_IN, USB_RECIP_INTERFACE, 0, status, 1)
252 #define usblp_get_id(usblp, config, id, maxlen)\
253         usblp_ctrl_msg(usblp, USBLP_REQ_GET_ID, USB_TYPE_CLASS, USB_DIR_IN, USB_RECIP_INTERFACE, config, id, maxlen)
254 #define usblp_reset(usblp)\
255         usblp_ctrl_msg(usblp, USBLP_REQ_RESET, USB_TYPE_CLASS, USB_DIR_OUT, USB_RECIP_OTHER, 0, NULL, 0)
256
257 #define usblp_hp_channel_change_request(usblp, channel, buffer) \
258         usblp_ctrl_msg(usblp, USBLP_REQ_HP_CHANNEL_CHANGE_REQUEST, USB_TYPE_VENDOR, USB_DIR_IN, USB_RECIP_INTERFACE, channel, buffer, 1)
259
260 /*
261  * See the description for usblp_select_alts() below for the usage
262  * explanation.  Look into your /proc/bus/usb/devices and dmesg in
263  * case of any trouble.
264  */
265 static int proto_bias = -1;
266
267 /*
268  * URB callback.
269  */
270
271 static void usblp_bulk_read(struct urb *urb, struct pt_regs *regs)
272 {
273         struct usblp *usblp = urb->context;
274
275         if (!usblp || !usblp->dev || !usblp->used || !usblp->present)
276                 return;
277
278         if (unlikely(urb->status))
279                 warn("usblp%d: nonzero read/write bulk status received: %d",
280                         usblp->minor, urb->status);
281         usblp->rcomplete = 1;
282         wake_up_interruptible(&usblp->wait);
283 }
284
285 static void usblp_bulk_write(struct urb *urb, struct pt_regs *regs)
286 {
287         struct usblp *usblp = urb->context;
288
289         if (!usblp || !usblp->dev || !usblp->used || !usblp->present)
290                 return;
291
292         if (unlikely(urb->status))
293                 warn("usblp%d: nonzero read/write bulk status received: %d",
294                         usblp->minor, urb->status);
295         usblp->wcomplete = 1;
296         wake_up_interruptible(&usblp->wait);
297 }
298
299 /*
300  * Get and print printer errors.
301  */
302
303 static char *usblp_messages[] = { "ok", "out of paper", "off-line", "on fire" };
304
305 static int usblp_check_status(struct usblp *usblp, int err)
306 {
307         unsigned char status, newerr = 0;
308         int error;
309
310         error = usblp_read_status (usblp, usblp->statusbuf);
311         if (error < 0) {
312                 err("usblp%d: error %d reading printer status",
313                         usblp->minor, error);
314                 return 0;
315         }
316
317         status = *usblp->statusbuf;
318
319         if (~status & LP_PERRORP)
320                 newerr = 3;
321         if (status & LP_POUTPA)
322                 newerr = 1;
323         if (~status & LP_PSELECD)
324                 newerr = 2;
325
326         if (newerr != err)
327                 info("usblp%d: %s", usblp->minor, usblp_messages[newerr]);
328
329         return newerr;
330 }
331
332 /*
333  * File op functions.
334  */
335
336 static int usblp_open(struct inode *inode, struct file *file)
337 {
338         int minor = iminor(inode);
339         struct usblp *usblp;
340         struct usb_interface *intf;
341         int retval;
342
343         if (minor < 0)
344                 return -ENODEV;
345
346         lock_kernel();
347
348         retval = -ENODEV;
349         intf = usb_find_interface(&usblp_driver, minor);
350         if (!intf) {
351                 goto out;
352         }
353         usblp = usb_get_intfdata (intf);
354         if (!usblp || !usblp->dev || !usblp->present)
355                 goto out;
356
357         retval = -EBUSY;
358         if (usblp->used)
359                 goto out;
360
361         /*
362          * TODO: need to implement LP_ABORTOPEN + O_NONBLOCK as in drivers/char/lp.c ???
363          * This is #if 0-ed because we *don't* want to fail an open
364          * just because the printer is off-line.
365          */
366 #if 0
367         if ((retval = usblp_check_status(usblp, 0))) {
368                 retval = retval > 1 ? -EIO : -ENOSPC;
369                 goto out;
370         }
371 #else
372         retval = 0;
373 #endif
374
375         usblp->used = 1;
376         file->private_data = usblp;
377
378         usblp->writeurb->transfer_buffer_length = 0;
379         usblp->wcomplete = 1; /* we begin writeable */
380         usblp->rcomplete = 0;
381
382         if (usblp->bidir) {
383                 usblp->readcount = 0;
384                 usblp->readurb->dev = usblp->dev;
385                 if (usb_submit_urb(usblp->readurb, GFP_KERNEL) < 0) {
386                         retval = -EIO;
387                         usblp->used = 0;
388                         file->private_data = NULL;
389                 }
390         }
391 out:
392         unlock_kernel();
393         return retval;
394 }
395
396 static void usblp_cleanup (struct usblp *usblp)
397 {
398         info("usblp%d: removed", usblp->minor);
399
400         kfree (usblp->device_id_string);
401         kfree (usblp->statusbuf);
402         usb_free_urb(usblp->writeurb);
403         usb_free_urb(usblp->readurb);
404         kfree (usblp);
405 }
406
407 static void usblp_unlink_urbs(struct usblp *usblp)
408 {
409         usb_unlink_urb(usblp->writeurb);
410         if (usblp->bidir)
411                 usb_unlink_urb(usblp->readurb);
412 }
413
414 static int usblp_release(struct inode *inode, struct file *file)
415 {
416         struct usblp *usblp = file->private_data;
417
418         down (&usblp->sem);
419         usblp->used = 0;
420         if (usblp->present) {
421                 usblp_unlink_urbs(usblp);
422                 up(&usblp->sem);
423         } else          /* finish cleanup from disconnect */
424                 usblp_cleanup (usblp);
425         return 0;
426 }
427
428 /* No kernel lock - fine */
429 static unsigned int usblp_poll(struct file *file, struct poll_table_struct *wait)
430 {
431         struct usblp *usblp = file->private_data;
432         poll_wait(file, &usblp->wait, wait);
433         return ((!usblp->bidir || !usblp->rcomplete) ? 0 : POLLIN  | POLLRDNORM)
434                                | (!usblp->wcomplete ? 0 : POLLOUT | POLLWRNORM);
435 }
436
437 static int usblp_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
438 {
439         struct usblp *usblp = file->private_data;
440         int length, err, i;
441         unsigned char newChannel;
442         int status;
443         int twoints[2];
444         int retval = 0;
445
446         down (&usblp->sem);
447         if (!usblp->present) {
448                 retval = -ENODEV;
449                 goto done;
450         }
451
452         dbg("usblp_ioctl: cmd=0x%x (%c nr=%d len=%d dir=%d)", cmd, _IOC_TYPE(cmd),
453                 _IOC_NR(cmd), _IOC_SIZE(cmd), _IOC_DIR(cmd) );
454
455         if (_IOC_TYPE(cmd) == 'P')      /* new-style ioctl number */
456
457                 switch (_IOC_NR(cmd)) {
458
459                         case IOCNR_GET_DEVICE_ID: /* get the DEVICE_ID string */
460                                 if (_IOC_DIR(cmd) != _IOC_READ) {
461                                         retval = -EINVAL;
462                                         goto done;
463                                 }
464
465                                 length = usblp_cache_device_id_string(usblp);
466                                 if (length < 0) {
467                                         retval = length;
468                                         goto done;
469                                 }
470                                 if (length > _IOC_SIZE(cmd))
471                                         length = _IOC_SIZE(cmd); /* truncate */
472
473                                 if (copy_to_user((void __user *) arg,
474                                                 usblp->device_id_string,
475                                                 (unsigned long) length)) {
476                                         retval = -EFAULT;
477                                         goto done;
478                                 }
479
480                                 break;
481
482                         case IOCNR_GET_PROTOCOLS:
483                                 if (_IOC_DIR(cmd) != _IOC_READ ||
484                                     _IOC_SIZE(cmd) < sizeof(twoints)) {
485                                         retval = -EINVAL;
486                                         goto done;
487                                 }
488
489                                 twoints[0] = usblp->current_protocol;
490                                 twoints[1] = 0;
491                                 for (i = USBLP_FIRST_PROTOCOL;
492                                      i <= USBLP_LAST_PROTOCOL; i++) {
493                                         if (usblp->protocol[i].alt_setting >= 0)
494                                                 twoints[1] |= (1<<i);
495                                 }
496
497                                 if (copy_to_user((void __user *)arg,
498                                                 (unsigned char *)twoints,
499                                                 sizeof(twoints))) {
500                                         retval = -EFAULT;
501                                         goto done;
502                                 }
503
504                                 break;
505
506                         case IOCNR_SET_PROTOCOL:
507                                 if (_IOC_DIR(cmd) != _IOC_WRITE) {
508                                         retval = -EINVAL;
509                                         goto done;
510                                 }
511
512 #ifdef DEBUG
513                                 if (arg == -10) {
514                                         usblp_dump(usblp);
515                                         break;
516                                 }
517 #endif
518
519                                 usblp_unlink_urbs(usblp);
520                                 retval = usblp_set_protocol(usblp, arg);
521                                 if (retval < 0) {
522                                         usblp_set_protocol(usblp,
523                                                 usblp->current_protocol);
524                                 }
525                                 break;
526
527                         case IOCNR_HP_SET_CHANNEL:
528                                 if (_IOC_DIR(cmd) != _IOC_WRITE ||
529                                     usblp->dev->descriptor.idVendor != 0x03F0 ||
530                                     usblp->quirks & USBLP_QUIRK_BIDIR) {
531                                         retval = -EINVAL;
532                                         goto done;
533                                 }
534
535                                 err = usblp_hp_channel_change_request(usblp,
536                                         arg, &newChannel);
537                                 if (err < 0) {
538                                         err("usblp%d: error = %d setting "
539                                                 "HP channel",
540                                                 usblp->minor, err);
541                                         retval = -EIO;
542                                         goto done;
543                                 }
544
545                                 dbg("usblp%d requested/got HP channel %ld/%d",
546                                         usblp->minor, arg, newChannel);
547                                 break;
548
549                         case IOCNR_GET_BUS_ADDRESS:
550                                 if (_IOC_DIR(cmd) != _IOC_READ ||
551                                     _IOC_SIZE(cmd) < sizeof(twoints)) {
552                                         retval = -EINVAL;
553                                         goto done;
554                                 }
555
556                                 twoints[0] = usblp->dev->bus->busnum;
557                                 twoints[1] = usblp->dev->devnum;
558                                 if (copy_to_user((void __user *)arg,
559                                                 (unsigned char *)twoints,
560                                                 sizeof(twoints))) {
561                                         retval = -EFAULT;
562                                         goto done;
563                                 }
564
565                                 dbg("usblp%d is bus=%d, device=%d",
566                                         usblp->minor, twoints[0], twoints[1]);
567                                 break;
568
569                         case IOCNR_GET_VID_PID:
570                                 if (_IOC_DIR(cmd) != _IOC_READ ||
571                                     _IOC_SIZE(cmd) < sizeof(twoints)) {
572                                         retval = -EINVAL;
573                                         goto done;
574                                 }
575
576                                 twoints[0] = usblp->dev->descriptor.idVendor;
577                                 twoints[1] = usblp->dev->descriptor.idProduct;
578                                 if (copy_to_user((void __user *)arg,
579                                                 (unsigned char *)twoints,
580                                                 sizeof(twoints))) {
581                                         retval = -EFAULT;
582                                         goto done;
583                                 }
584
585                                 dbg("usblp%d is VID=0x%4.4X, PID=0x%4.4X",
586                                         usblp->minor, twoints[0], twoints[1]);
587                                 break;
588
589                         case IOCNR_SOFT_RESET:
590                                 if (_IOC_DIR(cmd) != _IOC_NONE) {
591                                         retval = -EINVAL;
592                                         goto done;
593                                 }
594                                 retval = usblp_reset(usblp);
595                                 break;
596                         default:
597                                 retval = -ENOTTY;
598                 }
599         else    /* old-style ioctl value */
600                 switch (cmd) {
601
602                         case LPGETSTATUS:
603                                 if (usblp_read_status(usblp, usblp->statusbuf)) {
604                                         err("usblp%d: failed reading printer status", usblp->minor);
605                                         retval = -EIO;
606                                         goto done;
607                                 }
608                                 status = *usblp->statusbuf;
609                                 if (copy_to_user ((void __user *)arg, &status, sizeof(int)))
610                                         retval = -EFAULT;
611                                 break;
612
613                         default:
614                                 retval = -ENOTTY;
615                 }
616
617 done:
618         up (&usblp->sem);
619         return retval;
620 }
621
622 static ssize_t usblp_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos)
623 {
624         DECLARE_WAITQUEUE(wait, current);
625         struct usblp *usblp = file->private_data;
626         int timeout, err = 0, transfer_length = 0;
627         size_t writecount = 0;
628
629         while (writecount < count) {
630                 if (!usblp->wcomplete) {
631                         barrier();
632                         if (file->f_flags & O_NONBLOCK) {
633                                 writecount += transfer_length;
634                                 return writecount ? writecount : -EAGAIN;
635                         }
636
637                         timeout = USBLP_WRITE_TIMEOUT;
638                         add_wait_queue(&usblp->wait, &wait);
639                         while ( 1==1 ) {
640
641                                 if (signal_pending(current)) {
642                                         remove_wait_queue(&usblp->wait, &wait);
643                                         return writecount ? writecount : -EINTR;
644                                 }
645                                 set_current_state(TASK_INTERRUPTIBLE);
646                                 if (timeout && !usblp->wcomplete) {
647                                         timeout = schedule_timeout(timeout);
648                                 } else {
649                                         set_current_state(TASK_RUNNING);
650                                         break;
651                                 }
652                         }
653                         remove_wait_queue(&usblp->wait, &wait);
654                 }
655
656                 down (&usblp->sem);
657                 if (!usblp->present) {
658                         up (&usblp->sem);
659                         return -ENODEV;
660                 }
661
662                 if (usblp->writeurb->status != 0) {
663                         if (usblp->quirks & USBLP_QUIRK_BIDIR) {
664                                 if (!usblp->wcomplete)
665                                         err("usblp%d: error %d writing to printer",
666                                                 usblp->minor, usblp->writeurb->status);
667                                 err = usblp->writeurb->status;
668                         } else
669                                 err = usblp_check_status(usblp, err);
670                         up (&usblp->sem);
671
672                         /* if the fault was due to disconnect, let khubd's
673                          * call to usblp_disconnect() grab usblp->sem ...
674                          */
675                         schedule ();
676                         continue;
677                 }
678
679                 /* We must increment writecount here, and not at the
680                  * end of the loop. Otherwise, the final loop iteration may
681                  * be skipped, leading to incomplete printer output.
682                  */
683                 writecount += transfer_length;
684                 if (writecount == count) {
685                         up(&usblp->sem);
686                         break;
687                 }
688
689                 transfer_length=(count - writecount);
690                 if (transfer_length > USBLP_BUF_SIZE)
691                         transfer_length = USBLP_BUF_SIZE;
692
693                 usblp->writeurb->transfer_buffer_length = transfer_length;
694
695                 if (copy_from_user(usblp->writeurb->transfer_buffer, 
696                                    buffer + writecount, transfer_length)) {
697                         up(&usblp->sem);
698                         return writecount ? writecount : -EFAULT;
699                 }
700
701                 usblp->writeurb->dev = usblp->dev;
702                 usblp->wcomplete = 0;
703                 err = usb_submit_urb(usblp->writeurb, GFP_KERNEL);
704                 if (err) {
705                         if (err != -ENOMEM)
706                                 count = -EIO;
707                         else
708                                 count = writecount ? writecount : -ENOMEM;
709                         up (&usblp->sem);
710                         break;
711                 }
712                 up (&usblp->sem);
713         }
714
715         return count;
716 }
717
718 static ssize_t usblp_read(struct file *file, char __user *buffer, size_t count, loff_t *ppos)
719 {
720         struct usblp *usblp = file->private_data;
721         DECLARE_WAITQUEUE(wait, current);
722
723         if (!usblp->bidir)
724                 return -EINVAL;
725
726         down (&usblp->sem);
727         if (!usblp->present) {
728                 count = -ENODEV;
729                 goto done;
730         }
731
732         if (!usblp->rcomplete) {
733                 barrier();
734
735                 if (file->f_flags & O_NONBLOCK) {
736                         count = -EAGAIN;
737                         goto done;
738                 }
739
740                 add_wait_queue(&usblp->wait, &wait);
741                 while (1==1) {
742                         if (signal_pending(current)) {
743                                 count = -EINTR;
744                                 remove_wait_queue(&usblp->wait, &wait);
745                                 goto done;
746                         }
747                         up (&usblp->sem);
748                         set_current_state(TASK_INTERRUPTIBLE);
749                         if (!usblp->rcomplete) {
750                                 schedule();
751                         } else {
752                                 set_current_state(TASK_RUNNING);
753                                 break;
754                         }
755                         down (&usblp->sem);
756                 }
757                 remove_wait_queue(&usblp->wait, &wait);
758         }
759
760         if (!usblp->present) {
761                 count = -ENODEV;
762                 goto done;
763         }
764
765         if (usblp->readurb->status) {
766                 err("usblp%d: error %d reading from printer",
767                         usblp->minor, usblp->readurb->status);
768                 usblp->readurb->dev = usblp->dev;
769                 usblp->readcount = 0;
770                 usblp->rcomplete = 0;
771                 if (usb_submit_urb(usblp->readurb, GFP_KERNEL) < 0)
772                         dbg("error submitting urb");
773                 count = -EIO;
774                 goto done;
775         }
776
777         count = count < usblp->readurb->actual_length - usblp->readcount ?
778                 count : usblp->readurb->actual_length - usblp->readcount;
779
780         if (copy_to_user(buffer, usblp->readurb->transfer_buffer + usblp->readcount, count)) {
781                 count = -EFAULT;
782                 goto done;
783         }
784
785         if ((usblp->readcount += count) == usblp->readurb->actual_length) {
786                 usblp->readcount = 0;
787                 usblp->readurb->dev = usblp->dev;
788                 usblp->rcomplete = 0;
789                 if (usb_submit_urb(usblp->readurb, GFP_KERNEL)) {
790                         count = -EIO;
791                         goto done;
792                 }
793         }
794
795 done:
796         up (&usblp->sem);
797         return count;
798 }
799
800 /*
801  * Checks for printers that have quirks, such as requiring unidirectional
802  * communication but reporting bidirectional; currently some HP printers
803  * have this flaw (HP 810, 880, 895, etc.), or needing an init string
804  * sent at each open (like some Epsons).
805  * Returns 1 if found, 0 if not found.
806  *
807  * HP recommended that we use the bidirectional interface but
808  * don't attempt any bulk IN transfers from the IN endpoint.
809  * Here's some more detail on the problem:
810  * The problem is not that it isn't bidirectional though. The problem
811  * is that if you request a device ID, or status information, while
812  * the buffers are full, the return data will end up in the print data
813  * buffer. For example if you make sure you never request the device ID
814  * while you are sending print data, and you don't try to query the
815  * printer status every couple of milliseconds, you will probably be OK.
816  */
817 static unsigned int usblp_quirks (__u16 vendor, __u16 product)
818 {
819         int i;
820
821         for (i = 0; quirk_printers[i].vendorId; i++) {
822                 if (vendor == quirk_printers[i].vendorId &&
823                     product == quirk_printers[i].productId)
824                         return quirk_printers[i].quirks;
825         }
826         return 0;
827 }
828
829 static struct file_operations usblp_fops = {
830         .owner =        THIS_MODULE,
831         .read =         usblp_read,
832         .write =        usblp_write,
833         .poll =         usblp_poll,
834         .ioctl =        usblp_ioctl,
835         .open =         usblp_open,
836         .release =      usblp_release,
837 };
838
839 static struct usb_class_driver usblp_class = {
840         .name =         "usb/lp%d",
841         .fops =         &usblp_fops,
842         .mode =         S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP,
843         .minor_base =   USBLP_MINOR_BASE,
844 };
845
846 static int usblp_probe(struct usb_interface *intf,
847                        const struct usb_device_id *id)
848 {
849         struct usb_device *dev = interface_to_usbdev (intf);
850         struct usblp *usblp = NULL;
851         int protocol;
852         int retval;
853
854         /* Malloc and start initializing usblp structure so we can use it
855          * directly. */
856         if (!(usblp = kmalloc(sizeof(struct usblp), GFP_KERNEL))) {
857                 err("out of memory for usblp");
858                 goto abort;
859         }
860         memset(usblp, 0, sizeof(struct usblp));
861         usblp->dev = dev;
862         init_MUTEX (&usblp->sem);
863         init_waitqueue_head(&usblp->wait);
864         usblp->ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
865         usblp->intf = intf;
866
867         usblp->writeurb = usb_alloc_urb(0, GFP_KERNEL);
868         if (!usblp->writeurb) {
869                 err("out of memory");
870                 goto abort;
871         }
872         usblp->readurb = usb_alloc_urb(0, GFP_KERNEL);
873         if (!usblp->readurb) {
874                 err("out of memory");
875                 goto abort;
876         }
877
878         /* Malloc device ID string buffer to the largest expected length,
879          * since we can re-query it on an ioctl and a dynamic string
880          * could change in length. */
881         if (!(usblp->device_id_string = kmalloc(USBLP_DEVICE_ID_SIZE, GFP_KERNEL))) {
882                 err("out of memory for device_id_string");
883                 goto abort;
884         }
885
886         usblp->writebuf = usblp->readbuf = NULL;
887         usblp->writeurb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
888         usblp->readurb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
889         /* Malloc write & read buffers.  We somewhat wastefully
890          * malloc both regardless of bidirectionality, because the
891          * alternate setting can be changed later via an ioctl. */
892         if (!(usblp->writebuf = usb_buffer_alloc(dev, USBLP_BUF_SIZE,
893                                 GFP_KERNEL, &usblp->writeurb->transfer_dma))) {
894                 err("out of memory for write buf");
895                 goto abort;
896         }
897         if (!(usblp->readbuf = usb_buffer_alloc(dev, USBLP_BUF_SIZE,
898                                 GFP_KERNEL, &usblp->readurb->transfer_dma))) {
899                 err("out of memory for read buf");
900                 goto abort;
901         }
902
903         /* Allocate buffer for printer status */
904         usblp->statusbuf = kmalloc(STATUS_BUF_SIZE, GFP_KERNEL);
905         if (!usblp->statusbuf) {
906                 err("out of memory for statusbuf");
907                 goto abort;
908         }
909
910         /* Lookup quirks for this printer. */
911         usblp->quirks = usblp_quirks(
912                 dev->descriptor.idVendor,
913                 dev->descriptor.idProduct);
914
915         /* Analyze and pick initial alternate settings and endpoints. */
916         protocol = usblp_select_alts(usblp);
917         if (protocol < 0) {
918                 dbg("incompatible printer-class device 0x%4.4X/0x%4.4X",
919                         dev->descriptor.idVendor,
920                         dev->descriptor.idProduct);
921                 goto abort;
922         }
923
924         /* Setup the selected alternate setting and endpoints. */
925         if (usblp_set_protocol(usblp, protocol) < 0)
926                 goto abort;
927
928         /* Retrieve and store the device ID string. */
929         usblp_cache_device_id_string(usblp);
930
931 #ifdef DEBUG
932         usblp_check_status(usblp, 0);
933 #endif
934
935         info("usblp%d: USB %sdirectional printer dev %d "
936                 "if %d alt %d proto %d vid 0x%4.4X pid 0x%4.4X",
937                 usblp->minor, usblp->bidir ? "Bi" : "Uni", dev->devnum,
938                 usblp->ifnum,
939                 usblp->protocol[usblp->current_protocol].alt_setting,
940                 usblp->current_protocol, usblp->dev->descriptor.idVendor,
941                 usblp->dev->descriptor.idProduct);
942
943         usb_set_intfdata (intf, usblp);
944
945         usblp->present = 1;
946
947         retval = usb_register_dev(intf, &usblp_class);
948         if (retval) {
949                 err("Not able to get a minor for this device.");
950                 goto abort_intfdata;
951         }
952         usblp->minor = intf->minor;
953
954         return 0;
955
956 abort_intfdata:
957         usb_set_intfdata (intf, NULL);
958 abort:
959         if (usblp) {
960                 if (usblp->writebuf)
961                         usb_buffer_free (usblp->dev, USBLP_BUF_SIZE,
962                                 usblp->writebuf, usblp->writeurb->transfer_dma);
963                 if (usblp->readbuf)
964                         usb_buffer_free (usblp->dev, USBLP_BUF_SIZE,
965                                 usblp->readbuf, usblp->writeurb->transfer_dma);
966                 kfree(usblp->statusbuf);
967                 kfree(usblp->device_id_string);
968                 usb_free_urb(usblp->writeurb);
969                 usb_free_urb(usblp->readurb);
970                 kfree(usblp);
971         }
972         return -EIO;
973 }
974
975 /*
976  * We are a "new" style driver with usb_device_id table,
977  * but our requirements are too intricate for simple match to handle.
978  *
979  * The "proto_bias" option may be used to specify the preferred protocol
980  * for all USB printers (1=7/1/1, 2=7/1/2, 3=7/1/3).  If the device
981  * supports the preferred protocol, then we bind to it.
982  *
983  * The best interface for us is 7/1/2, because it is compatible
984  * with a stream of characters. If we find it, we bind to it.
985  *
986  * Note that the people from hpoj.sourceforge.net need to be able to
987  * bind to 7/1/3 (MLC/1284.4), so we provide them ioctls for this purpose.
988  *
989  * Failing 7/1/2, we look for 7/1/3, even though it's probably not
990  * stream-compatible, because this matches the behaviour of the old code.
991  *
992  * If nothing else, we bind to 7/1/1 - the unidirectional interface.
993  */
994 static int usblp_select_alts(struct usblp *usblp)
995 {
996         struct usb_interface *if_alt;
997         struct usb_host_interface *ifd;
998         struct usb_endpoint_descriptor *epd, *epwrite, *epread;
999         int p, i, e;
1000
1001         if_alt = usblp->intf;
1002
1003         for (p = 0; p < USBLP_MAX_PROTOCOLS; p++)
1004                 usblp->protocol[p].alt_setting = -1;
1005
1006         /* Find out what we have. */
1007         for (i = 0; i < if_alt->num_altsetting; i++) {
1008                 ifd = &if_alt->altsetting[i];
1009
1010                 if (ifd->desc.bInterfaceClass != 7 || ifd->desc.bInterfaceSubClass != 1)
1011                         continue;
1012
1013                 if (ifd->desc.bInterfaceProtocol < USBLP_FIRST_PROTOCOL ||
1014                     ifd->desc.bInterfaceProtocol > USBLP_LAST_PROTOCOL)
1015                         continue;
1016
1017                 /* Look for bulk OUT and IN endpoints. */
1018                 epwrite = epread = NULL;
1019                 for (e = 0; e < ifd->desc.bNumEndpoints; e++) {
1020                         epd = &ifd->endpoint[e].desc;
1021
1022                         if ((epd->bmAttributes&USB_ENDPOINT_XFERTYPE_MASK)!=
1023                             USB_ENDPOINT_XFER_BULK)
1024                                 continue;
1025
1026                         if (!(epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK)) {
1027                                 if (!epwrite)
1028                                         epwrite = epd;
1029
1030                         } else {
1031                                 if (!epread)
1032                                         epread = epd;
1033                         }
1034                 }
1035
1036                 /* Ignore buggy hardware without the right endpoints. */
1037                 if (!epwrite || (ifd->desc.bInterfaceProtocol > 1 && !epread))
1038                         continue;
1039
1040                 /* Turn off reads for 7/1/1 (unidirectional) interfaces
1041                  * and buggy bidirectional printers. */
1042                 if (ifd->desc.bInterfaceProtocol == 1) {
1043                         epread = NULL;
1044                 } else if (usblp->quirks & USBLP_QUIRK_BIDIR) {
1045                         info("Disabling reads from problem bidirectional "
1046                                 "printer on usblp%d", usblp->minor);
1047                         epread = NULL;
1048                 }
1049
1050                 usblp->protocol[ifd->desc.bInterfaceProtocol].alt_setting =
1051                                 ifd->desc.bAlternateSetting;
1052                 usblp->protocol[ifd->desc.bInterfaceProtocol].epwrite = epwrite;
1053                 usblp->protocol[ifd->desc.bInterfaceProtocol].epread = epread;
1054         }
1055
1056         /* If our requested protocol is supported, then use it. */
1057         if (proto_bias >= USBLP_FIRST_PROTOCOL &&
1058             proto_bias <= USBLP_LAST_PROTOCOL &&
1059             usblp->protocol[proto_bias].alt_setting != -1)
1060                 return proto_bias;
1061
1062         /* Ordering is important here. */
1063         if (usblp->protocol[2].alt_setting != -1)
1064                 return 2;
1065         if (usblp->protocol[1].alt_setting != -1)
1066                 return 1;
1067         if (usblp->protocol[3].alt_setting != -1)
1068                 return 3;
1069
1070         /* If nothing is available, then don't bind to this device. */
1071         return -1;
1072 }
1073
1074 static int usblp_set_protocol(struct usblp *usblp, int protocol)
1075 {
1076         int r, alts;
1077
1078         if (protocol < USBLP_FIRST_PROTOCOL || protocol > USBLP_LAST_PROTOCOL)
1079                 return -EINVAL;
1080
1081         alts = usblp->protocol[protocol].alt_setting;
1082         if (alts < 0)
1083                 return -EINVAL;
1084         r = usb_set_interface(usblp->dev, usblp->ifnum, alts);
1085         if (r < 0) {
1086                 err("can't set desired altsetting %d on interface %d",
1087                         alts, usblp->ifnum);
1088                 return r;
1089         }
1090
1091         usb_fill_bulk_urb(usblp->writeurb, usblp->dev,
1092                 usb_sndbulkpipe(usblp->dev,
1093                   usblp->protocol[protocol].epwrite->bEndpointAddress),
1094                 usblp->writebuf, 0,
1095                 usblp_bulk_write, usblp);
1096
1097         usblp->bidir = (usblp->protocol[protocol].epread != 0);
1098         if (usblp->bidir)
1099                 usb_fill_bulk_urb(usblp->readurb, usblp->dev,
1100                         usb_rcvbulkpipe(usblp->dev,
1101                           usblp->protocol[protocol].epread->bEndpointAddress),
1102                         usblp->readbuf, USBLP_BUF_SIZE,
1103                         usblp_bulk_read, usblp);
1104
1105         usblp->current_protocol = protocol;
1106         dbg("usblp%d set protocol %d", usblp->minor, protocol);
1107         return 0;
1108 }
1109
1110 /* Retrieves and caches device ID string.
1111  * Returns length, including length bytes but not null terminator.
1112  * On error, returns a negative errno value. */
1113 static int usblp_cache_device_id_string(struct usblp *usblp)
1114 {
1115         int err, length;
1116
1117         err = usblp_get_id(usblp, 0, usblp->device_id_string, USBLP_DEVICE_ID_SIZE - 1);
1118         if (err < 0) {
1119                 dbg("usblp%d: error = %d reading IEEE-1284 Device ID string",
1120                         usblp->minor, err);
1121                 usblp->device_id_string[0] = usblp->device_id_string[1] = '\0';
1122                 return -EIO;
1123         }
1124
1125         /* First two bytes are length in big-endian.
1126          * They count themselves, and we copy them into
1127          * the user's buffer. */
1128         length = be16_to_cpu(*((__be16 *)usblp->device_id_string));
1129         if (length < 2)
1130                 length = 2;
1131         else if (length >= USBLP_DEVICE_ID_SIZE)
1132                 length = USBLP_DEVICE_ID_SIZE - 1;
1133         usblp->device_id_string[length] = '\0';
1134
1135         dbg("usblp%d Device ID string [len=%d]=\"%s\"",
1136                 usblp->minor, length, &usblp->device_id_string[2]);
1137
1138         return length;
1139 }
1140
1141 static void usblp_disconnect(struct usb_interface *intf)
1142 {
1143         struct usblp *usblp = usb_get_intfdata (intf);
1144
1145         usb_deregister_dev(intf, &usblp_class);
1146
1147         if (!usblp || !usblp->dev) {
1148                 err("bogus disconnect");
1149                 BUG ();
1150         }
1151
1152         down (&usblp->sem);
1153         lock_kernel();
1154         usblp->present = 0;
1155         usb_set_intfdata (intf, NULL);
1156
1157         usblp_unlink_urbs(usblp);
1158         usb_buffer_free (usblp->dev, USBLP_BUF_SIZE,
1159                         usblp->writebuf, usblp->writeurb->transfer_dma);
1160         usb_buffer_free (usblp->dev, USBLP_BUF_SIZE,
1161                         usblp->readbuf, usblp->readurb->transfer_dma);
1162
1163         if (!usblp->used)
1164                 usblp_cleanup (usblp);
1165         else    /* cleanup later, on release */
1166                 up (&usblp->sem);
1167         unlock_kernel();
1168 }
1169
1170 static struct usb_device_id usblp_ids [] = {
1171         { USB_DEVICE_INFO(7, 1, 1) },
1172         { USB_DEVICE_INFO(7, 1, 2) },
1173         { USB_DEVICE_INFO(7, 1, 3) },
1174         { USB_INTERFACE_INFO(7, 1, 1) },
1175         { USB_INTERFACE_INFO(7, 1, 2) },
1176         { USB_INTERFACE_INFO(7, 1, 3) },
1177         { }                                             /* Terminating entry */
1178 };
1179
1180 MODULE_DEVICE_TABLE (usb, usblp_ids);
1181
1182 static struct usb_driver usblp_driver = {
1183         .owner =        THIS_MODULE,
1184         .name =         "usblp",
1185         .probe =        usblp_probe,
1186         .disconnect =   usblp_disconnect,
1187         .id_table =     usblp_ids,
1188 };
1189
1190 static int __init usblp_init(void)
1191 {
1192         int retval;
1193         retval = usb_register(&usblp_driver);
1194         if (retval)
1195                 goto out;
1196         info(DRIVER_VERSION ": " DRIVER_DESC);
1197 out:
1198         return retval;
1199 }
1200
1201 static void __exit usblp_exit(void)
1202 {
1203         usb_deregister(&usblp_driver);
1204 }
1205
1206 module_init(usblp_init);
1207 module_exit(usblp_exit);
1208
1209 MODULE_AUTHOR( DRIVER_AUTHOR );
1210 MODULE_DESCRIPTION( DRIVER_DESC );
1211 module_param(proto_bias, int, S_IRUGO | S_IWUSR);
1212 MODULE_PARM_DESC(proto_bias, "Favourite protocol number");
1213 MODULE_LICENSE("GPL");