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