4d300c114e09bb1c429fc834f1c438aa4e95f076
[linux-flexiantxendom0-3.2.10.git] / drivers / usb / microtek.c
1 /* Driver for Microtek Scanmaker X6 USB scanner, and possibly others.
2  *
3  * (C) Copyright 2000 John Fremlin <vii@penguinpowered.com>
4  * (C) Copyright 2000 Oliver Neukum <Oliver.Neukum@lrz.uni-muenchen.de>
5  *
6  * Parts shamelessly stolen from usb-storage and copyright by their
7  * authors. Thanks to Matt Dharm for giving us permission!
8  *
9  * This driver implements a SCSI host controller driver and a USB
10  * device driver. To avoid confusion, all the USB related stuff is
11  * prefixed by mts_usb_ and all the SCSI stuff by mts_scsi_.
12  *
13  * Microtek (www.microtek.com) did not release the specifications for
14  * their USB protocol to us, so we had to reverse engineer them. We
15  * don't know for which models they are valid.
16  *
17  * The X6 USB has three bulk endpoints, one output (0x1) down which
18  * commands and outgoing data are sent, and two input: 0x82 from which
19  * normal data is read from the scanner (in packets of maximum 32
20  * bytes) and from which the status byte is read, and 0x83 from which
21  * the results of a scan (or preview) are read in up to 64 * 1024 byte
22  * chunks by the Windows driver. We don't know how much it is possible
23  * to read at a time from 0x83.
24  *
25  * It seems possible to read (with URB transfers) everything from 0x82
26  * in one go, without bothering to read in 32 byte chunks.
27  *
28  * There seems to be an optimisation of a further READ implicit if
29  * you simply read from 0x83.
30  *
31  * Guessed protocol:
32  *
33  *      Send raw SCSI command to EP 0x1
34  *
35  *      If there is data to receive:
36  *              If the command was READ datatype=image:
37  *                      Read a lot of data from EP 0x83
38  *              Else:
39  *                      Read data from EP 0x82
40  *      Else:
41  *              If there is data to transmit:
42  *                      Write it to EP 0x1
43  *
44  *      Read status byte from EP 0x82
45  *
46  * References:
47  *
48  * The SCSI command set for the scanner is available from
49  *      ftp://ftp.microtek.com/microtek/devpack/
50  *
51  * Microtek NV sent us a more up to date version of the document. If
52  * you want it, just send mail.
53  *
54  * Status:
55  *
56  *      Untested with multiple scanners.
57  *      Untested on SMP.
58  *      Untested on a bigendian machine.
59  *
60  * History:
61  *
62  *      20000417 starting history
63  *      20000417 fixed load oops
64  *      20000417 fixed unload oops
65  *      20000419 fixed READ IMAGE detection
66  *      20000424 started conversion to use URBs
67  *      20000502 handled short transfers as errors
68  *      20000513 rename and organisation of functions (john)
69  *      20000513 added IDs for all products supported by Windows driver (john)
70  *      20000514 Rewrote mts_scsi_queuecommand to use URBs (john)
71  *      20000514 Version 0.0.8j
72  *      20000514 Fix reporting of non-existant devices to SCSI layer (john)
73  *      20000514 Added MTS_DEBUG_INT (john)
74  *      20000514 Changed "usb-microtek" to "microtek" for consistency (john)
75  *      20000514 Stupid bug fixes (john)
76  *      20000514 Version 0.0.9j
77  *      20000515 Put transfer context and URB in mts_desc (john)
78  *      20000515 Added prelim turn off debugging support (john)
79  *      20000515 Version 0.0.10j
80  *      20000515 Fixed up URB allocation (clear URB on alloc) (john)
81  *      20000515 Version 0.0.11j
82  *      20000516 Removed unnecessary spinlock in mts_transfer_context (john)
83  *      20000516 Removed unnecessary up on instance lock in mts_remove_nolock (john)
84  *      20000516 Implemented (badly) scsi_abort (john)
85  *      20000516 Version 0.0.12j
86  *      20000517 Hopefully removed mts_remove_nolock quasideadlock (john)
87  *      20000517 Added mts_debug_dump to print ll USB info (john)
88  *      20000518 Tweaks and documentation updates (john)
89  *      20000518 Version 0.0.13j
90  *      20000518 Cleaned up abort handling (john)
91  *      20000523 Removed scsi_command and various scsi_..._resets (john)
92  *      20000523 Added unlink URB on scsi_abort, now OHCI supports it (john)
93  *      20000523 Fixed last tiresome compile warning (john)
94  *      20000523 Version 0.0.14j (though version 0.1 has come out?)
95  *      20000602 Added primitive reset
96  *      20000602 Version 0.2.0
97  *      20000603 various cosmetic changes
98  *      20000603 Version 0.2.1
99  *      20000620 minor cosmetic changes
100  *      20000620 Version 0.2.2
101  *      20000822 Hopefully fixed deadlock in mts_remove_nolock()
102  *      20000822 Fixed minor race in mts_transfer_cleanup()
103  *      20000822 Fixed deadlock on submission error in queuecommand
104  *      20000822 Version 0.2.3
105  *      20000913 Reduced module size if debugging is off
106  *      20000913 Version 0.2.4
107  *      20010210 New abort logic
108  *      20010210 Version 0.3.0
109  *      20010217 Merged scatter/gather
110  *      20010218 Version 0.4.0
111  *      20010218 Cosmetic fixes
112  *      20010218 Version 0.4.1
113  *      20010306 Abort while using scatter/gather
114  *      20010306 Version 0.4.2
115  *      20010311 Remove all timeouts and tidy up generally (john)
116  *      20010320 check return value of scsi_register()
117  *      20010320 Version 0.4.3
118  *      20010408 Identify version on module load.
119  */
120
121 #include <linux/module.h>
122 #include <linux/kernel.h>
123 #include <linux/sched.h>
124 #include <linux/signal.h>
125 #include <linux/errno.h>
126 #include <linux/random.h>
127 #include <linux/poll.h>
128 #include <linux/init.h>
129 #include <linux/slab.h>
130 #include <linux/spinlock.h>
131 #include <linux/smp_lock.h>
132 #include <linux/usb.h>
133 #include <linux/proc_fs.h>
134
135 #include <asm/atomic.h>
136 #include <linux/blk.h>
137 #include "../scsi/scsi.h"
138 #include "../scsi/hosts.h"
139 #include "../scsi/sd.h"
140
141 #include "microtek.h"
142
143 /*
144  * Version Information
145  */
146 #define DRIVER_VERSION "v0.4.3"
147 #define DRIVER_AUTHOR "John Fremlin <vii@penguinpowered.com>, Oliver Neukum <Oliver.Neukum@lrz.uni-muenchen.de>"
148 #define DRIVER_DESC "Microtek Scanmaker X6 USB scanner driver"
149
150 /* Should we do debugging? */
151
152 //#define MTS_DO_DEBUG
153
154 /* USB layer driver interface */
155
156 static void *mts_usb_probe(struct usb_device *dev, unsigned int interface,
157                          const struct usb_device_id *id);
158 static void mts_usb_disconnect(struct usb_device *dev, void *ptr);
159
160 static struct usb_device_id mts_usb_ids [];
161
162 static struct usb_driver mts_usb_driver = {
163         name:           "microtekX6",
164         probe:          mts_usb_probe,
165         disconnect:     mts_usb_disconnect,
166         id_table:       mts_usb_ids,
167 };
168
169
170 /* Internal driver stuff */
171
172 #define MTS_VERSION     "0.4.3"
173 #define MTS_NAME        "microtek usb (rev " MTS_VERSION "): "
174
175 #define MTS_WARNING(x...) \
176         printk( KERN_WARNING MTS_NAME x )
177 #define MTS_ERROR(x...) \
178         printk( KERN_ERR MTS_NAME x )
179 #define MTS_INT_ERROR(x...) \
180         MTS_ERROR(x)
181 #define MTS_MESSAGE(x...) \
182         printk( KERN_INFO MTS_NAME x )
183
184 #if defined MTS_DO_DEBUG
185
186 #define MTS_DEBUG(x...) \
187         printk( KERN_DEBUG MTS_NAME x )
188
189 #define MTS_DEBUG_GOT_HERE() \
190         MTS_DEBUG("got to %s:%d (%s)\n", __FILE__, (int)__LINE__, __PRETTY_FUNCTION__ )
191 #define MTS_DEBUG_INT() \
192         do { MTS_DEBUG_GOT_HERE(); \
193              MTS_DEBUG("transfer = 0x%x context = 0x%x\n",(int)transfer,(int)context ); \
194              MTS_DEBUG("status = 0x%x data-length = 0x%x sent = 0x%x\n",(int)transfer->status,(int)context->data_length, (int)transfer->actual_length ); \
195              mts_debug_dump(context->instance);\
196            } while(0)
197 #else
198
199 #define MTS_NUL_STATEMENT do { } while(0)
200
201 #define MTS_DEBUG(x...) MTS_NUL_STATEMENT
202 #define MTS_DEBUG_GOT_HERE() MTS_NUL_STATEMENT
203 #define MTS_DEBUG_INT() MTS_NUL_STATEMENT
204
205 #endif
206
207
208
209 #define MTS_INT_INIT()\
210         struct mts_transfer_context* context = (struct mts_transfer_context*)transfer->context; \
211         MTS_DEBUG_INT();\
212
213 #ifdef MTS_DO_DEBUG
214
215 static inline void mts_debug_dump(struct mts_desc* desc) {
216         MTS_DEBUG("desc at 0x%x: halted = %02x%02x, toggle = %02x%02x\n",
217                   (int)desc,(int)desc->usb_dev->halted[1],(int)desc->usb_dev->halted[0],
218                   (int)desc->usb_dev->toggle[1],(int)desc->usb_dev->toggle[0]
219                 );
220         MTS_DEBUG("ep_out=%x ep_response=%x ep_image=%x\n",
221                   usb_sndbulkpipe(desc->usb_dev,desc->ep_out),
222                   usb_rcvbulkpipe(desc->usb_dev,desc->ep_response),
223                   usb_rcvbulkpipe(desc->usb_dev,desc->ep_image)
224                 );
225 }
226
227
228 static inline void mts_show_command(Scsi_Cmnd *srb)
229 {
230         char *what = NULL;
231
232         switch (srb->cmnd[0]) {
233         case TEST_UNIT_READY: what = "TEST_UNIT_READY"; break;
234         case REZERO_UNIT: what = "REZERO_UNIT"; break;
235         case REQUEST_SENSE: what = "REQUEST_SENSE"; break;
236         case FORMAT_UNIT: what = "FORMAT_UNIT"; break;
237         case READ_BLOCK_LIMITS: what = "READ_BLOCK_LIMITS"; break;
238         case REASSIGN_BLOCKS: what = "REASSIGN_BLOCKS"; break;
239         case READ_6: what = "READ_6"; break;
240         case WRITE_6: what = "WRITE_6"; break;
241         case SEEK_6: what = "SEEK_6"; break;
242         case READ_REVERSE: what = "READ_REVERSE"; break;
243         case WRITE_FILEMARKS: what = "WRITE_FILEMARKS"; break;
244         case SPACE: what = "SPACE"; break;
245         case INQUIRY: what = "INQUIRY"; break;
246         case RECOVER_BUFFERED_DATA: what = "RECOVER_BUFFERED_DATA"; break;
247         case MODE_SELECT: what = "MODE_SELECT"; break;
248         case RESERVE: what = "RESERVE"; break;
249         case RELEASE: what = "RELEASE"; break;
250         case COPY: what = "COPY"; break;
251         case ERASE: what = "ERASE"; break;
252         case MODE_SENSE: what = "MODE_SENSE"; break;
253         case START_STOP: what = "START_STOP"; break;
254         case RECEIVE_DIAGNOSTIC: what = "RECEIVE_DIAGNOSTIC"; break;
255         case SEND_DIAGNOSTIC: what = "SEND_DIAGNOSTIC"; break;
256         case ALLOW_MEDIUM_REMOVAL: what = "ALLOW_MEDIUM_REMOVAL"; break;
257         case SET_WINDOW: what = "SET_WINDOW"; break;
258         case READ_CAPACITY: what = "READ_CAPACITY"; break;
259         case READ_10: what = "READ_10"; break;
260         case WRITE_10: what = "WRITE_10"; break;
261         case SEEK_10: what = "SEEK_10"; break;
262         case WRITE_VERIFY: what = "WRITE_VERIFY"; break;
263         case VERIFY: what = "VERIFY"; break;
264         case SEARCH_HIGH: what = "SEARCH_HIGH"; break;
265         case SEARCH_EQUAL: what = "SEARCH_EQUAL"; break;
266         case SEARCH_LOW: what = "SEARCH_LOW"; break;
267         case SET_LIMITS: what = "SET_LIMITS"; break;
268         case READ_POSITION: what = "READ_POSITION"; break;
269         case SYNCHRONIZE_CACHE: what = "SYNCHRONIZE_CACHE"; break;
270         case LOCK_UNLOCK_CACHE: what = "LOCK_UNLOCK_CACHE"; break;
271         case READ_DEFECT_DATA: what = "READ_DEFECT_DATA"; break;
272         case MEDIUM_SCAN: what = "MEDIUM_SCAN"; break;
273         case COMPARE: what = "COMPARE"; break;
274         case COPY_VERIFY: what = "COPY_VERIFY"; break;
275         case WRITE_BUFFER: what = "WRITE_BUFFER"; break;
276         case READ_BUFFER: what = "READ_BUFFER"; break;
277         case UPDATE_BLOCK: what = "UPDATE_BLOCK"; break;
278         case READ_LONG: what = "READ_LONG"; break;
279         case WRITE_LONG: what = "WRITE_LONG"; break;
280         case CHANGE_DEFINITION: what = "CHANGE_DEFINITION"; break;
281         case WRITE_SAME: what = "WRITE_SAME"; break;
282         case READ_TOC: what = "READ_TOC"; break;
283         case LOG_SELECT: what = "LOG_SELECT"; break;
284         case LOG_SENSE: what = "LOG_SENSE"; break;
285         case MODE_SELECT_10: what = "MODE_SELECT_10"; break;
286         case MODE_SENSE_10: what = "MODE_SENSE_10"; break;
287         case MOVE_MEDIUM: what = "MOVE_MEDIUM"; break;
288         case READ_12: what = "READ_12"; break;
289         case WRITE_12: what = "WRITE_12"; break;
290         case WRITE_VERIFY_12: what = "WRITE_VERIFY_12"; break;
291         case SEARCH_HIGH_12: what = "SEARCH_HIGH_12"; break;
292         case SEARCH_EQUAL_12: what = "SEARCH_EQUAL_12"; break;
293         case SEARCH_LOW_12: what = "SEARCH_LOW_12"; break;
294         case READ_ELEMENT_STATUS: what = "READ_ELEMENT_STATUS"; break;
295         case SEND_VOLUME_TAG: what = "SEND_VOLUME_TAG"; break;
296         case WRITE_LONG_2: what = "WRITE_LONG_2"; break;
297         default:
298                 MTS_DEBUG("can't decode command\n");
299                 goto out;
300                 break;
301         }
302         MTS_DEBUG( "Command %s (%d bytes)\n", what, srb->cmd_len);
303
304  out:
305         MTS_DEBUG( "  %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x\n",
306                srb->cmnd[0], srb->cmnd[1], srb->cmnd[2], srb->cmnd[3], srb->cmnd[4], srb->cmnd[5],
307                srb->cmnd[6], srb->cmnd[7], srb->cmnd[8], srb->cmnd[9]);
308 }
309
310 #else
311
312 static inline void mts_show_command(Scsi_Cmnd * dummy)
313 {
314 }
315
316 static inline void mts_debug_dump(struct mts_desc* dummy)
317 {
318 }
319
320 #endif
321
322
323 /* static inline int mts_is_aborting(struct mts_desc* desc) {
324         return (atomic_read(&desc->context.do_abort));
325 }  */
326
327 static inline void mts_urb_abort(struct mts_desc* desc) {
328         MTS_DEBUG_GOT_HERE();
329         mts_debug_dump(desc);
330
331         usb_unlink_urb( &desc->urb );
332 }
333
334 static struct mts_desc * mts_list; /* list of active scanners */
335 struct semaphore mts_list_semaphore;
336
337 /* Internal list operations */
338
339 static
340 void mts_remove_nolock( struct mts_desc* to_remove )
341 {
342         MTS_DEBUG( "removing 0x%x from list\n",
343                    (int)to_remove );
344
345         lock_kernel();
346         mts_urb_abort(to_remove);
347
348         MTS_DEBUG_GOT_HERE();
349
350         if ( to_remove != mts_list ) {
351                 MTS_DEBUG_GOT_HERE();
352                 if (to_remove->prev && to_remove->next)
353                         to_remove->prev->next = to_remove->next;
354         } else {
355                 MTS_DEBUG_GOT_HERE();
356                 mts_list = to_remove->next;
357                 if (mts_list) {
358                         MTS_DEBUG_GOT_HERE();
359                         mts_list->prev = 0;
360                 }
361         }
362
363         if ( to_remove->next ) {
364                 MTS_DEBUG_GOT_HERE();
365                 to_remove->next->prev = to_remove->prev;
366         }
367
368         MTS_DEBUG_GOT_HERE();
369         scsi_unregister_module(MODULE_SCSI_HA, &(to_remove->ctempl));
370         unlock_kernel();
371
372         kfree( to_remove );
373 }
374
375 static
376 void mts_add_nolock( struct mts_desc* to_add )
377 {
378         MTS_DEBUG( "adding 0x%x to list\n", (int)to_add );
379
380         to_add->prev = 0;
381         to_add->next = mts_list;
382         if ( mts_list ) {
383                 mts_list->prev = to_add;
384         }
385
386         mts_list = to_add;
387 }
388
389
390
391
392 /* SCSI driver interface */
393
394 /* scsi related functions - dummies for now mostly */
395
396 static int mts_scsi_release(struct Scsi_Host *psh)
397 {
398         MTS_DEBUG_GOT_HERE();
399
400         return 0;
401 }
402
403 static int mts_scsi_abort (Scsi_Cmnd *srb)
404 {
405         struct mts_desc* desc = (struct mts_desc*)(srb->host->hostdata[0]);
406
407         MTS_DEBUG_GOT_HERE();
408
409         mts_urb_abort(desc);
410
411         return SCSI_ABORT_PENDING;
412 }
413
414 static int mts_scsi_host_reset (Scsi_Cmnd *srb)
415 {
416         struct mts_desc* desc = (struct mts_desc*)(srb->host->hostdata[0]);
417
418         MTS_DEBUG_GOT_HERE();
419         mts_debug_dump(desc);
420
421         usb_reset_device(desc->usb_dev); /*FIXME: untested on new reset code */
422         return 0;  /* RANT why here 0 and not SUCCESS */
423 }
424
425 /* the core of the scsi part */
426
427 /* faking a detection - which can't fail :-) */
428
429 static int mts_scsi_detect (struct SHT * sht)
430 {
431         /* Whole function stolen from usb-storage */
432
433         struct mts_desc * desc = (struct mts_desc *)sht->proc_dir;
434         /* What a hideous hack! */
435
436         char local_name[48];
437
438         MTS_DEBUG_GOT_HERE();
439
440         /* set up the name of our subdirectory under /proc/scsi/ */
441         sprintf(local_name, "microtek-%d", desc->host_number);
442         sht->proc_name = kmalloc (strlen(local_name) + 1, GFP_KERNEL);
443         /* FIXME: where is this freed ? */
444
445         if (!sht->proc_name) {
446                 MTS_ERROR( "unable to allocate memory for proc interface!!\n" );
447                 return 0;
448         }
449
450         strcpy(sht->proc_name, local_name);
451
452         sht->proc_dir = NULL;
453
454         /* In host->hostdata we store a pointer to desc */
455         desc->host = scsi_register(sht, sizeof(desc));
456         if (desc->host == NULL) {
457                 MTS_ERROR("Cannot register due to low memory");
458                 kfree(sht->proc_name);
459                 return 0;
460         }
461         desc->host->hostdata[0] = (unsigned long)desc;
462 /* FIXME: what if sizeof(void*) != sizeof(unsigned long)? */
463
464         return 1;
465 }
466
467
468
469 /* Main entrypoint: SCSI commands are dispatched to here */
470
471
472
473 static
474 int mts_scsi_queuecommand (Scsi_Cmnd *srb, mts_scsi_cmnd_callback callback );
475
476 static void mts_transfer_cleanup( struct urb *transfer );
477 static void mts_do_sg(struct urb * transfer);
478
479
480 inline static
481 void mts_int_submit_urb (struct urb* transfer,
482                         int pipe,
483                         void* data,
484                         unsigned length,
485                         mts_usb_urb_callback callback )
486 /* Interrupt context! */
487
488 /* Holding transfer->context->lock! */
489 {
490         int res;
491
492         MTS_INT_INIT();
493
494         FILL_BULK_URB(transfer,
495                       context->instance->usb_dev,
496                       pipe,
497                       data,
498                       length,
499                       callback,
500                       context
501                 );
502
503         transfer->transfer_flags = USB_ASYNC_UNLINK;
504         transfer->status = 0;
505
506         res = usb_submit_urb( transfer );
507         if ( res ) {
508                 MTS_INT_ERROR( "could not submit URB! Error was %d\n",(int)res );
509                 context->srb->result = DID_ERROR << 16;
510                 mts_transfer_cleanup(transfer);
511         }
512         return;
513 }
514
515
516 static void mts_transfer_cleanup( struct urb *transfer )
517 /* Interrupt context! */
518 {
519         MTS_INT_INIT();
520
521         if ( context->final_callback )
522                 context->final_callback(context->srb);
523         up( &context->instance->lock );
524
525 }
526
527 static void mts_transfer_done( struct urb *transfer )
528 {
529         MTS_INT_INIT();
530
531         context->srb->result &= MTS_SCSI_ERR_MASK;
532         context->srb->result |= (unsigned)context->status<<1;
533
534         mts_transfer_cleanup(transfer);
535
536         return;
537 }
538
539
540 static void mts_get_status( struct urb *transfer )
541 /* Interrupt context! */
542 {
543         MTS_INT_INIT();
544
545         mts_int_submit_urb(transfer,
546                            usb_rcvbulkpipe(context->instance->usb_dev,
547                                            context->instance->ep_response),
548                            &context->status,
549                            1,
550                            mts_transfer_done );
551 }
552
553 static void mts_data_done( struct urb* transfer )
554 /* Interrupt context! */
555 {
556         MTS_INT_INIT();
557
558         if ( context->data_length != transfer->actual_length ) {
559                 context->srb->resid = context->data_length - transfer->actual_length;
560         } else if ( transfer->status ) {
561                 context->srb->result = (transfer->status == -ENOENT ? DID_ABORT : DID_ERROR)<<16;
562         }
563
564         mts_get_status(transfer);
565
566         return;
567 }
568
569
570 static void mts_command_done( struct urb *transfer )
571 /* Interrupt context! */
572 {
573         MTS_INT_INIT();
574
575         if ( transfer->status ) {
576                 if (transfer->status == -ENOENT) {
577                         /* We are being killed */
578                         MTS_DEBUG_GOT_HERE();
579                         context->srb->result = DID_ABORT<<16;
580                 } else {
581                         /* A genuine error has occured */
582                         MTS_DEBUG_GOT_HERE();
583
584                         context->srb->result = DID_ERROR<<16;
585                 }
586                 mts_transfer_cleanup(transfer);
587
588                 return;
589         }
590
591         if ( context->data ) {
592                 mts_int_submit_urb(transfer,
593                                    context->data_pipe,
594                                    context->data,
595                                    context->data_length,
596                                    context->srb->use_sg ? mts_do_sg : mts_data_done);
597         } else mts_get_status(transfer);
598
599         return;
600 }
601
602 static void mts_do_sg (struct urb* transfer)
603 {
604         struct scatterlist * sg;
605         MTS_INT_INIT();
606         
607         MTS_DEBUG("Processing fragment %d of %d\n", context->fragment,context->srb->use_sg);
608
609         if (transfer->status) {
610                 context->srb->result = (transfer->status == -ENOENT ? DID_ABORT : DID_ERROR)<<16;
611                 mts_transfer_cleanup(transfer);
612         }
613
614         sg = context->srb->buffer;
615         context->fragment++;
616         mts_int_submit_urb(transfer,
617                         context->data_pipe,
618                         sg[context->fragment].address,
619                         sg[context->fragment].length,
620                         context->fragment + 1 == context->srb->use_sg ? mts_data_done : mts_do_sg);
621         return;
622 }
623
624 static const u8 mts_read_image_sig[] = { 0x28, 00, 00, 00 };
625 static const u8 mts_read_image_sig_len = 4;
626 static const unsigned char mts_direction[256/8] = {
627         0x28, 0x81, 0x14, 0x14, 0x20, 0x01, 0x90, 0x77,
628         0x0C, 0x20, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00,
629         0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01,
630         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
631 };
632
633
634 #define MTS_DIRECTION_IS_IN(x) ((mts_direction[x>>3] >> (x & 7)) & 1)
635
636 static void
637 mts_build_transfer_context( Scsi_Cmnd *srb, struct mts_desc* desc )
638 {
639         int pipe;
640         struct scatterlist * sg;
641         
642         MTS_DEBUG_GOT_HERE();
643
644         desc->context.instance = desc;
645         desc->context.srb = srb;
646         desc->context.fragment = 0;
647
648         if (!srb->use_sg) {
649                 if ( !srb->bufflen ){
650                         desc->context.data = 0;
651                         desc->context.data_length = 0;
652                         return;
653                 } else {
654                         desc->context.data = srb->buffer;
655                         desc->context.data_length = srb->bufflen;
656                         MTS_DEBUG("length = %d or %d\n",
657                                   srb->request_bufflen, srb->bufflen);
658                 }
659         } else {
660                 MTS_DEBUG("Using scatter/gather\n");
661                 sg = srb->buffer;
662                 desc->context.data = sg[0].address;
663                 desc->context.data_length = sg[0].length;
664         }
665
666
667         /* can't rely on srb->sc_data_direction */
668
669         /* Brutally ripped from usb-storage */
670
671         if ( !memcmp( srb->cmnd, mts_read_image_sig, mts_read_image_sig_len )
672 ) {             pipe = usb_rcvbulkpipe(desc->usb_dev,desc->ep_image);
673                 MTS_DEBUG( "transfering from desc->ep_image == %d\n",
674                            (int)desc->ep_image );
675         } else if ( MTS_DIRECTION_IS_IN(srb->cmnd[0]) ) {
676                         pipe = usb_rcvbulkpipe(desc->usb_dev,desc->ep_response);
677                         MTS_DEBUG( "transfering from desc->ep_response == %d\n",
678                                    (int)desc->ep_response);
679         } else {
680                 MTS_DEBUG("transfering to desc->ep_out == %d\n",
681                           (int)desc->ep_out);
682                 pipe = usb_sndbulkpipe(desc->usb_dev,desc->ep_out);
683         }
684         desc->context.data_pipe = pipe;
685 }
686
687
688 static
689 int mts_scsi_queuecommand( Scsi_Cmnd *srb, mts_scsi_cmnd_callback callback )
690 {
691         struct mts_desc* desc = (struct mts_desc*)(srb->host->hostdata[0]);
692         int err = 0;
693         int res;
694
695         MTS_DEBUG_GOT_HERE();
696         mts_show_command(srb);
697         mts_debug_dump(desc);
698
699         if ( srb->device->lun || srb->device->id || srb->device->channel ) {
700
701                 MTS_DEBUG("Command to LUN=%d ID=%d CHANNEL=%d from SCSI layer\n",(int)srb->device->lun,(int)srb->device->id, (int)srb->device->channel );
702
703                 MTS_DEBUG("this device doesn't exist\n");
704
705                 srb->result = DID_BAD_TARGET << 16;
706
707                 if(callback)
708                         callback(srb);
709
710                 goto out;
711         }
712
713         down(&desc->lock);
714         
715         FILL_BULK_URB(&desc->urb,
716                       desc->usb_dev,
717                       usb_sndbulkpipe(desc->usb_dev,desc->ep_out),
718                       srb->cmnd,
719                       srb->cmd_len,
720                       mts_command_done,
721                       &desc->context
722                       );
723
724
725         mts_build_transfer_context( srb, desc );
726         desc->context.final_callback = callback;
727         
728         res=usb_submit_urb(&desc->urb);
729
730         if(res){
731                 MTS_ERROR("error %d submitting URB\n",(int)res);
732                 srb->result = DID_ERROR << 16;
733
734                 if(callback)
735                         callback(srb);
736                 up(&desc->lock);
737
738         }
739
740 out:
741         return err;
742 }
743 /*
744  * this defines our 'host'
745  */
746
747 /* NOTE: This is taken from usb-storage, should be right. */
748
749
750 static Scsi_Host_Template mts_scsi_host_template = {
751         name:           "microtekX6",
752         detect:         mts_scsi_detect,
753         release:        mts_scsi_release,
754         queuecommand:   mts_scsi_queuecommand,
755
756         eh_abort_handler:       mts_scsi_abort,
757         eh_host_reset_handler:  mts_scsi_host_reset,
758
759         sg_tablesize:           SG_ALL,
760         can_queue:              1,
761         this_id:                -1,
762         cmd_per_lun:            1,
763         present:                0,
764         unchecked_isa_dma:      FALSE,
765         use_clustering:         TRUE,
766         use_new_eh_code:        TRUE,
767         emulated:               TRUE
768 };
769
770
771 /* USB layer driver interface implementation */
772
773 static void mts_usb_disconnect (struct usb_device *dev, void *ptr)
774 {
775         struct mts_desc* to_remove = (struct mts_desc*)ptr;
776
777         MTS_DEBUG_GOT_HERE();
778
779         /* leave the list - lock it */
780         down(&mts_list_semaphore);
781
782         mts_remove_nolock(to_remove);
783
784         up(&mts_list_semaphore);
785 }
786
787 struct vendor_product
788 {
789         char* name;
790         enum
791         {
792                 mts_sup_unknown=0,
793                 mts_sup_alpha,
794                 mts_sup_full
795         }
796         support_status;
797 } ;
798
799
800 /* These are taken from the msmUSB.inf file on the Windows driver CD */
801 const static struct vendor_product mts_supported_products[] =
802 {
803         { "Phantom 336CX",      mts_sup_unknown},
804         { "Phantom 336CX",      mts_sup_unknown},
805         { "Scanmaker X6",       mts_sup_alpha},
806         { "Phantom C6",         mts_sup_unknown},
807         { "Phantom 336CX",      mts_sup_unknown},
808         { "ScanMaker V6USL",    mts_sup_unknown},
809         { "ScanMaker V6USL",    mts_sup_unknown},
810         { "Scanmaker V6UL",     mts_sup_unknown},
811         { "Scanmaker V6UPL",    mts_sup_alpha},
812 };
813
814 /* The entries of microtek_table must correspond, line-by-line to
815    the entries of mts_supported_products[]. */
816
817 static struct usb_device_id mts_usb_ids [] =
818 {
819         { USB_DEVICE(0x4ce, 0x0300) },
820         { USB_DEVICE(0x5da, 0x0094) },
821         { USB_DEVICE(0x5da, 0x0099) },
822         { USB_DEVICE(0x5da, 0x009a) },
823         { USB_DEVICE(0x5da, 0x00a0) },
824         { USB_DEVICE(0x5da, 0x00a3) },
825         { USB_DEVICE(0x5da, 0x80a3) },
826         { USB_DEVICE(0x5da, 0x80ac) },
827         { USB_DEVICE(0x5da, 0x00b6) },
828         { }                                             /* Terminating entry */
829 };
830
831 MODULE_DEVICE_TABLE (usb, mts_usb_ids);
832
833
834 static void * mts_usb_probe (struct usb_device *dev, unsigned int interface,
835                              const struct usb_device_id *id)
836 {
837         int i;
838         int result;
839         int ep_out = -1;
840         int ep_in_set[3]; /* this will break if we have more than three endpoints
841                            which is why we check */
842         int *ep_in_current = ep_in_set;
843
844         struct mts_desc * new_desc;
845         struct vendor_product const* p;
846
847         /* the altsettting 0 on the interface we're probing */
848         struct usb_interface_descriptor *altsetting;
849
850         MTS_DEBUG_GOT_HERE();
851         MTS_DEBUG( "usb-device descriptor at %x\n", (int)dev );
852
853         MTS_DEBUG( "product id = 0x%x, vendor id = 0x%x\n",
854                    (int)dev->descriptor.idProduct,
855                    (int)dev->descriptor.idVendor );
856
857         MTS_DEBUG_GOT_HERE();
858
859         p = &mts_supported_products[id - mts_usb_ids];
860
861         MTS_DEBUG_GOT_HERE();
862
863         MTS_DEBUG( "found model %s\n", p->name );
864         if ( p->support_status != mts_sup_full )
865                 MTS_MESSAGE( "model %s is not known to be fully supported, reports welcome!\n",
866                              p->name );
867
868         /* the altsettting 0 on the interface we're probing */
869         altsetting =
870                 &(dev->actconfig->interface[interface].altsetting[0]);
871
872
873         /* Check if the config is sane */
874
875         if ( altsetting->bNumEndpoints != MTS_EP_TOTAL ) {
876                 MTS_WARNING( "expecting %d got %d endpoints! Bailing out.\n",
877                              (int)MTS_EP_TOTAL, (int)altsetting->bNumEndpoints );
878                 return NULL;
879         }
880
881         for( i = 0; i < altsetting->bNumEndpoints; i++ ) {
882                 if ((altsetting->endpoint[i].bmAttributes &
883                      USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_BULK) {
884
885                         MTS_WARNING( "can only deal with bulk endpoints; endpoint %d is not bulk.\n",
886                              (int)altsetting->endpoint[i].bEndpointAddress );
887                 } else {
888                         if (altsetting->endpoint[i].bEndpointAddress &
889                             USB_DIR_IN)
890                                 *ep_in_current++
891                                         = altsetting->endpoint[i].bEndpointAddress &
892                                         USB_ENDPOINT_NUMBER_MASK;
893                         else {
894                                 if ( ep_out != -1 ) {
895                                         MTS_WARNING( "can only deal with one output endpoints. Bailing out." );
896                                         return NULL;
897                                 }
898
899                                 ep_out = altsetting->endpoint[i].bEndpointAddress &
900                                         USB_ENDPOINT_NUMBER_MASK;
901                         }
902                 }
903
904         }
905
906
907         if ( ep_out == -1 ) {
908                 MTS_WARNING( "couldn't find an output bulk endpoint. Bailing out.\n" );
909                 return NULL;
910         }
911
912
913         /* I don't understand the following fully (it's from usb-storage) -- John */
914
915         /* set the interface -- STALL is an acceptable response here */
916         result = usb_set_interface(dev, altsetting->bInterfaceNumber, 0);
917
918         MTS_DEBUG("usb_set_interface returned %d.\n",result);
919         switch( result )
920         {
921         case 0: /* no error */
922                 break;
923                 
924         case -EPIPE:
925                 usb_clear_halt(dev, usb_sndctrlpipe(dev, 0));
926                 MTS_DEBUG( "clearing clearing stall on control interface\n" );
927                 break;
928                 
929         default:
930                 MTS_DEBUG( "unknown error %d from usb_set_interface\n",
931                         (int)result );
932                 return NULL;
933         }
934         
935         
936         /* allocating a new descriptor */
937         new_desc = (struct mts_desc *)kmalloc(sizeof(struct mts_desc), GFP_KERNEL);
938         if (new_desc == NULL)
939         {
940                 MTS_ERROR("couldn't allocate scanner desc, bailing out!\n");
941                 return NULL;
942         }
943
944         /* As done by usb_alloc_urb */
945         memset( new_desc, 0, sizeof(*new_desc) );
946         spin_lock_init(&new_desc->urb.lock);
947         
948                 
949         /* initialising that descriptor */
950         new_desc->usb_dev = dev;
951         new_desc->interface = interface;
952
953         init_MUTEX(&new_desc->lock);
954
955         if(mts_list){
956                 new_desc->host_number = mts_list->host_number+1;
957         } else {
958                 new_desc->host_number = 0;
959         }
960         
961         /* endpoints */
962         
963         new_desc->ep_out = ep_out;
964         new_desc->ep_response = ep_in_set[0];
965         new_desc->ep_image = ep_in_set[1];
966
967
968         if ( new_desc->ep_out != MTS_EP_OUT )
969                 MTS_WARNING( "will this work? Command EP is not usually %d\n",
970                              (int)new_desc->ep_out );
971
972         if ( new_desc->ep_response != MTS_EP_RESPONSE )
973                 MTS_WARNING( "will this work? Response EP is not usually %d\n",
974                              (int)new_desc->ep_response );
975
976         if ( new_desc->ep_image != MTS_EP_IMAGE )
977                 MTS_WARNING( "will this work? Image data EP is not usually %d\n",
978                              (int)new_desc->ep_image );
979
980
981         /* Initialize the host template based on the default one */
982         memcpy(&(new_desc->ctempl), &mts_scsi_host_template, sizeof(mts_scsi_host_template));
983         /* HACK from usb-storage - this is needed for scsi detection */
984         (struct mts_desc *)new_desc->ctempl.proc_dir = new_desc; /* FIXME */
985
986         MTS_DEBUG("registering SCSI module\n");
987
988         new_desc->ctempl.module = THIS_MODULE;
989         result = scsi_register_module(MODULE_SCSI_HA, &(new_desc->ctempl));
990         /* Will get hit back in microtek_detect by this func */
991         if ( result )
992         {
993                 MTS_ERROR( "error %d from scsi_register_module! Help!\n",
994                            (int)result );
995
996                 /* FIXME: need more cleanup? */
997                 kfree( new_desc );
998                 return NULL;
999         }
1000         MTS_DEBUG_GOT_HERE();
1001
1002         /* FIXME: the bomb is armed, must the host be registered under lock ? */
1003         /* join the list - lock it */
1004         down(&mts_list_semaphore);
1005
1006         mts_add_nolock( new_desc );
1007
1008         up(&mts_list_semaphore);
1009
1010
1011         MTS_DEBUG("completed probe and exiting happily\n");
1012
1013         return (void *)new_desc;
1014 }
1015
1016
1017
1018 /* get us noticed by the rest of the kernel */
1019
1020 int __init microtek_drv_init(void)
1021 {
1022         int result;
1023
1024         MTS_DEBUG_GOT_HERE();
1025         init_MUTEX(&mts_list_semaphore);
1026
1027         if ((result = usb_register(&mts_usb_driver)) < 0) {
1028                 MTS_DEBUG("usb_register returned %d\n", result );
1029                 return -1;
1030         } else {
1031                 MTS_DEBUG("driver registered.\n");
1032         }
1033
1034         info(DRIVER_VERSION ":" DRIVER_DESC);
1035
1036         return 0;
1037 }
1038
1039 void __exit microtek_drv_exit(void)
1040 {
1041         struct mts_desc* next;
1042
1043         MTS_DEBUG_GOT_HERE();
1044
1045         usb_deregister(&mts_usb_driver);
1046
1047         down(&mts_list_semaphore);
1048
1049         while (mts_list) {
1050                 /* keep track of where the next one is */
1051                 next = mts_list->next;
1052
1053                 mts_remove_nolock( mts_list );
1054
1055                 /* advance the list pointer */
1056                 mts_list = next;
1057         }
1058
1059         up(&mts_list_semaphore);
1060 }
1061
1062 module_init(microtek_drv_init);
1063 module_exit(microtek_drv_exit);
1064
1065 MODULE_AUTHOR( DRIVER_AUTHOR );
1066 MODULE_DESCRIPTION( DRIVER_DESC );
1067 MODULE_LICENSE("GPL");
1068