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