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