File: /usr/src/linux/drivers/usb/scanner.c

1     /* -*- linux-c -*- */
2     
3     /* 
4      * Driver for USB Scanners (linux-2.4.0)
5      *
6      * Copyright (C) 1999, 2000 David E. Nelson
7      *
8      * Portions may be copyright Brad Keryan and Michael Gee.
9      *
10      * David E. Nelson (dnelson@jump.net)
11      * 
12      * This program is free software; you can redistribute it and/or
13      * modify it under the terms of the GNU General Public License as
14      * published by the Free Software Foundation; either version 2 of the
15      * License, or (at your option) any later version.
16      *
17      * This program is distributed in the hope that it will be useful, but
18      * WITHOUT ANY WARRANTY; without even the implied warranty of
19      * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20      * General Public License for more details.
21      *
22      * You should have received a copy of the GNU General Public License
23      * along with this program; if not, write to the Free Software
24      * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25      *
26      * Originally based upon mouse.c (Brad Keryan) and printer.c (Michael Gee).
27      *
28      * History
29      *
30      *  0.1  8/31/1999
31      *
32      *    Developed/tested using linux-2.3.15 with minor ohci.c changes to
33      *    support short packes during bulk xfer mode.  Some testing was
34      *    done with ohci-hcd but the performace was low.  Very limited
35      *    testing was performed with uhci but I was unable to get it to
36      *    work.  Initial relase to the linux-usb development effort.
37      *
38      *
39      *  0.2  10/16/1999
40      *
41      *    - Device can't be opened unless a scanner is plugged into the USB.
42      *    - Finally settled on a reasonable value for the I/O buffer's.
43      *    - Cleaned up write_scanner()
44      *    - Disabled read/write stats
45      *    - A little more code cleanup
46      *
47      *
48      *  0.3  10/18/1999
49      *
50      *    - Device registration changed to reflect new device
51      *      allocation/registration for linux-2.3.22+.
52      *    - Adopted David Brownell's <david-b@pacbell.net> technique for 
53      *      assigning bulk endpoints.
54      *    - Removed unnessesary #include's
55      *    - Scanner model now reported via syslog INFO after being detected 
56      *      *and* configured.
57      *    - Added user specified vendor:product USB ID's which can be passed 
58      *      as module parameters.
59      *
60      *
61      *  0.3.1
62      *
63      *    - Applied patches for linux-2.3.25.
64      *    - Error number reporting changed to reflect negative return codes.
65      *
66      *
67      *  0.3.2
68      *
69      *    - Applied patches for linux-2.3.26 to scanner_init().
70      *    - Debug read/write stats now report values as signed decimal.
71      *
72      *
73      *  0.3.3
74      *
75      *    - Updated the bulk_msg() calls to usb usb_bulk_msg().
76      *    - Added a small delay in the write_scanner() method to aid in
77      *      avoiding NULL data reads on HP scanners.  We'll see how this works.
78      *    - Return values from usb_bulk_msg() now ignore positive values for
79      *      use with the ohci driver.
80      *    - Added conditional debugging instead of commenting/uncommenting
81      *      all over the place.
82      *    - kfree()'d the pointer after using usb_string() as documented in
83      *      linux-usb-api.txt.
84      *    - Added usb_set_configuration().  It got lost in version 0.3 -- ack!
85      *    - Added the HP 5200C USB Vendor/Product ID's.
86      *
87      *
88      *  0.3.4  1/23/2000
89      *
90      *    - Added Greg K-H's <greg@kroah.com> patch for better handling of 
91      *      Product/Vendor detection.
92      *    - The driver now autoconfigures its endpoints including interrupt
93      *      endpoints if one is detected.  The concept was originally based
94      *      upon David Brownell's method.
95      *    - Added some Seiko/Epson ID's. Thanks to Karl Heinz 
96      *      Kremer <khk@khk.net>.
97      *    - Added some preliminary ioctl() calls for the PV8630 which is used
98      *      by the HP4200. The ioctl()'s still have to be registered. Thanks 
99      *      to Adrian Perez Jorge <adrianpj@easynews.com>.
100      *    - Moved/migrated stuff to scanner.h
101      *    - Removed the usb_set_configuration() since this is handled by
102      *      the usb_new_device() routine in usb.c.
103      *    - Added the HP 3300C.  Thanks to Bruce Tenison.
104      *    - Changed user specified vendor/product id so that root hub doesn't
105      *      get falsely attached to. Thanks to Greg K-H.
106      *    - Added some Mustek ID's. Thanks to Gernot Hoyler 
107      *      <Dr.Hoyler@t-online.de>.
108      *    - Modified the usb_string() reporting.  See kfree() comment above.
109      *    - Added Umax Astra 2000U. Thanks to Doug Alcorn <doug@lathi.net>.
110      *    - Updated the printk()'s to use the info/warn/dbg macros.
111      *    - Updated usb_bulk_msg() argument types to fix gcc warnings.
112      *
113      *
114      *  0.4  2/4/2000
115      *
116      *    - Removed usb_string() from probe_scanner since the core now does a
117      *      good job of reporting what was connnected.  
118      *    - Finally, simultaneous multiple device attachment!
119      *    - Fixed some potential memory freeing issues should memory allocation
120      *      fail in probe_scanner();
121      *    - Some fixes to disconnect_scanner().
122      *    - Added interrupt endpoint support.
123      *    - Added Agfa SnapScan Touch. Thanks to Jan Van den Bergh
124      *      <jan.vandenbergh@cs.kuleuven.ac.be>.
125      *    - Added Umax 1220U ID's. Thanks to Maciek Klimkowski
126      *      <mac@nexus.carleton.ca>.
127      *    - Fixed bug in write_scanner(). The buffer was not being properly
128      *      updated for writes larger than OBUF_SIZE. Thanks to Henrik 
129      *      Johansson <henrikjo@post.utfors.se> for identifying it.
130      *    - Added Microtek X6 ID's. Thanks to Oliver Neukum
131      *      <Oliver.Neukum@lrz.uni-muenchen.de>.
132      *
133      * 
134      *  0.4.1  2/15/2000
135      *  
136      *    - Fixed 'count' bug in read_scanner(). Thanks to Henrik
137      *      Johansson <henrikjo@post.utfors.se> for identifying it.  Amazing
138      *      it has worked this long.
139      *    - Fixed '>=' bug in both read/write_scanner methods.
140      *    - Cleaned up both read/write_scanner() methods so that they are 
141      *      a little more readable.
142      *    - Added a lot of Microtek ID's.  Thanks to Adrian Perez Jorge.
143      *    - Adopted the __initcall().
144      *    - Added #include <linux/init.h> to scanner.h for __initcall().
145      *    - Added one liner in irq_scanner() to keep gcc from complaining 
146      *      about an unused variable (data) if debugging was disabled
147      *      in scanner.c.
148      *    - Increased the timeout parameter in read_scanner() to 120 Secs.
149      *
150      *
151      *  0.4.2  3/23/2000
152      *
153      *    - Added Umax 1236U ID.  Thanks to Philipp Baer <ph_baer@npw.net>.
154      *    - Added Primax, ReadyScan, Visioneer, Colorado, and Genius ID's.
155      *      Thanks to Adrian Perez Jorge <adrianpj@easynews.com>.
156      *    - Fixed error number reported for non-existant devices.  Thanks to
157      *      Spyridon Papadimitriou <Spyridon_Papadimitriou@gs91.sp.cs.cmu.edu>.
158      *    - Added Acer Prisascan 620U ID's.  Thanks to Joao <joey@knoware.nl>.
159      *    - Replaced __initcall() with module_init()/module_exit(). Updates
160      *      from patch-2.3.48.
161      *    - Replaced file_operations structure with new syntax.  Updates
162      *      from patch-2.3.49.
163      *    - Changed #include "usb.h" to #include <linux/usb.h>
164      *    - Added #define SCN_IOCTL to exclude development areas 
165      *      since 2.4.x is about to be released. This mainly affects the 
166      *      ioctl() stuff.  See scanner.h for more details.
167      *    - Changed the return value for signal_pending() from -ERESTARTSYS to
168      *      -EINTR.
169      *
170      *
171      * 0.4.3  4/30/2000
172      *
173      *    - Added Umax Astra 2200 ID.  Thanks to Flynn Marquardt 
174      *      <flynn@isr.uni-stuttgart.de>.
175      *    - Added iVina 1200U ID. Thanks to Dyson Lin <dyson@avision.com.tw>.
176      *    - Added access time update for the device file courtesy of Paul
177      *      Mackerras <paulus@samba.org>.  This allows a user space daemon
178      *      to turn the lamp off for a Umax 1220U scanner after a prescribed
179      *      time.
180      *    - Fixed HP S20 ID's.  Thanks to Ruud Linders <rlinders@xs4all.nl>.
181      *    - Added Acer ScanPrisa 620U ID. Thanks to Oliver
182      *      Schwartz <Oliver.Schwartz@gmx.de> via sane-devel mail list.
183      *    - Fixed bug in read_scanner for copy_to_user() function.  The returned
184      *      value should be 'partial' not 'this_read'.
185      *    - Fixed bug in read_scanner. 'count' should be decremented 
186      *      by 'this_read' and not by 'partial'.  This resulted in twice as many
187      *      calls to read_scanner() for small amounts of data and possibly
188      *      unexpected returns of '0'.  Thanks to Karl Heinz 
189      *      Kremer <khk@khk.net> and Alain Knaff <Alain.Knaff@ltnb.lu>
190      *      for discovering this.
191      *    - Integrated Randy Dunlap's <randy.dunlap@intel.com> patch for a
192      *      scanner lookup/ident table. Thanks Randy.
193      *    - Documentation updates.
194      *    - Added wait queues to read_scanner().
195      *
196      *
197      * 0.4.3.1
198      *
199      *    - Fixed HP S20 ID's...again..sigh.  Thanks to Ruud
200      *      Linders <rlinders@xs4all.nl>.
201      *
202      * 0.4.4
203      *    - Added addtional Mustek ID's (BearPaw 1200, 600 CU, 1200 USB,
204      *      and 1200 UB.  Thanks to Henning Meier-Geinitz <henningmg@gmx.de>.
205      *    - Added the Vuego Scan Brisa 340U ID's.  Apparently this scanner is
206      *      marketed by Acer Peripherals as a cheap 300 dpi model. Thanks to
207      *      David Gundersen <gundersd@paradise.net.nz>.
208      *    - Added the Epson Expression1600 ID's. Thanks to Karl Heinz
209      *      Kremer <khk@khk.net>.
210      *
211      * 0.4.5  2/28/2001
212      *    - Added Mustek ID's (BearPaw 2400, 1200 CU Plus, BearPaw 1200F).
213      *      Thanks to Henning Meier-Geinitz <henningmg@gmx.de>.
214      *    - Added read_timeout module parameter to override RD_NAK_TIMEOUT
215      *      when read()'ing from devices.
216      *    - Stalled pipes are now checked and cleared with
217      *      usb_clear_halt() for the read_scanner() function. This should
218      *      address the "funky result: -32" error messages.
219      *    - Removed Microtek scanner ID's.  Microtek scanners are now
220      *      supported via the drivers/usb/microtek.c driver.
221      *    - Added scanner specific read timeout's.
222      *    - Return status errors are NEGATIVE!!!  This should address the
223      *      "funky result: -110" error messages.
224      *    - Replaced USB_ST_TIMEOUT with ETIMEDOUT.
225      *    - rd_nak was still defined in MODULE_PARM.  It's been updated with
226      *      read_timeout.  Thanks to Mark W. Webb <markwebb@adelphia.net> for
227      *      reporting this bug.
228      *    - Added Epson Perfection 1640SU and 1640SU Photo.  Thanks to
229      *      Jean-Luc <f5ibh@db0bm.ampr.org>.
230      *
231      * 0.4.6 08/16/2001 Yves Duret <yduret@mandrakesoft.com>
232      *    - added devfs support (from printer.c)
233      *
234      *  TODO
235      *
236      *    - Performance
237      *    - Select/poll methods
238      *    - More testing
239      *    - Proper registry/assignment for LM9830 ioctl's
240      *
241      *
242      *  Thanks to:
243      *
244      *    - All the folks on the linux-usb list who put up with me. :)  This 
245      *      has been a great learning experience for me.
246      *    - To Linus Torvalds for this great OS.
247      *    - The GNU folks.
248      *    - The folks that forwarded Vendor:Product ID's to me.
249      *    - Johannes Erdfelt for the loaning of a USB analyzer for tracking an
250      *      issue with HP-4100 and uhci.
251      *    - Adolfo Montero for his assistance.
252      *    - All the folks who chimed in with reports and suggestions.
253      *    - All the developers that are working on USB SANE backends or other
254      *      applications to use USB scanners.
255      *
256      *  Performance:
257      *
258      *    System: Pentium 120, 80 MB RAM, OHCI, Linux 2.3.23, HP 4100C USB Scanner
259      *            300 dpi scan of the entire bed
260      *      24 Bit Color ~ 70 secs - 3.6 Mbit/sec
261      *       8 Bit Gray ~ 17 secs - 4.2 Mbit/sec */
262     
263     /* 
264      * Scanner definitions, macros, module info, 
265      * debug/ioctl/data_dump enable, and other constants.
266      */ 
267     #include "scanner.h"
268     
269     
270     static void
271     irq_scanner(struct urb *urb)
272     {
273     
274     /*
275      * For the meantime, this is just a placeholder until I figure out what
276      * all I want to do with it -- or somebody else for that matter.
277      */
278     
279     	struct scn_usb_data *scn = urb->context;
280     	unsigned char *data = &scn->button;
281     	data += 0;		/* Keep gcc from complaining about unused var */
282     
283     	if (urb->status) {
284     		return;
285     	}
286     
287     	dbg("irq_scanner(%d): data:%x", scn->scn_minor, *data);
288     	return;
289     }
290     
291     
292     static int
293     open_scanner(struct inode * inode, struct file * file)
294     {
295     	struct scn_usb_data *scn;
296     	struct usb_device *dev;
297     
298     	kdev_t scn_minor;
299     
300     	int err=0;
301     
302     	lock_kernel();
303     
304     	scn_minor = USB_SCN_MINOR(inode);
305     
306     	dbg("open_scanner: scn_minor:%d", scn_minor);
307     
308     	if (!p_scn_table[scn_minor]) {
309     		err("open_scanner(%d): Unable to access minor data", scn_minor);
310     		err = -ENODEV;
311     		goto out_error;
312     	}
313     
314     	scn = p_scn_table[scn_minor];
315     
316     	dev = scn->scn_dev;
317     
318     	if (!dev) {
319     		err("open_scanner(%d): Scanner device not present", scn_minor);
320     		err = -ENODEV;
321     		goto out_error;
322     	}
323     
324     	if (!scn->present) {
325     		err("open_scanner(%d): Scanner is not present", scn_minor);
326     		err = -ENODEV;
327     		goto out_error;
328     	}
329     
330     	if (scn->isopen) {
331     		err("open_scanner(%d): Scanner device is already open", scn_minor);
332     		err = -EBUSY;
333     		goto out_error;
334     	}
335     
336     	init_waitqueue_head(&scn->rd_wait_q);
337     
338     	scn->isopen = 1;
339     
340     	file->private_data = scn; /* Used by the read and write metheds */
341     
342     	MOD_INC_USE_COUNT;
343     
344     out_error:
345     
346     	unlock_kernel();
347     
348     	return err;
349     }
350     
351     static int
352     close_scanner(struct inode * inode, struct file * file)
353     {
354     	struct scn_usb_data *scn;
355     
356     	kdev_t scn_minor;
357     
358     	scn_minor = USB_SCN_MINOR (inode);
359     
360     	dbg("close_scanner: scn_minor:%d", scn_minor);
361     
362     	if (!p_scn_table[scn_minor]) {
363     		err("close_scanner(%d): invalid scn_minor", scn_minor);
364     		return -ENODEV;
365     	}
366     
367     	scn = p_scn_table[scn_minor];
368     
369     	scn->isopen = 0;
370     
371     	file->private_data = NULL;
372     
373     	MOD_DEC_USE_COUNT;
374     
375     	return 0;
376     }
377     
378     static ssize_t
379     write_scanner(struct file * file, const char * buffer,
380                   size_t count, loff_t *ppos)
381     {
382     	struct scn_usb_data *scn;
383     	struct usb_device *dev;
384     
385     	ssize_t bytes_written = 0; /* Overall count of bytes written */
386     	ssize_t ret = 0;
387     
388     	kdev_t scn_minor;
389     
390     	int this_write;		/* Number of bytes to write */
391     	int partial;		/* Number of bytes successfully written */
392     	int result = 0;
393     
394     	char *obuf;
395     
396     	scn = file->private_data;
397     
398     	scn_minor = scn->scn_minor;
399     
400     	obuf = scn->obuf;
401     
402     	dev = scn->scn_dev;
403     
404     	file->f_dentry->d_inode->i_atime = CURRENT_TIME;
405     
406     	down(&(scn->gen_lock));
407     
408     	while (count > 0) {
409     
410     		if (signal_pending(current)) {
411     			ret = -EINTR;
412     			break;
413     		}
414     
415     		this_write = (count >= OBUF_SIZE) ? OBUF_SIZE : count;
416     
417     		if (copy_from_user(scn->obuf, buffer, this_write)) {
418     			ret = -EFAULT;
419     			break;
420     		}
421     
422     		result = usb_bulk_msg(dev,usb_sndbulkpipe(dev, scn->bulk_out_ep), obuf, this_write, &partial, 60*HZ);
423     		dbg("write stats(%d): result:%d this_write:%d partial:%d", scn_minor, result, this_write, partial);
424     
425     		if (result == -ETIMEDOUT) {	/* NAK -- shouldn't happen */
426     			warn("write_scanner: NAK received.");
427     			ret = result;
428     			break;
429     		} else if (result < 0) { /* We should not get any I/O errors */
430     			warn("write_scanner(%d): funky result: %d. Please notify the maintainer.", scn_minor, result);
431     			ret = -EIO;
432     			break;
433     		}
434     
435     #ifdef WR_DATA_DUMP
436     		if (partial) {
437     			unsigned char cnt, cnt_max;
438     			cnt_max = (partial > 24) ? 24 : partial;
439     			printk(KERN_DEBUG "dump(%d): ", scn_minor);
440     			for (cnt=0; cnt < cnt_max; cnt++) {
441     				printk("%X ", obuf[cnt]);
442     			}
443     			printk("\n");
444     		}
445     #endif
446     		if (partial != this_write) { /* Unable to write all contents of obuf */
447     			ret = -EIO;
448     			break;
449     		}
450     
451     		if (partial) { /* Data written */
452     			buffer += partial;
453     			count -= partial;
454     			bytes_written += partial;
455     		} else { /* No data written */
456     			ret = 0;
457     			break;
458     		}
459     	}
460     	up(&(scn->gen_lock));
461     	mdelay(5);		/* This seems to help with SANE queries */
462     	return ret ? ret : bytes_written;
463     }
464     
465     static ssize_t
466     read_scanner(struct file * file, char * buffer,
467                  size_t count, loff_t *ppos)
468     {
469     	struct scn_usb_data *scn;
470     	struct usb_device *dev;
471     
472     	ssize_t bytes_read;	/* Overall count of bytes_read */
473     	ssize_t ret;
474     
475     	kdev_t scn_minor;
476     
477     	int partial;		/* Number of bytes successfully read */
478     	int this_read;		/* Max number of bytes to read */
479     	int result;
480     	int rd_expire = RD_EXPIRE;
481     
482     	char *ibuf;
483     
484     	scn = file->private_data;
485     
486     	scn_minor = scn->scn_minor;
487     
488     	ibuf = scn->ibuf;
489     
490     	dev = scn->scn_dev;
491     
492     	bytes_read = 0;
493     	ret = 0;
494     
495     	file->f_dentry->d_inode->i_atime = CURRENT_TIME; /* Update the
496                                                                 atime of
497                                                                 the device
498                                                                 node */
499     	down(&(scn->gen_lock));
500     
501     	while (count > 0) {
502     		if (signal_pending(current)) {
503     			ret = -EINTR;
504     			break;
505     		}
506     
507     		this_read = (count >= IBUF_SIZE) ? IBUF_SIZE : count;
508     
509     		result = usb_bulk_msg(dev, usb_rcvbulkpipe(dev, scn->bulk_in_ep), ibuf, this_read, &partial, scn->rd_nak_timeout);
510     		dbg("read stats(%d): result:%d this_read:%d partial:%d count:%d", scn_minor, result, this_read, partial, count);
511     
512     /*
513      * Scanners are sometimes inheriently slow since they are mechanical
514      * in nature.  USB bulk reads tend to timeout while the scanner is
515      * positioning, resetting, warming up the lamp, etc if the timeout is
516      * set too low.  A very long timeout parameter for bulk reads was used
517      * to overcome this limitation, but this sometimes resulted in folks
518      * having to wait for the timeout to expire after pressing Ctrl-C from
519      * an application. The user was sometimes left with the impression
520      * that something had hung or crashed when in fact the USB read was
521      * just waiting on data.  So, the below code retains the same long
522      * timeout period, but splits it up into smaller parts so that
523      * Ctrl-C's are acted upon in a reasonable amount of time.
524      */
525     
526     		if (result == -ETIMEDOUT) { /* NAK */
527     			if (!partial) { /* No data */
528     				if (--rd_expire <= 0) {	/* Give it up */
529     					warn("read_scanner(%d): excessive NAK's received", scn_minor);
530     					ret = result;
531     					break;
532     				} else { /* Keep trying to read data */
533     					interruptible_sleep_on_timeout(&scn->rd_wait_q, scn->rd_nak_timeout);
534     					continue;
535     				}
536     			} else { /* Timeout w/ some data */
537     				goto data_recvd;
538     			}
539     		}
540     		
541     		if (result == -EPIPE) { /* No hope */
542     			if(usb_clear_halt(dev, scn->bulk_in_ep)) {
543     				err("read_scanner(%d): Failure to clear endpoint halt condition (%Zd).", scn_minor, ret);
544     			}
545     			ret = result;
546     			break;
547     		} else if ((result < 0) && (result != USB_ST_DATAUNDERRUN)) {
548     			warn("read_scanner(%d): funky result:%d. Please notify the maintainer.", scn_minor, (int)result);
549     			ret = -EIO;
550     			break;
551     		}
552     
553     	data_recvd:
554     
555     #ifdef RD_DATA_DUMP
556     		if (partial) {
557     			unsigned char cnt, cnt_max;
558     			cnt_max = (partial > 24) ? 24 : partial;
559     			printk(KERN_DEBUG "dump(%d): ", scn_minor);
560     			for (cnt=0; cnt < cnt_max; cnt++) {
561     				printk("%X ", ibuf[cnt]);
562     			}
563     			printk("\n");
564     		}
565     #endif
566     
567     		if (partial) { /* Data returned */
568     			if (copy_to_user(buffer, ibuf, partial)) {
569     				ret = -EFAULT;
570     				break;
571     			}
572     			count -= this_read; /* Compensate for short reads */
573     			bytes_read += partial; /* Keep tally of what actually was read */
574     			buffer += partial;
575     		} else {
576     			ret = 0;
577     			break;
578     		}
579     	}
580     	up(&(scn->gen_lock));
581     
582     	return ret ? ret : bytes_read;
583     }
584     
585     #ifdef SCN_IOCTL
586     static int
587     ioctl_scanner(struct inode *inode, struct file *file,
588     	      unsigned int cmd, unsigned long arg)
589     {
590     	struct usb_device *dev;
591     
592     	int result;
593     
594     	kdev_t scn_minor;
595     
596     	scn_minor = USB_SCN_MINOR(inode);
597     
598     	if (!p_scn_table[scn_minor]) {
599     		err("ioctl_scanner(%d): invalid scn_minor", scn_minor);
600     		return -ENODEV;
601     	}
602     
603     	dev = p_scn_table[scn_minor]->scn_dev;
604     
605     	switch (cmd)
606     	{
607     	case IOCTL_SCANNER_VENDOR :
608     		return (put_user(dev->descriptor.idVendor, (unsigned int *) arg));
609     	case IOCTL_SCANNER_PRODUCT :
610     		return (put_user(dev->descriptor.idProduct, (unsigned int *) arg));
611     	case PV8630_IOCTL_INREQUEST :
612     	{
613     		struct {
614     			__u8  data;
615     			__u8  request;
616     			__u16 value;
617     			__u16 index;
618     		} args;
619     
620     		if (copy_from_user(&args, (void *)arg, sizeof(args)))
621     			return -EFAULT;
622     
623     		result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
624     					 args.request, USB_TYPE_VENDOR|
625     					 USB_RECIP_DEVICE|USB_DIR_IN,
626     					 args.value, args.index, &args.data,
627     					 1, HZ*5);
628     
629     		dbg("ioctl_scanner(%d): inreq: args.data:%x args.value:%x args.index:%x args.request:%x\n", scn_minor, args.data, args.value, args.index, args.request);
630     
631     		if (copy_to_user((void *)arg, &args, sizeof(args)))
632     			return -EFAULT;
633     
634     		dbg("ioctl_scanner(%d): inreq: result:%d\n", scn_minor, result);
635     
636     		return result;
637     	}
638     	case PV8630_IOCTL_OUTREQUEST :
639     	{
640     		struct {
641     			__u8  request;
642     			__u16 value;
643     			__u16 index;
644     		} args;
645     
646     		if (copy_from_user(&args, (void *)arg, sizeof(args)))
647     			return -EFAULT;
648     
649     		dbg("ioctl_scanner(%d): outreq: args.value:%x args.index:%x args.request:%x\n", scn_minor, args.value, args.index, args.request);
650     
651     		result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
652     					 args.request, USB_TYPE_VENDOR|
653     					 USB_RECIP_DEVICE|USB_DIR_OUT,
654     					 args.value, args.index, NULL,
655     					 0, HZ*5);
656     
657     		dbg("ioctl_scanner(%d): outreq: result:%d\n", scn_minor, result);
658     
659     		return result;
660     	}
661     	default:
662     		return -ENOTTY;
663     	}
664     	return 0;
665     }
666     #endif /* SCN_IOCTL */
667     
668     static struct
669     file_operations usb_scanner_fops = {
670     	read:		read_scanner,
671     	write:		write_scanner,
672     #ifdef SCN_IOCTL
673     	ioctl:		ioctl_scanner,
674     #endif /* SCN_IOCTL */
675     	open:		open_scanner,
676     	release:	close_scanner,
677     };
678     
679     static void *
680     probe_scanner(struct usb_device *dev, unsigned int ifnum,
681     	      const struct usb_device_id *id)
682     {
683     	struct scn_usb_data *scn;
684     	struct usb_interface_descriptor *interface;
685     	struct usb_endpoint_descriptor *endpoint;
686     
687     	int ep_cnt;
688     	int ix;
689     
690     	kdev_t scn_minor;
691     
692     	char valid_device = 0;
693     	char have_bulk_in, have_bulk_out, have_intr;
694     
695     	if (vendor != -1 && product != -1) {
696     		info("probe_scanner: User specified USB scanner -- Vendor:Product - %x:%x", vendor, product);
697     	}
698     
699     	dbg("probe_scanner: USB dev address:%p", dev);
700     	dbg("probe_scanner: ifnum:%u", ifnum);
701     
702     /*
703      * 1. Check Vendor/Product
704      * 2. Determine/Assign Bulk Endpoints
705      * 3. Determine/Assign Intr Endpoint
706      */
707     
708     /*
709      * There doesn't seem to be an imaging class defined in the USB
710      * Spec. (yet).  If there is, HP isn't following it and it doesn't
711      * look like anybody else is either.  Therefore, we have to test the
712      * Vendor and Product ID's to see what we have.  Also, other scanners
713      * may be able to use this driver by specifying both vendor and
714      * product ID's as options to the scanner module in conf.modules.
715      *
716      * NOTE: Just because a product is supported here does not mean that
717      * applications exist that support the product.  It's in the hopes
718      * that this will allow developers a means to produce applications
719      * that will support USB products.
720      *
721      * Until we detect a device which is pleasing, we silently punt.
722      */
723     
724     	for (ix = 0; ix < sizeof (scanner_device_ids) / sizeof (struct usb_device_id); ix++) {
725     		if ((dev->descriptor.idVendor == scanner_device_ids [ix].idVendor) &&
726     		    (dev->descriptor.idProduct == scanner_device_ids [ix].idProduct)) {
727     			valid_device = 1;
728     			break;
729                     }
730     	}
731     	if (dev->descriptor.idVendor == vendor &&   /* User specified */
732     	    dev->descriptor.idProduct == product) { /* User specified */
733     		valid_device = 1;
734     	}
735     
736             if (!valid_device)
737                     return NULL;    /* We didn't find anything pleasing */
738     
739     /*
740      * After this point we can be a little noisy about what we are trying to
741      *  configure.
742      */
743     
744     	if (dev->descriptor.bNumConfigurations != 1) {
745     		info("probe_scanner: Only one device configuration is supported.");
746     		return NULL;
747     	}
748     
749     	if (dev->config[0].bNumInterfaces != 1) {
750     		info("probe_scanner: Only one device interface is supported.");
751     		return NULL;
752     	}
753     
754     	interface = dev->config[0].interface[ifnum].altsetting;
755     	endpoint = interface[ifnum].endpoint;
756     
757     /*
758      * Start checking for two bulk endpoints OR two bulk endpoints *and* one
759      * interrupt endpoint. If we have an interrupt endpoint go ahead and
760      * setup the handler. FIXME: This is a future enhancement...
761      */
762     
763     	dbg("probe_scanner: Number of Endpoints:%d", (int) interface->bNumEndpoints);
764     
765     	if ((interface->bNumEndpoints != 2) && (interface->bNumEndpoints != 3)) {
766     		info("probe_scanner: Only two or three endpoints supported.");
767     		return NULL;
768     	}
769     
770     	ep_cnt = have_bulk_in = have_bulk_out = have_intr = 0;
771     
772     	while (ep_cnt < interface->bNumEndpoints) {
773     
774     		if (!have_bulk_in && IS_EP_BULK_IN(endpoint[ep_cnt])) {
775     			ep_cnt++;
776     			have_bulk_in = ep_cnt;
777     			dbg("probe_scanner: bulk_in_ep:%d", have_bulk_in);
778     			continue;
779     		}
780     
781     		if (!have_bulk_out && IS_EP_BULK_OUT(endpoint[ep_cnt])) {
782     			ep_cnt++;
783     			have_bulk_out = ep_cnt;
784     			dbg("probe_scanner: bulk_out_ep:%d", have_bulk_out);
785     			continue;
786     		}
787     
788     		if (!have_intr && IS_EP_INTR(endpoint[ep_cnt])) {
789     			ep_cnt++;
790     			have_intr = ep_cnt;
791     			dbg("probe_scanner: intr_ep:%d", have_intr);
792     			continue;
793     		}
794     		info("probe_scanner: Undetected endpoint. Notify the maintainer.");
795     		return NULL;	/* Shouldn't ever get here unless we have something weird */
796     	}
797     
798     
799     /*
800      * Perform a quick check to make sure that everything worked as it
801      * should have.
802      */
803     
804     	switch(interface->bNumEndpoints) {
805     	case 2:
806     		if (!have_bulk_in || !have_bulk_out) {
807     			info("probe_scanner: Two bulk endpoints required.");
808     			return NULL;
809     		}
810     		break;
811     	case 3:
812     		if (!have_bulk_in || !have_bulk_out || !have_intr) {
813     			info("probe_scanner: Two bulk endpoints and one interrupt endpoint required.");
814     			return NULL;
815     		}
816     		break;
817     	default:
818     		info("probe_scanner: Endpoint determination failed.  Notify the maintainer.");
819     		return NULL;
820     	}
821     
822     
823     /*
824      * Determine a minor number and initialize the structure associated
825      * with it.  The problem with this is that we are counting on the fact
826      * that the user will sequentially add device nodes for the scanner
827      * devices.  */
828     
829     	for (scn_minor = 0; scn_minor < SCN_MAX_MNR; scn_minor++) {
830     		if (!p_scn_table[scn_minor])
831     			break;
832     	}
833     
834     /* Check to make sure that the last slot isn't already taken */
835     	if (p_scn_table[scn_minor]) {
836     		err("probe_scanner: No more minor devices remaining.");
837     		return NULL;
838     	}
839     
840     	dbg("probe_scanner: Allocated minor:%d", scn_minor);
841     
842     	if (!(scn = kmalloc (sizeof (struct scn_usb_data), GFP_KERNEL))) {
843     		err("probe_scanner: Out of memory.");
844     		return NULL;
845     	}
846     	memset (scn, 0, sizeof(struct scn_usb_data));
847     	dbg ("probe_scanner(%d): Address of scn:%p", scn_minor, scn);
848     
849     
850     /* Ok, if we detected an interrupt EP, setup a handler for it */
851     	if (have_intr) {
852     		dbg("probe_scanner(%d): Configuring IRQ handler for intr EP:%d", scn_minor, have_intr);
853     		FILL_INT_URB(&scn->scn_irq, dev,
854     			     usb_rcvintpipe(dev, have_intr),
855     			     &scn->button, 1, irq_scanner, scn,
856     			     // endpoint[(int)have_intr].bInterval);
857     			     250);
858     
859     	        if (usb_submit_urb(&scn->scn_irq)) {
860     			err("probe_scanner(%d): Unable to allocate INT URB.", scn_minor);
861                     	kfree(scn);
862                     	return NULL;
863             	}
864     	}
865     
866     
867     /* Ok, now initialize all the relevant values */
868     	if (!(scn->obuf = (char *)kmalloc(OBUF_SIZE, GFP_KERNEL))) {
869     		err("probe_scanner(%d): Not enough memory for the output buffer.", scn_minor);
870     		kfree(scn);
871     		return NULL;
872     	}
873     	dbg("probe_scanner(%d): obuf address:%p", scn_minor, scn->obuf);
874     
875     	if (!(scn->ibuf = (char *)kmalloc(IBUF_SIZE, GFP_KERNEL))) {
876     		err("probe_scanner(%d): Not enough memory for the input buffer.", scn_minor);
877     		kfree(scn->obuf);
878     		kfree(scn);
879     		return NULL;
880     	}
881     	dbg("probe_scanner(%d): ibuf address:%p", scn_minor, scn->ibuf);
882     	
883     
884     	switch (dev->descriptor.idVendor) { /* Scanner specific read timeout parameters */
885     	case 0x04b8:		/* Seiko/Epson */
886     		scn->rd_nak_timeout = HZ * 40;
887     		break;
888     	case 0x055f:		/* Mustek */
889     	case 0x0400:		/* Another Mustek */
890     	case 0x0ff5:		/* And yet another Mustek */
891     		scn->rd_nak_timeout = HZ * 1;
892     	default:
893     		scn->rd_nak_timeout = RD_NAK_TIMEOUT;
894     	}
895     
896     
897     	if (read_timeout > 0) {	/* User specified read timeout overrides everything */
898     		info("probe_scanner: User specified USB read timeout - %d", read_timeout);
899     		scn->rd_nak_timeout = read_timeout;
900     	}
901     
902     
903     	scn->bulk_in_ep = have_bulk_in;
904     	scn->bulk_out_ep = have_bulk_out;
905     	scn->intr_ep = have_intr;
906     	scn->present = 1;
907     	scn->scn_dev = dev;
908     	scn->scn_minor = scn_minor;
909     	scn->isopen = 0;
910     
911     	init_MUTEX(&(scn->gen_lock));
912     
913     	/* if we have devfs, create with perms=660 */
914     	scn->devfs = devfs_register(usb_devfs_handle, "scanner",
915     				      DEVFS_FL_DEFAULT, USB_MAJOR,
916     				      SCN_BASE_MNR + scn_minor,
917     				      S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP |
918     				      S_IWGRP, &usb_scanner_fops, NULL);
919     
920     
921     	return p_scn_table[scn_minor] = scn;
922     }
923     
924     static void
925     disconnect_scanner(struct usb_device *dev, void *ptr)
926     {
927     	struct scn_usb_data *scn = (struct scn_usb_data *) ptr;
928     
929     	if(scn->intr_ep) {
930     		dbg("disconnect_scanner(%d): Unlinking IRQ URB", scn->scn_minor);
931     		usb_unlink_urb(&scn->scn_irq);
932     	}
933             usb_driver_release_interface(&scanner_driver,
934                     &scn->scn_dev->actconfig->interface[scn->ifnum]);
935     
936     	devfs_unregister (scn->devfs);
937     
938     	kfree(scn->ibuf);
939     	kfree(scn->obuf);
940     
941     	dbg("disconnect_scanner: De-allocating minor:%d", scn->scn_minor);
942     	p_scn_table[scn->scn_minor] = NULL;
943     	kfree (scn);
944     }
945     
946     
947     static struct
948     usb_driver scanner_driver = {
949     	name:		"usbscanner",
950     	probe:		probe_scanner,
951     	disconnect:	disconnect_scanner,
952     	fops:		&usb_scanner_fops,
953     	minor:		SCN_BASE_MNR,
954     	id_table:	NULL, /* This would be scanner_device_ids, but we
955     				 need to check every USB device, in case
956     				 we match a user defined vendor/product ID. */
957     };
958     
959     void __exit
960     usb_scanner_exit(void)
961     {
962     	usb_deregister(&scanner_driver);
963     }
964     
965     int __init
966     usb_scanner_init (void)
967     {
968             if (usb_register(&scanner_driver) < 0)
969                     return -1;
970     
971     	info("USB Scanner support registered.");
972     	return 0;
973     }
974     
975     module_init(usb_scanner_init);
976     module_exit(usb_scanner_exit);
977