added mtd driver
[linux-2.4.git] / drivers / usb / printer.c
1 /*
2  * printer.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 #include <linux/devfs_fs_kernel.h>
58 #undef DEBUG
59 #include <linux/usb.h>
60
61 /*
62  * Version Information
63  */
64 #define DRIVER_VERSION "v0.13"
65 #define DRIVER_AUTHOR "Michael Gee, Pavel Machek, Vojtech Pavlik, Randy Dunlap, Pete Zaitcev, David Paschal"
66 #define DRIVER_DESC "USB Printer Device Class driver"
67
68 #define USBLP_BUF_SIZE          8192
69 #define USBLP_DEVICE_ID_SIZE    1024
70
71 /* ioctls: */
72 #define LPGETSTATUS             0x060b          /* same as in drivers/char/lp.c */
73 #define IOCNR_GET_DEVICE_ID             1
74 #define IOCNR_GET_PROTOCOLS             2
75 #define IOCNR_SET_PROTOCOL              3
76 #define IOCNR_HP_SET_CHANNEL            4
77 #define IOCNR_GET_BUS_ADDRESS           5
78 #define IOCNR_GET_VID_PID               6
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
95 /*
96  * A DEVICE_ID string may include the printer's serial number.
97  * It should end with a semi-colon (';').
98  * An example from an HP 970C DeskJet printer is (this is one long string,
99  * with the serial number changed):
100 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:                    ;
101  */
102
103 /*
104  * USB Printer Requests
105  */
106
107 #define USBLP_REQ_GET_ID                        0x00
108 #define USBLP_REQ_GET_STATUS                    0x01
109 #define USBLP_REQ_RESET                         0x02
110 #define USBLP_REQ_HP_CHANNEL_CHANGE_REQUEST     0x00    /* HP Vendor-specific */
111
112 #define USBLP_MINORS            16
113 #define USBLP_MINOR_BASE        0
114
115 #define USBLP_WRITE_TIMEOUT     (5*HZ)                  /* 5 seconds */
116
117 #define USBLP_FIRST_PROTOCOL    1
118 #define USBLP_LAST_PROTOCOL     3
119 #define USBLP_MAX_PROTOCOLS     (USBLP_LAST_PROTOCOL+1)
120
121 /*
122  * some arbitrary status buffer size;
123  * need a status buffer that is allocated via kmalloc(), not on stack
124  */
125 #define STATUS_BUF_SIZE         8
126
127 struct usblp {
128         struct usb_device       *dev;                   /* USB device */
129         devfs_handle_t          devfs;                  /* devfs device */
130         struct semaphore        sem;                    /* locks this struct, especially "dev" */
131         char                    *writebuf;              /* write transfer_buffer */
132         char                    *readbuf;               /* read transfer_buffer */
133         char                    *statusbuf;             /* status transfer_buffer */
134         struct urb              *readurb, *writeurb;    /* The urbs */
135         wait_queue_head_t       wait;                   /* Zzzzz ... */
136         int                     readcount;              /* Counter for reads */
137         int                     ifnum;                  /* Interface number */
138         /* Alternate-setting numbers and endpoints for each protocol
139          * (7/1/{index=1,2,3}) that the device supports: */
140         struct {
141                 int                             alt_setting;
142                 struct usb_endpoint_descriptor  *epwrite;
143                 struct usb_endpoint_descriptor  *epread;
144         }                       protocol[USBLP_MAX_PROTOCOLS];
145         int                     current_protocol;
146         int                     minor;                  /* minor number of device */
147         int                     wcomplete;              /* writing is completed */
148         int                     rcomplete;              /* reading is completed */
149         unsigned int            quirks;                 /* quirks flags */
150         unsigned char           used;                   /* True if open */
151         unsigned char           present;                /* True if not disconnected */
152         unsigned char           bidir;                  /* interface is bidirectional */
153         unsigned char           *device_id_string;      /* IEEE 1284 DEVICE ID string (ptr) */
154                                                         /* first 2 bytes are (big-endian) length */
155 };
156
157 #ifdef DEBUG
158 static void usblp_dump(struct usblp *usblp) {
159         int p;
160
161         dbg("usblp=0x%p", usblp);
162         dbg("dev=0x%p", usblp->dev);
163         dbg("present=%d", usblp->present);
164         dbg("readbuf=0x%p", usblp->readbuf);
165         dbg("writebuf=0x%p", usblp->writebuf);
166         dbg("readurb=0x%p", usblp->readurb);
167         dbg("writeurb=0x%p", usblp->writeurb);
168         dbg("readcount=%d", usblp->readcount);
169         dbg("ifnum=%d", usblp->ifnum);
170     for (p = USBLP_FIRST_PROTOCOL; p <= USBLP_LAST_PROTOCOL; p++) {
171         dbg("protocol[%d].alt_setting=%d", p, usblp->protocol[p].alt_setting);
172         dbg("protocol[%d].epwrite=%p", p, usblp->protocol[p].epwrite);
173         dbg("protocol[%d].epread=%p", p, usblp->protocol[p].epread);
174     }
175         dbg("current_protocol=%d", usblp->current_protocol);
176         dbg("minor=%d", usblp->minor);
177         dbg("wcomplete=%d", usblp->wcomplete);
178         dbg("rcomplete=%d", usblp->rcomplete);
179         dbg("quirks=%d", usblp->quirks);
180         dbg("used=%d", usblp->used);
181         dbg("bidir=%d", usblp->bidir);
182         dbg("device_id_string=\"%s\"",
183                 usblp->device_id_string ?
184                         usblp->device_id_string + 2 :
185                         (unsigned char *)"(null)");
186 }
187 #endif
188
189 extern devfs_handle_t usb_devfs_handle;                 /* /dev/usb dir. */
190
191 static struct usblp *usblp_table[USBLP_MINORS];
192
193 /* Quirks: various printer quirks are handled by this table & its flags. */
194
195 struct quirk_printer_struct {
196         __u16 vendorId;
197         __u16 productId;
198         unsigned int quirks;
199 };
200
201 #define USBLP_QUIRK_BIDIR       0x1     /* reports bidir but requires unidirectional mode (no INs/reads) */
202 #define USBLP_QUIRK_USB_INIT    0x2     /* needs vendor USB init string */
203
204 static struct quirk_printer_struct quirk_printers[] = {
205         { 0x03f0, 0x0004, USBLP_QUIRK_BIDIR }, /* HP DeskJet 895C */
206         { 0x03f0, 0x0104, USBLP_QUIRK_BIDIR }, /* HP DeskJet 880C */
207         { 0x03f0, 0x0204, USBLP_QUIRK_BIDIR }, /* HP DeskJet 815C */
208         { 0x03f0, 0x0304, USBLP_QUIRK_BIDIR }, /* HP DeskJet 810C/812C */
209         { 0x03f0, 0x0404, USBLP_QUIRK_BIDIR }, /* HP DeskJet 830C */
210         { 0x03f0, 0x0504, USBLP_QUIRK_BIDIR }, /* HP DeskJet 885C */
211         { 0x03f0, 0x0604, USBLP_QUIRK_BIDIR }, /* HP DeskJet 840C */   
212         { 0x03f0, 0x0804, USBLP_QUIRK_BIDIR }, /* HP DeskJet 816C */   
213         { 0x03f0, 0x1104, USBLP_QUIRK_BIDIR }, /* HP Deskjet 959C */
214         { 0x0409, 0xefbe, USBLP_QUIRK_BIDIR }, /* NEC Picty900 (HP OEM) */
215         { 0x0409, 0xbef4, USBLP_QUIRK_BIDIR }, /* NEC Picty760 (HP OEM) */
216         { 0x0409, 0xf0be, USBLP_QUIRK_BIDIR }, /* NEC Picty920 (HP OEM) */
217         { 0x0409, 0xf1be, USBLP_QUIRK_BIDIR }, /* NEC Picty800 (HP OEM) */
218         { 0, 0 }
219 };
220
221 static int usblp_select_alts(struct usblp *usblp);
222 static int usblp_set_protocol(struct usblp *usblp, int protocol);
223 static int usblp_cache_device_id_string(struct usblp *usblp);
224
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)
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)
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 = MINOR(inode->i_rdev) - USBLP_MINOR_BASE;
340         struct usblp *usblp;
341         int retval;
342
343         if (minor < 0 || minor >= USBLP_MINORS)
344                 return -ENODEV;
345
346         down (&usblp_sem);
347         usblp  = usblp_table[minor];
348
349         retval = -ENODEV;
350         if (!usblp || !usblp->dev || !usblp->present)
351                 goto out;
352
353         retval = -EBUSY;
354         if (usblp->used)
355                 goto out;
356
357         /*
358          * TODO: need to implement LP_ABORTOPEN + O_NONBLOCK as in drivers/char/lp.c ???
359          * This is #if 0-ed because we *don't* want to fail an open
360          * just because the printer is off-line.
361          */
362 #if 0
363         if ((retval = usblp_check_status(usblp, 0))) {
364                 retval = retval > 1 ? -EIO : -ENOSPC;
365                 goto out;
366         }
367 #else
368         retval = 0;
369 #endif
370
371         usblp->used = 1;
372         file->private_data = usblp;
373
374         usblp->writeurb->transfer_buffer_length = 0;
375         usblp->wcomplete = 1; /* we begin writeable */
376         usblp->rcomplete = 0;
377
378         if (usblp->bidir) {
379                 usblp->readcount = 0;
380                 usblp->readurb->dev = usblp->dev;
381                 if (usb_submit_urb(usblp->readurb) < 0) {
382                         retval = -EIO;
383                         usblp->used = 0;
384                         file->private_data = NULL;
385                 }
386         }
387 out:
388         up (&usblp_sem);
389         return retval;
390 }
391
392 static void usblp_cleanup (struct usblp *usblp)
393 {
394         devfs_unregister (usblp->devfs);
395         usblp_table [usblp->minor] = NULL;
396         info("usblp%d: removed", usblp->minor);
397
398         kfree (usblp->writebuf);
399         kfree (usblp->readbuf);
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         } else          /* finish cleanup from disconnect */
423                 usblp_cleanup (usblp);
424         up (&usblp_sem);
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         if (_IOC_TYPE(cmd) == 'P')      /* new-style ioctl number */
453
454                 switch (_IOC_NR(cmd)) {
455
456                         case IOCNR_GET_DEVICE_ID: /* get the DEVICE_ID string */
457                                 if (_IOC_DIR(cmd) != _IOC_READ) {
458                                         retval = -EINVAL;
459                                         goto done;
460                                 }
461
462                                 length = usblp_cache_device_id_string(usblp);
463                                 if (length < 0) {
464                                         retval = length;
465                                         goto done;
466                                 }
467                                 if (length > _IOC_SIZE(cmd))
468                                         length = _IOC_SIZE(cmd); /* truncate */
469
470                                 if (copy_to_user((unsigned char *) arg,
471                                                 usblp->device_id_string,
472                                                 (unsigned long) length)) {
473                                         retval = -EFAULT;
474                                         goto done;
475                                 }
476
477                                 break;
478
479                         case IOCNR_GET_PROTOCOLS:
480                                 if (_IOC_DIR(cmd) != _IOC_READ ||
481                                     _IOC_SIZE(cmd) < sizeof(twoints)) {
482                                         retval = -EINVAL;
483                                         goto done;
484                                 }
485
486                                 twoints[0] = usblp->current_protocol;
487                                 twoints[1] = 0;
488                                 for (i = USBLP_FIRST_PROTOCOL;
489                                      i <= USBLP_LAST_PROTOCOL; i++) {
490                                         if (usblp->protocol[i].alt_setting >= 0)
491                                                 twoints[1] |= (1<<i);
492                                 }
493
494                                 if (copy_to_user((unsigned char *)arg,
495                                                 (unsigned char *)twoints,
496                                                 sizeof(twoints))) {
497                                         retval = -EFAULT;
498                                         goto done;
499                                 }
500
501                                 break;
502
503                         case IOCNR_SET_PROTOCOL:
504                                 if (_IOC_DIR(cmd) != _IOC_WRITE) {
505                                         retval = -EINVAL;
506                                         goto done;
507                                 }
508
509 #ifdef DEBUG
510                                 if (arg == -10) {
511                                         usblp_dump(usblp);
512                                         break;
513                                 }
514 #endif
515
516                                 usblp_unlink_urbs(usblp);
517                                 retval = usblp_set_protocol(usblp, arg);
518                                 if (retval < 0) {
519                                         usblp_set_protocol(usblp,
520                                                 usblp->current_protocol);
521                                 }
522                                 break;
523
524                         case IOCNR_HP_SET_CHANNEL:
525                                 if (_IOC_DIR(cmd) != _IOC_WRITE ||
526                                     usblp->dev->descriptor.idVendor != 0x03F0 ||
527                                     usblp->quirks & USBLP_QUIRK_BIDIR) {
528                                         retval = -EINVAL;
529                                         goto done;
530                                 }
531
532                                 err = usblp_hp_channel_change_request(usblp,
533                                         arg, &newChannel);
534                                 if (err < 0) {
535                                         err("usblp%d: error = %d setting "
536                                                 "HP channel",
537                                                 usblp->minor, err);
538                                         retval = -EIO;
539                                         goto done;
540                                 }
541
542                                 dbg("usblp%d requested/got HP channel %ld/%d",
543                                         usblp->minor, arg, newChannel);
544                                 break;
545
546                         case IOCNR_GET_BUS_ADDRESS:
547                                 if (_IOC_DIR(cmd) != _IOC_READ ||
548                                     _IOC_SIZE(cmd) < sizeof(twoints)) {
549                                         retval = -EINVAL;
550                                         goto done;
551                                 }
552
553                                 twoints[0] = usblp->dev->bus->busnum;
554                                 twoints[1] = usblp->dev->devnum;
555                                 if (copy_to_user((unsigned char *)arg,
556                                                 (unsigned char *)twoints,
557                                                 sizeof(twoints))) {
558                                         retval = -EFAULT;
559                                         goto done;
560                                 }
561
562                                 dbg("usblp%d is bus=%d, device=%d",
563                                         usblp->minor, twoints[0], twoints[1]);
564                                 break;
565
566                         case IOCNR_GET_VID_PID:
567                                 if (_IOC_DIR(cmd) != _IOC_READ ||
568                                     _IOC_SIZE(cmd) < sizeof(twoints)) {
569                                         retval = -EINVAL;
570                                         goto done;
571                                 }
572
573                                 twoints[0] = usblp->dev->descriptor.idVendor;
574                                 twoints[1] = usblp->dev->descriptor.idProduct;
575                                 if (copy_to_user((unsigned char *)arg,
576                                                 (unsigned char *)twoints,
577                                                 sizeof(twoints))) {
578                                         retval = -EFAULT;
579                                         goto done;
580                                 }
581
582                                 dbg("usblp%d is VID=0x%4.4X, PID=0x%4.4X",
583                                         usblp->minor, twoints[0], twoints[1]);
584                                 break;
585
586                         default:
587                                 retval = -ENOTTY;
588                 }
589         else    /* old-style ioctl value */
590                 switch (cmd) {
591
592                         case LPGETSTATUS:
593                                 if (usblp_read_status(usblp, usblp->statusbuf)) {
594                                         err("usblp%d: failed reading printer status", usblp->minor);
595                                         retval = -EIO;
596                                         goto done;
597                                 }
598                                 status = *usblp->statusbuf;
599                                 if (copy_to_user ((int *)arg, &status, sizeof(int)))
600                                         retval = -EFAULT;
601                                 break;
602
603                         default:
604                                 retval = -ENOTTY;
605                 }
606
607 done:
608         up (&usblp->sem);
609         return retval;
610 }
611
612 static ssize_t usblp_write(struct file *file, const char *buffer, size_t count, loff_t *ppos)
613 {
614         DECLARE_WAITQUEUE(wait, current);
615         struct usblp *usblp = file->private_data;
616         int timeout, err = 0, transfer_length = 0;
617         size_t writecount = 0;
618
619         while (writecount < count) {
620                 if (!usblp->wcomplete) {
621                         barrier();
622                         if (file->f_flags & O_NONBLOCK) {
623                                 writecount += transfer_length;
624                                 return writecount ? writecount : -EAGAIN;
625                         }
626
627                         timeout = USBLP_WRITE_TIMEOUT;
628                         add_wait_queue(&usblp->wait, &wait);
629                         while ( 1==1 ) {
630
631                                 if (signal_pending(current)) {
632                                         remove_wait_queue(&usblp->wait, &wait);
633                                         return writecount ? writecount : -EINTR;
634                                 }
635                                 set_current_state(TASK_INTERRUPTIBLE);
636                                 if (timeout && !usblp->wcomplete) {
637                                         timeout = schedule_timeout(timeout);
638                                 } else {
639                                         set_current_state(TASK_RUNNING);
640                                         break;
641                                 }
642                         }
643                         remove_wait_queue(&usblp->wait, &wait);
644                 }
645
646                 down (&usblp->sem);
647                 if (!usblp->present) {
648                         up (&usblp->sem);
649                         return -ENODEV;
650                 }
651
652                 if (usblp->writeurb->status != 0) {
653                         if (usblp->quirks & USBLP_QUIRK_BIDIR) {
654                                 if (!usblp->wcomplete)
655                                         err("usblp%d: error %d writing to printer",
656                                                 usblp->minor, usblp->writeurb->status);
657                                 err = usblp->writeurb->status;
658                         } else
659                                 err = usblp_check_status(usblp, err);
660                         up (&usblp->sem);
661
662                         /* if the fault was due to disconnect, let khubd's
663                          * call to usblp_disconnect() grab usblp->sem ...
664                          */
665                         schedule ();
666                         continue;
667                 }
668
669                 /* We must increment writecount here, and not at the
670                  * end of the loop. Otherwise, the final loop iteration may
671                  * be skipped, leading to incomplete printer output.
672                  */
673                 writecount += transfer_length;
674                 if (writecount == count) {
675                         up (&usblp->sem);
676                         break;
677                 }
678
679                 transfer_length = count - writecount;
680                 if(transfer_length > USBLP_BUF_SIZE) 
681                         transfer_length = USBLP_BUF_SIZE;
682                 
683                 usblp->writeurb->transfer_buffer_length = transfer_length;
684
685                 if (copy_from_user(usblp->writeurb->transfer_buffer, 
686                                    buffer + writecount, transfer_length)) {
687                         up(&usblp->sem);
688                         return writecount ? writecount : -EFAULT;
689                 }
690
691                 usblp->writeurb->dev = usblp->dev;
692                 usblp->wcomplete = 0;
693                 err = usb_submit_urb(usblp->writeurb);
694                 if (err) {
695                         usblp->wcomplete = 1;
696                         if (err != -ENOMEM)
697                                 count = -EIO;
698                         else
699                                 count = writecount ? writecount : -ENOMEM;
700                         up (&usblp->sem);
701                         break;
702                 }
703                 up (&usblp->sem);
704         }
705
706         return count;
707 }
708
709 static ssize_t usblp_read(struct file *file, char *buffer, size_t count, loff_t *ppos)
710 {
711         struct usblp *usblp = file->private_data;
712         DECLARE_WAITQUEUE(wait, current);
713
714         if (!usblp->bidir)
715                 return -EINVAL;
716
717         down (&usblp->sem);
718         if (!usblp->present) {
719                 count = -ENODEV;
720                 goto done;
721         }
722
723         if (!usblp->rcomplete) {
724                 barrier();
725
726                 if (file->f_flags & O_NONBLOCK) {
727                         count = -EAGAIN;
728                         goto done;
729                 }
730
731                 add_wait_queue(&usblp->wait, &wait);
732                 while (1==1) {
733                         if (signal_pending(current)) {
734                                 count = -EINTR;
735                                 remove_wait_queue(&usblp->wait, &wait);
736                                 goto done;
737                         }
738                         up (&usblp->sem);
739                         set_current_state(TASK_INTERRUPTIBLE);
740                         if (!usblp->rcomplete) {
741                                 schedule();
742                         } else {
743                                 set_current_state(TASK_RUNNING);
744                                 down (&usblp->sem);
745                                 break;
746                         }
747                         down (&usblp->sem);
748                 }
749                 remove_wait_queue(&usblp->wait, &wait);
750         }
751
752         if (!usblp->present) {
753                 count = -ENODEV;
754                 goto done;
755         }
756
757         if (usblp->readurb->status) {
758                 err("usblp%d: error %d reading from printer",
759                         usblp->minor, usblp->readurb->status);
760                 usblp->readurb->dev = usblp->dev;
761                 usblp->readcount = 0;
762                 usblp->rcomplete = 0;
763                 if (usb_submit_urb(usblp->readurb) < 0)
764                         dbg("error submitting urb");
765                 count = -EIO;
766                 goto done;
767         }
768
769         count = count < usblp->readurb->actual_length - usblp->readcount ?
770                 count : usblp->readurb->actual_length - usblp->readcount;
771
772         if (copy_to_user(buffer, usblp->readurb->transfer_buffer + usblp->readcount, count)) {
773                 count = -EFAULT;
774                 goto done;
775         }
776
777         if ((usblp->readcount += count) == usblp->readurb->actual_length) {
778                 usblp->readcount = 0;
779                 usblp->readurb->dev = usblp->dev;
780                 usblp->rcomplete = 0;
781                 if (usb_submit_urb(usblp->readurb)) {
782                         count = -EIO;
783                         goto done;
784                 }
785         }
786
787 done:
788         up (&usblp->sem);
789         return count;
790 }
791
792 /*
793  * Checks for printers that have quirks, such as requiring unidirectional
794  * communication but reporting bidirectional; currently some HP printers
795  * have this flaw (HP 810, 880, 895, etc.), or needing an init string
796  * sent at each open (like some Epsons).
797  * Returns 1 if found, 0 if not found.
798  *
799  * HP recommended that we use the bidirectional interface but
800  * don't attempt any bulk IN transfers from the IN endpoint.
801  * Here's some more detail on the problem:
802  * The problem is not that it isn't bidirectional though. The problem
803  * is that if you request a device ID, or status information, while
804  * the buffers are full, the return data will end up in the print data
805  * buffer. For example if you make sure you never request the device ID
806  * while you are sending print data, and you don't try to query the
807  * printer status every couple of milliseconds, you will probably be OK.
808  */
809 static unsigned int usblp_quirks (__u16 vendor, __u16 product)
810 {
811         int i;
812
813         for (i = 0; quirk_printers[i].vendorId; i++) {
814                 if (vendor == quirk_printers[i].vendorId &&
815                     product == quirk_printers[i].productId)
816                         return quirk_printers[i].quirks;
817         }
818         return 0;
819 }
820
821 static struct file_operations usblp_fops = {
822         owner:          THIS_MODULE,
823         read:           usblp_read,
824         write:          usblp_write,
825         poll:           usblp_poll,
826         ioctl:          usblp_ioctl,
827         open:           usblp_open,
828         release:        usblp_release,
829 };
830
831 static void *usblp_probe(struct usb_device *dev, unsigned int ifnum,
832                          const struct usb_device_id *id)
833 {
834         struct usblp *usblp = 0;
835         int protocol;
836         char name[6];
837
838         /* Malloc and start initializing usblp structure so we can use it
839          * directly. */
840         if (!(usblp = kmalloc(sizeof(struct usblp), GFP_KERNEL))) {
841                 err("out of memory for usblp");
842                 goto abort;
843         }
844         memset(usblp, 0, sizeof(struct usblp));
845         usblp->dev = dev;
846         init_MUTEX (&usblp->sem);
847         init_waitqueue_head(&usblp->wait);
848         usblp->ifnum = ifnum;
849
850         /* Look for a free usblp_table entry. */
851         while (usblp_table[usblp->minor]) {
852                 usblp->minor++;
853                 if (usblp->minor >= USBLP_MINORS) {
854                         err("no more free usblp devices");
855                         goto abort;
856                 }
857         }
858
859         usblp->writeurb = usb_alloc_urb(0);
860         if (!usblp->writeurb) {
861                 err("out of memory");
862                 goto abort;
863         }
864         usblp->readurb = usb_alloc_urb(0);
865         if (!usblp->readurb) {
866                 err("out of memory");
867                 goto abort;
868         }
869
870         /* Malloc device ID string buffer to the largest expected length,
871          * since we can re-query it on an ioctl and a dynamic string
872          * could change in length. */
873         if (!(usblp->device_id_string = kmalloc(USBLP_DEVICE_ID_SIZE, GFP_KERNEL))) {
874                 err("out of memory for device_id_string");
875                 goto abort;
876         }
877
878         usblp->writebuf = usblp->readbuf = NULL;
879         /* Malloc write & read buffers.  We somewhat wastefully
880          * malloc both regardless of bidirectionality, because the
881          * alternate setting can be changed later via an ioctl. */
882         if (!(usblp->writebuf = kmalloc(USBLP_BUF_SIZE, GFP_KERNEL))) {
883                 err("out of memory for write buf");
884                 goto abort;
885         }
886         if (!(usblp->readbuf = kmalloc(USBLP_BUF_SIZE, GFP_KERNEL))) {
887                 err("out of memory for read buf");
888                 goto abort;
889         }
890
891         /* Allocate buffer for printer status */
892         usblp->statusbuf = kmalloc(STATUS_BUF_SIZE, GFP_KERNEL);
893         if (!usblp->statusbuf) {
894                 err("out of memory for statusbuf");
895                 goto abort;
896         }
897
898         /* Lookup quirks for this printer. */
899         usblp->quirks = usblp_quirks(
900                 dev->descriptor.idVendor,
901                 dev->descriptor.idProduct);
902
903         /* Analyze and pick initial alternate settings and endpoints. */
904         protocol = usblp_select_alts(usblp);
905         if (protocol < 0) {
906                 dbg("incompatible printer-class device 0x%4.4X/0x%4.4X",
907                         dev->descriptor.idVendor,
908                         dev->descriptor.idProduct);
909                 goto abort;
910         }
911
912         /* Setup the selected alternate setting and endpoints. */
913         if (usblp_set_protocol(usblp, protocol) < 0)
914                 goto abort;
915
916         /* Retrieve and store the device ID string. */
917         usblp_cache_device_id_string(usblp);
918
919 #ifdef DEBUG
920         usblp_check_status(usblp, 0);
921 #endif
922
923         usblp_table[usblp->minor] = usblp;
924         /* If we have devfs, create with perms=660. */
925         sprintf(name, "lp%d", usblp->minor);
926         usblp->devfs = devfs_register(usb_devfs_handle, name,
927                                       DEVFS_FL_DEFAULT, USB_MAJOR,
928                                       USBLP_MINOR_BASE + usblp->minor,
929                                       S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP |
930                                       S_IWGRP, &usblp_fops, NULL);
931
932         info("usblp%d: USB %sdirectional printer dev %d "
933                 "if %d alt %d proto %d vid 0x%4.4X pid 0x%4.4X",
934                 usblp->minor, usblp->bidir ? "Bi" : "Uni", dev->devnum,
935                 usblp->ifnum,
936                 usblp->protocol[usblp->current_protocol].alt_setting,
937                 usblp->current_protocol, usblp->dev->descriptor.idVendor,
938                 usblp->dev->descriptor.idProduct);
939
940         usblp->present = 1;
941
942         return usblp;
943
944 abort:
945         if (usblp) {
946                 if (usblp->writebuf)
947                         kfree (usblp->writebuf);
948                 if (usblp->readbuf)
949                         kfree (usblp->readbuf);
950                 kfree(usblp->statusbuf);
951                 kfree(usblp->device_id_string);
952                 usb_free_urb(usblp->writeurb);
953                 usb_free_urb(usblp->readurb);
954                 kfree(usblp);
955         }
956         return NULL;
957 }
958
959 /*
960  * We are a "new" style driver with usb_device_id table,
961  * but our requirements are too intricate for simple match to handle.
962  *
963  * The "proto_bias" option may be used to specify the preferred protocol
964  * for all USB printers (1=7/1/1, 2=7/1/2, 3=7/1/3).  If the device
965  * supports the preferred protocol, then we bind to it.
966  *
967  * The best interface for us is 7/1/2, because it is compatible
968  * with a stream of characters. If we find it, we bind to it.
969  *
970  * Note that the people from hpoj.sourceforge.net need to be able to
971  * bind to 7/1/3 (MLC/1284.4), so we provide them ioctls for this purpose.
972  *
973  * Failing 7/1/2, we look for 7/1/3, even though it's probably not
974  * stream-compatible, because this matches the behaviour of the old code.
975  *
976  * If nothing else, we bind to 7/1/1 - the unidirectional interface.
977  */
978 static int usblp_select_alts(struct usblp *usblp)
979 {
980         struct usb_interface *if_alt;
981         struct usb_interface_descriptor *ifd;
982         struct usb_endpoint_descriptor *epd, *epwrite, *epread;
983         int p, i, e;
984
985         if_alt = &usblp->dev->actconfig->interface[usblp->ifnum];
986
987         for (p = 0; p < USBLP_MAX_PROTOCOLS; p++)
988                 usblp->protocol[p].alt_setting = -1;
989
990         /* Find out what we have. */
991         for (i = 0; i < if_alt->num_altsetting; i++) {
992                 ifd = &if_alt->altsetting[i];
993
994                 if (ifd->bInterfaceClass != 7 || ifd->bInterfaceSubClass != 1)
995                         continue;
996
997                 if (ifd->bInterfaceProtocol < USBLP_FIRST_PROTOCOL ||
998                     ifd->bInterfaceProtocol > USBLP_LAST_PROTOCOL)
999                         continue;
1000
1001                 /* Look for bulk OUT and IN endpoints. */
1002                 epwrite = epread = 0;
1003                 for (e = 0; e < ifd->bNumEndpoints; e++) {
1004                         epd = &ifd->endpoint[e];
1005
1006                         if ((epd->bmAttributes&USB_ENDPOINT_XFERTYPE_MASK)!=
1007                             USB_ENDPOINT_XFER_BULK)
1008                                 continue;
1009
1010                         if (!(epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK)) {
1011                                 if (!epwrite) epwrite=epd;
1012
1013                         } else {
1014                                 if (!epread) epread=epd;
1015                         }
1016                 }
1017
1018                 /* Ignore buggy hardware without the right endpoints. */
1019                 if (!epwrite || (ifd->bInterfaceProtocol > 1 && !epread))
1020                         continue;
1021
1022                 /* Turn off reads for 7/1/1 (unidirectional) interfaces
1023                  * and buggy bidirectional printers. */
1024                 if (ifd->bInterfaceProtocol == 1) {
1025                         epread = NULL;
1026                 } else if (usblp->quirks & USBLP_QUIRK_BIDIR) {
1027                         info("Disabling reads from problem bidirectional "
1028                                 "printer on usblp%d", usblp->minor);
1029                         epread = NULL;
1030                 }
1031
1032                 usblp->protocol[ifd->bInterfaceProtocol].alt_setting = i;
1033                 usblp->protocol[ifd->bInterfaceProtocol].epwrite = epwrite;
1034                 usblp->protocol[ifd->bInterfaceProtocol].epread = epread;
1035         }
1036
1037         /* If our requested protocol is supported, then use it. */
1038         if (proto_bias >= USBLP_FIRST_PROTOCOL &&
1039             proto_bias <= USBLP_LAST_PROTOCOL &&
1040             usblp->protocol[proto_bias].alt_setting != -1)
1041                 return proto_bias;
1042
1043         /* Ordering is important here. */
1044         if (usblp->protocol[2].alt_setting != -1) return 2;
1045         if (usblp->protocol[1].alt_setting != -1) return 1;
1046         if (usblp->protocol[3].alt_setting != -1) return 3;
1047
1048         /* If nothing is available, then don't bind to this device. */
1049         return -1;
1050 }
1051
1052 static int usblp_set_protocol(struct usblp *usblp, int protocol)
1053 {
1054         int r, alts;
1055
1056         if (protocol < USBLP_FIRST_PROTOCOL || protocol > USBLP_LAST_PROTOCOL)
1057                 return -EINVAL;
1058
1059         alts = usblp->protocol[protocol].alt_setting;
1060         if (alts < 0) return -EINVAL;
1061         r = usb_set_interface(usblp->dev, usblp->ifnum, alts);
1062         if (r < 0) {
1063                 err("can't set desired altsetting %d on interface %d",
1064                         alts, usblp->ifnum);
1065                 return r;
1066         }
1067
1068         usb_fill_bulk_urb(usblp->writeurb, usblp->dev,
1069                 usb_sndbulkpipe(usblp->dev,
1070                   usblp->protocol[protocol].epwrite->bEndpointAddress),
1071                 usblp->writebuf, 0,
1072                 usblp_bulk_write, usblp);
1073
1074         usblp->bidir = (usblp->protocol[protocol].epread != 0);
1075         if (usblp->bidir)
1076                 usb_fill_bulk_urb(usblp->readurb, usblp->dev,
1077                         usb_rcvbulkpipe(usblp->dev,
1078                           usblp->protocol[protocol].epread->bEndpointAddress),
1079                         usblp->readbuf, USBLP_BUF_SIZE,
1080                         usblp_bulk_read, usblp);
1081
1082         usblp->current_protocol = protocol;
1083         dbg("usblp%d set protocol %d", usblp->minor, protocol);
1084         return 0;
1085 }
1086
1087 /* Retrieves and caches device ID string.
1088  * Returns length, including length bytes but not null terminator.
1089  * On error, returns a negative errno value. */
1090 static int usblp_cache_device_id_string(struct usblp *usblp)
1091 {
1092         int err, length;
1093
1094         err = usblp_get_id(usblp, 0, usblp->device_id_string, USBLP_DEVICE_ID_SIZE - 1);
1095         if (err < 0) {
1096                 dbg("usblp%d: error = %d reading IEEE-1284 Device ID string",
1097                         usblp->minor, err);
1098                 usblp->device_id_string[0] = usblp->device_id_string[1] = '\0';
1099                 return -EIO;
1100         }
1101
1102         /* First two bytes are length in big-endian.
1103          * They count themselves, and we copy them into
1104          * the user's buffer. */
1105         length = (usblp->device_id_string[0] << 8) + usblp->device_id_string[1];
1106         if (length < 2)
1107                 length = 2;
1108         else if (length >= USBLP_DEVICE_ID_SIZE)
1109                 length = USBLP_DEVICE_ID_SIZE - 1;
1110         usblp->device_id_string[length] = '\0';
1111
1112         dbg("usblp%d Device ID string [len=%d]=\"%s\"",
1113                 usblp->minor, length, &usblp->device_id_string[2]);
1114
1115         return length;
1116 }
1117
1118 static void usblp_disconnect(struct usb_device *dev, void *ptr)
1119 {
1120         struct usblp *usblp = ptr;
1121
1122         if (!usblp || !usblp->dev) {
1123                 err("bogus disconnect");
1124                 BUG ();
1125         }
1126
1127         down (&usblp_sem);
1128         down (&usblp->sem);
1129         usblp->present = 0;
1130
1131         usblp_unlink_urbs(usblp);
1132         up (&usblp->sem);
1133
1134         if (!usblp->used)
1135                 usblp_cleanup (usblp);
1136         up (&usblp_sem);
1137 }
1138
1139 static struct usb_device_id usblp_ids [] = {
1140         { USB_DEVICE_INFO(7, 1, 1) },
1141         { USB_DEVICE_INFO(7, 1, 2) },
1142         { USB_DEVICE_INFO(7, 1, 3) },
1143         { USB_INTERFACE_INFO(7, 1, 1) },
1144         { USB_INTERFACE_INFO(7, 1, 2) },
1145         { USB_INTERFACE_INFO(7, 1, 3) },
1146         { }                                             /* Terminating entry */
1147 };
1148
1149 MODULE_DEVICE_TABLE (usb, usblp_ids);
1150
1151 static struct usb_driver usblp_driver = {
1152         name:           "usblp",
1153         probe:          usblp_probe,
1154         disconnect:     usblp_disconnect,
1155         fops:           &usblp_fops,
1156         minor:          USBLP_MINOR_BASE,
1157         id_table:       usblp_ids,
1158 };
1159
1160 static int __init usblp_init(void)
1161 {
1162         if (usb_register(&usblp_driver))
1163                 return -1;
1164         info(DRIVER_VERSION ": " DRIVER_DESC);
1165         return 0;
1166 }
1167
1168 static void __exit usblp_exit(void)
1169 {
1170         usb_deregister(&usblp_driver);
1171 }
1172
1173 module_init(usblp_init);
1174 module_exit(usblp_exit);
1175
1176 MODULE_AUTHOR( DRIVER_AUTHOR );
1177 MODULE_DESCRIPTION( DRIVER_DESC );
1178 MODULE_PARM(proto_bias, "i");
1179 MODULE_PARM_DESC(proto_bias, "Favourite protocol number");
1180 MODULE_LICENSE("GPL");