Fedora kernel-2.6.17-1.2142_FC4
[linux-2.6.git] / drivers / xen / usbback / usbback.c
1 /******************************************************************************
2  * arch/xen/drivers/usbif/backend/main.c
3  * 
4  * Backend for the Xen virtual USB driver - provides an abstraction of a
5  * USB host controller to the corresponding frontend driver.
6  *
7  * by Mark Williamson
8  * Copyright (c) 2004 Intel Research Cambridge
9  * Copyright (c) 2004, 2005 Mark Williamson
10  *
11  * Based on arch/xen/drivers/blkif/backend/main.c
12  * Copyright (c) 2003-2004, Keir Fraser & Steve Hand
13  */
14
15 #include "common.h"
16
17
18 #include <linux/list.h>
19 #include <linux/usb.h>
20 #include <linux/spinlock.h>
21 #include <linux/module.h>
22 #include <linux/tqueue.h>
23
24 /*
25  * This is rather arbitrary.
26  */
27 #define MAX_PENDING_REQS 4
28 #define BATCH_PER_DOMAIN 1
29
30 static unsigned long mmap_vstart;
31
32 /* Needs to be sufficiently large that we can map the (large) buffers
33  * the USB mass storage driver wants. */
34 #define MMAP_PAGES_PER_REQUEST \
35     (128)
36 #define MMAP_PAGES             \
37     (MAX_PENDING_REQS * MMAP_PAGES_PER_REQUEST)
38
39 #define MMAP_VADDR(_req,_seg)                        \
40     (mmap_vstart +                                   \
41      ((_req) * MMAP_PAGES_PER_REQUEST * PAGE_SIZE) + \
42      ((_seg) * PAGE_SIZE))
43
44
45 static spinlock_t owned_ports_lock;
46 LIST_HEAD(owned_ports);
47
48 /* A list of these structures is used to track ownership of physical USB
49  * ports. */
50 typedef struct 
51 {
52     usbif_priv_t     *usbif_priv;
53     char             path[16];
54     int               guest_port;
55     int enabled;
56     struct list_head  list;
57     unsigned long guest_address; /* The USB device address that has been
58                                   * assigned by the guest. */
59     int               dev_present; /* Is there a device present? */
60     struct usb_device * dev;
61     unsigned long ifaces;  /* What interfaces are present on this device? */
62 } owned_port_t;
63
64
65 /*
66  * Each outstanding request that we've passed to the lower device layers has a
67  * 'pending_req' allocated to it.  The request is complete, the specified
68  * domain has a response queued for it, with the saved 'id' passed back.
69  */
70 typedef struct {
71     usbif_priv_t       *usbif_priv;
72     unsigned long      id;
73     int                nr_pages;
74     unsigned short     operation;
75     int                status;
76 } pending_req_t;
77
78 /*
79  * We can't allocate pending_req's in order, since they may complete out of 
80  * order. We therefore maintain an allocation ring. This ring also indicates 
81  * when enough work has been passed down -- at that point the allocation ring 
82  * will be empty.
83  */
84 static pending_req_t pending_reqs[MAX_PENDING_REQS];
85 static unsigned char pending_ring[MAX_PENDING_REQS];
86 static spinlock_t pend_prod_lock;
87
88 /* NB. We use a different index type to differentiate from shared usb rings. */
89 typedef unsigned int PEND_RING_IDX;
90 #define MASK_PEND_IDX(_i) ((_i)&(MAX_PENDING_REQS-1))
91 static PEND_RING_IDX pending_prod, pending_cons;
92 #define NR_PENDING_REQS (MAX_PENDING_REQS - pending_prod + pending_cons)
93
94 static int do_usb_io_op(usbif_priv_t *usbif, int max_to_do);
95 static void make_response(usbif_priv_t *usbif, unsigned long id, 
96                           unsigned short op, int st, int inband,
97                           unsigned long actual_length);
98 static void dispatch_usb_probe(usbif_priv_t *up, unsigned long id, unsigned long port);
99 static void dispatch_usb_io(usbif_priv_t *up, usbif_request_t *req);    
100 static void dispatch_usb_reset(usbif_priv_t *up, unsigned long portid);
101 static owned_port_t *usbif_find_port(char *);
102
103 /******************************************************************
104  * PRIVATE DEBUG FUNCTIONS
105  */
106
107 #undef DEBUG
108 #ifdef DEBUG
109
110 static void dump_port(owned_port_t *p)
111 {
112     printk(KERN_DEBUG "owned_port_t @ %p\n"
113            "  usbif_priv @ %p\n"
114            "  path: %s\n"
115            "  guest_port: %d\n"
116            "  guest_address: %ld\n"
117            "  dev_present: %d\n"
118            "  dev @ %p\n"
119            "  ifaces: 0x%lx\n",
120            p, p->usbif_priv, p->path, p->guest_port, p->guest_address,
121            p->dev_present, p->dev, p->ifaces);
122 }
123
124
125 static void dump_request(usbif_request_t *req)
126 {    
127     printk(KERN_DEBUG "id = 0x%lx\n"
128            "devnum %d\n"
129            "endpoint 0x%x\n"
130            "direction %d\n"
131            "speed %d\n"
132            "pipe_type 0x%x\n"
133            "transfer_buffer 0x%lx\n"
134            "length 0x%lx\n"
135            "transfer_flags 0x%lx\n"
136            "setup = { 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x }\n"
137            "iso_schedule = 0x%lx\n"
138            "num_iso %ld\n",
139            req->id, req->devnum, req->endpoint, req->direction, req->speed,
140            req->pipe_type, req->transfer_buffer, req->length,
141            req->transfer_flags, req->setup[0], req->setup[1], req->setup[2],
142            req->setup[3], req->setup[4], req->setup[5], req->setup[6],
143            req->setup[7], req->iso_schedule, req->num_iso);
144 }
145
146 static void dump_urb(struct urb *urb)
147 {
148     printk(KERN_DEBUG "dumping urb @ %p\n", urb);
149
150 #define DUMP_URB_FIELD(name, format) \
151     printk(KERN_DEBUG "  " # name " " format "\n", urb-> name)
152     
153     DUMP_URB_FIELD(pipe, "0x%x");
154     DUMP_URB_FIELD(status, "%d");
155     DUMP_URB_FIELD(transfer_flags, "0x%x");    
156     DUMP_URB_FIELD(transfer_buffer, "%p");
157     DUMP_URB_FIELD(transfer_buffer_length, "%d");
158     DUMP_URB_FIELD(actual_length, "%d");
159 }
160
161 static void dump_response(usbif_response_t *resp)
162 {
163     printk(KERN_DEBUG "usbback: Sending response:\n"
164            "         id = 0x%x\n"
165            "         op = %d\n"
166            "         status = %d\n"
167            "         data = %d\n"
168            "         length = %d\n",
169            resp->id, resp->op, resp->status, resp->data, resp->length);
170 }
171
172 #else /* DEBUG */
173
174 #define dump_port(blah)     ((void)0)
175 #define dump_request(blah)   ((void)0)
176 #define dump_urb(blah)      ((void)0)
177 #define dump_response(blah) ((void)0)
178
179 #endif /* DEBUG */
180
181 /******************************************************************
182  * MEMORY MANAGEMENT
183  */
184
185 static void fast_flush_area(int idx, int nr_pages)
186 {
187     multicall_entry_t mcl[MMAP_PAGES_PER_REQUEST];
188     int               i;
189
190     for ( i = 0; i < nr_pages; i++ )
191     {
192         mcl[i].op = __HYPERVISOR_update_va_mapping;
193         mcl[i].args[0] = MMAP_VADDR(idx, i);
194         mcl[i].args[1] = 0;
195         mcl[i].args[2] = 0;
196     }
197
198     mcl[nr_pages-1].args[2] = UVMF_TLB_FLUSH|UVMF_ALL;
199     if ( unlikely(HYPERVISOR_multicall(mcl, nr_pages) != 0) )
200         BUG();
201 }
202
203
204 /******************************************************************
205  * USB INTERFACE SCHEDULER LIST MAINTENANCE
206  */
207
208 static struct list_head usbio_schedule_list;
209 static spinlock_t usbio_schedule_list_lock;
210
211 static int __on_usbif_list(usbif_priv_t *up)
212 {
213     return up->usbif_list.next != NULL;
214 }
215
216 void remove_from_usbif_list(usbif_priv_t *up)
217 {
218     unsigned long flags;
219     if ( !__on_usbif_list(up) ) return;
220     spin_lock_irqsave(&usbio_schedule_list_lock, flags);
221     if ( __on_usbif_list(up) )
222     {
223         list_del(&up->usbif_list);
224         up->usbif_list.next = NULL;
225         usbif_put(up);
226     }
227     spin_unlock_irqrestore(&usbio_schedule_list_lock, flags);
228 }
229
230 static void add_to_usbif_list_tail(usbif_priv_t *up)
231 {
232     unsigned long flags;
233     if ( __on_usbif_list(up) ) return;
234     spin_lock_irqsave(&usbio_schedule_list_lock, flags);
235     if ( !__on_usbif_list(up) && (up->status == CONNECTED) )
236     {
237         list_add_tail(&up->usbif_list, &usbio_schedule_list);
238         usbif_get(up);
239     }
240     spin_unlock_irqrestore(&usbio_schedule_list_lock, flags);
241 }
242
243 void free_pending(int pending_idx)
244 {
245     unsigned long flags;
246
247     /* Free the pending request. */
248     spin_lock_irqsave(&pend_prod_lock, flags);
249     pending_ring[MASK_PEND_IDX(pending_prod++)] = pending_idx;
250     spin_unlock_irqrestore(&pend_prod_lock, flags);
251 }
252
253 /******************************************************************
254  * COMPLETION CALLBACK -- Called as urb->complete()
255  */
256
257 static void maybe_trigger_usbio_schedule(void);
258
259 static void __end_usb_io_op(struct urb *purb)
260 {
261     pending_req_t *pending_req;
262     int pending_idx;
263
264     pending_req = purb->context;
265
266     pending_idx = pending_req - pending_reqs;
267
268     ASSERT(purb->actual_length <= purb->transfer_buffer_length);
269     ASSERT(purb->actual_length <= pending_req->nr_pages * PAGE_SIZE);
270     
271     /* An error fails the entire request. */
272     if ( purb->status )
273     {
274         printk(KERN_WARNING "URB @ %p failed. Status %d\n", purb, purb->status);
275     }
276
277     if ( usb_pipetype(purb->pipe) == 0 )
278     {
279         int i;
280         usbif_iso_t *sched = (usbif_iso_t *)MMAP_VADDR(pending_idx, pending_req->nr_pages - 1);
281
282         /* If we're dealing with an iso pipe, we need to copy back the schedule. */
283         for ( i = 0; i < purb->number_of_packets; i++ )
284         {
285             sched[i].length = purb->iso_frame_desc[i].actual_length;
286             ASSERT(sched[i].buffer_offset ==
287                    purb->iso_frame_desc[i].offset);
288             sched[i].status = purb->iso_frame_desc[i].status;
289         }
290     }
291     
292     fast_flush_area(pending_req - pending_reqs, pending_req->nr_pages);
293
294     kfree(purb->setup_packet);
295
296     make_response(pending_req->usbif_priv, pending_req->id,
297                   pending_req->operation, pending_req->status, 0, purb->actual_length);
298     usbif_put(pending_req->usbif_priv);
299
300     usb_free_urb(purb);
301
302     free_pending(pending_idx);
303     
304     rmb();
305
306     /* Check for anything still waiting in the rings, having freed a request... */
307     maybe_trigger_usbio_schedule();
308 }
309
310 /******************************************************************
311  * SCHEDULER FUNCTIONS
312  */
313
314 static DECLARE_WAIT_QUEUE_HEAD(usbio_schedule_wait);
315
316 static int usbio_schedule(void *arg)
317 {
318     DECLARE_WAITQUEUE(wq, current);
319
320     usbif_priv_t          *up;
321     struct list_head *ent;
322
323     daemonize();
324
325     for ( ; ; )
326     {
327         /* Wait for work to do. */
328         add_wait_queue(&usbio_schedule_wait, &wq);
329         set_current_state(TASK_INTERRUPTIBLE);
330         if ( (NR_PENDING_REQS == MAX_PENDING_REQS) || 
331              list_empty(&usbio_schedule_list) )
332             schedule();
333         __set_current_state(TASK_RUNNING);
334         remove_wait_queue(&usbio_schedule_wait, &wq);
335
336         /* Queue up a batch of requests. */
337         while ( (NR_PENDING_REQS < MAX_PENDING_REQS) &&
338                 !list_empty(&usbio_schedule_list) )
339         {
340             ent = usbio_schedule_list.next;
341             up = list_entry(ent, usbif_priv_t, usbif_list);
342             usbif_get(up);
343             remove_from_usbif_list(up);
344             if ( do_usb_io_op(up, BATCH_PER_DOMAIN) )
345                 add_to_usbif_list_tail(up);
346             usbif_put(up);
347         }
348     }
349 }
350
351 static void maybe_trigger_usbio_schedule(void)
352 {
353     /*
354      * Needed so that two processes, who together make the following predicate
355      * true, don't both read stale values and evaluate the predicate
356      * incorrectly. Incredibly unlikely to stall the scheduler on x86, but...
357      */
358     smp_mb();
359
360     if ( !list_empty(&usbio_schedule_list) )
361         wake_up(&usbio_schedule_wait);
362 }
363
364
365 /******************************************************************************
366  * NOTIFICATION FROM GUEST OS.
367  */
368
369 irqreturn_t usbif_be_int(int irq, void *dev_id, struct pt_regs *regs)
370 {
371     usbif_priv_t *up = dev_id;
372
373     smp_mb();
374
375     add_to_usbif_list_tail(up); 
376
377     /* Will in fact /always/ trigger an io schedule in this case. */
378     maybe_trigger_usbio_schedule();
379
380     return IRQ_HANDLED;
381 }
382
383
384
385 /******************************************************************
386  * DOWNWARD CALLS -- These interface with the usb-device layer proper.
387  */
388
389 static int do_usb_io_op(usbif_priv_t *up, int max_to_do)
390 {
391     usbif_back_ring_t *usb_ring = &up->usb_ring;
392     usbif_request_t *req;
393     RING_IDX i, rp;
394     int more_to_do = 0;
395
396     rp = usb_ring->sring->req_prod;
397     rmb(); /* Ensure we see queued requests up to 'rp'. */
398     
399     /* Take items off the comms ring, taking care not to overflow. */
400     for ( i = usb_ring->req_cons; 
401           (i != rp) && !RING_REQUEST_CONS_OVERFLOW(usb_ring, i);
402           i++ )
403     {
404         if ( (max_to_do-- == 0) || (NR_PENDING_REQS == MAX_PENDING_REQS) )
405         {
406             more_to_do = 1;
407             break;
408         }
409
410         req = RING_GET_REQUEST(usb_ring, i);
411         
412         switch ( req->operation )
413         {
414         case USBIF_OP_PROBE:
415             dispatch_usb_probe(up, req->id, req->port);
416             break;
417
418         case USBIF_OP_IO:
419           /* Assemble an appropriate URB. */
420           dispatch_usb_io(up, req);
421           break;
422
423         case USBIF_OP_RESET:
424           dispatch_usb_reset(up, req->port);
425           break;
426
427         default:
428             DPRINTK("error: unknown USB io operation [%d]\n",
429                     req->operation);
430             make_response(up, req->id, req->operation, -EINVAL, 0, 0);
431             break;
432         }
433     }
434
435     usb_ring->req_cons = i;
436
437     return more_to_do;
438 }
439
440 static owned_port_t *find_guest_port(usbif_priv_t *up, int port)
441 {
442     unsigned long flags;
443     struct list_head *l;
444
445     spin_lock_irqsave(&owned_ports_lock, flags);
446     list_for_each(l, &owned_ports)
447     {
448         owned_port_t *p = list_entry(l, owned_port_t, list);
449         if(p->usbif_priv == up && p->guest_port == port)
450         {
451             spin_unlock_irqrestore(&owned_ports_lock, flags);
452             return p;
453         }
454     }
455     spin_unlock_irqrestore(&owned_ports_lock, flags);
456
457     return NULL;
458 }
459
460 static void dispatch_usb_reset(usbif_priv_t *up, unsigned long portid)
461 {
462     owned_port_t *port = find_guest_port(up, portid);
463     int ret = 0;
464
465
466     /* Allowing the guest to actually reset the device causes more problems
467      * than it's worth.  We just fake it out in software but we will do a real
468      * reset when the interface is destroyed. */
469
470     dump_port(port);
471
472     port->guest_address = 0;
473     /* If there's an attached device then the port is now enabled. */
474     if ( port->dev_present )
475         port->enabled = 1;
476     else
477         port->enabled = 0;
478
479     make_response(up, 0, USBIF_OP_RESET, ret, 0, 0);
480 }
481
482 static void dispatch_usb_probe(usbif_priv_t *up, unsigned long id, unsigned long portid)
483 {
484     owned_port_t *port = find_guest_port(up, portid);
485     int ret;
486  
487     if ( port != NULL )
488         ret = port->dev_present;
489     else
490     {
491         ret = -EINVAL;
492         printk(KERN_INFO "dispatch_usb_probe(): invalid port probe request "
493                "(port %ld)\n", portid);
494     }
495
496     /* Probe result is sent back in-band.  Probes don't have an associated id
497      * right now... */
498     make_response(up, id, USBIF_OP_PROBE, ret, portid, 0);
499 }
500
501 /**
502  * check_iso_schedule - safety check the isochronous schedule for an URB
503  * @purb : the URB in question
504  */
505 static int check_iso_schedule(struct urb *purb)
506 {
507     int i;
508     unsigned long total_length = 0;
509     
510     for ( i = 0; i < purb->number_of_packets; i++ )
511     {
512         struct usb_iso_packet_descriptor *desc = &purb->iso_frame_desc[i];
513         
514         if ( desc->offset >= purb->transfer_buffer_length
515             || ( desc->offset + desc->length) > purb->transfer_buffer_length )
516             return -EINVAL;
517
518         total_length += desc->length;
519
520         if ( total_length > purb->transfer_buffer_length )
521             return -EINVAL;
522     }
523     
524     return 0;
525 }
526
527 owned_port_t *find_port_for_request(usbif_priv_t *up, usbif_request_t *req);
528
529 static void dispatch_usb_io(usbif_priv_t *up, usbif_request_t *req)
530 {
531     unsigned long buffer_mach;
532     int i = 0, offset = 0,
533         pending_idx = pending_ring[MASK_PEND_IDX(pending_cons)];
534     pending_req_t *pending_req;
535     unsigned long  remap_prot;
536     multicall_entry_t mcl[MMAP_PAGES_PER_REQUEST];
537     struct urb *purb = NULL;
538     owned_port_t *port;
539     unsigned char *setup;    
540
541     dump_request(req);
542
543     if ( NR_PENDING_REQS == MAX_PENDING_REQS )
544     {
545         printk(KERN_WARNING "usbback: Max requests already queued. "
546                "Giving up!\n");
547         
548         return;
549     }
550
551     port = find_port_for_request(up, req);
552
553     if ( port == NULL )
554     {
555         printk(KERN_WARNING "No such device! (%d)\n", req->devnum);
556         dump_request(req);
557
558         make_response(up, req->id, req->operation, -ENODEV, 0, 0);
559         return;
560     }
561     else if ( !port->dev_present )
562     {
563         /* In normal operation, we'll only get here if a device is unplugged
564          * and the frontend hasn't noticed yet. */
565         make_response(up, req->id, req->operation, -ENODEV, 0, 0);
566         return;
567     }
568         
569
570     setup = kmalloc(8, GFP_KERNEL);
571
572     if ( setup == NULL )
573         goto no_mem;
574    
575     /* Copy request out for safety. */
576     memcpy(setup, req->setup, 8);
577
578     if( setup[0] == 0x0 && setup[1] == 0x5)
579     {
580         /* To virtualise the USB address space, we need to intercept
581          * set_address messages and emulate.  From the USB specification:
582          * bmRequestType = 0x0;
583          * Brequest = SET_ADDRESS (i.e. 0x5)
584          * wValue = device address
585          * wIndex = 0
586          * wLength = 0
587          * data = None
588          */
589         /* Store into the guest transfer buffer using cpu_to_le16 */
590         port->guest_address = le16_to_cpu(*(u16 *)(setup + 2));
591         /* Make a successful response.  That was easy! */
592
593         make_response(up, req->id, req->operation, 0, 0, 0);
594
595         kfree(setup);
596         return;
597     }
598     else if ( setup[0] == 0x0 && setup[1] == 0x9 )
599     {
600         /* The host kernel needs to know what device configuration is in use
601          * because various error checks get confused otherwise.  We just do
602          * configuration settings here, under controlled conditions.
603          */
604
605       /* Ignore configuration setting and hope that the host kernel
606          did it right. */
607         /* usb_set_configuration(port->dev, setup[2]); */
608
609         make_response(up, req->id, req->operation, 0, 0, 0);
610
611         kfree(setup);
612         return;
613     }
614     else if ( setup[0] == 0x1 && setup[1] == 0xB )
615     {
616         /* The host kernel needs to know what device interface is in use
617          * because various error checks get confused otherwise.  We just do
618          * configuration settings here, under controlled conditions.
619          */
620         usb_set_interface(port->dev, (setup[4] | setup[5] << 8),
621                           (setup[2] | setup[3] << 8) );
622
623         make_response(up, req->id, req->operation, 0, 0, 0);
624
625         kfree(setup);
626         return;
627     }
628
629     if ( ( req->transfer_buffer - (req->transfer_buffer & PAGE_MASK)
630            + req->length )
631          > MMAP_PAGES_PER_REQUEST * PAGE_SIZE )
632     {
633         printk(KERN_WARNING "usbback: request of %lu bytes too large\n",
634                req->length);
635         make_response(up, req->id, req->operation, -EINVAL, 0, 0);
636         kfree(setup);
637         return;
638     }
639     
640     buffer_mach = req->transfer_buffer;
641
642     if( buffer_mach == 0 )
643         goto no_remap;
644
645     ASSERT((req->length >> PAGE_SHIFT) <= MMAP_PAGES_PER_REQUEST);
646     ASSERT(buffer_mach);
647
648     /* Always map writeable for now. */
649     remap_prot = _PAGE_PRESENT|_PAGE_DIRTY|_PAGE_ACCESSED|_PAGE_RW;
650
651     for ( i = 0, offset = 0; offset < req->length;
652           i++, offset += PAGE_SIZE )
653     {
654         mcl[i].op = __HYPERVISOR_update_va_mapping_otherdomain;
655         mcl[i].args[0] = MMAP_VADDR(pending_idx, i);
656         mcl[i].args[1] = ((buffer_mach & PAGE_MASK) + offset) | remap_prot;
657         mcl[i].args[2] = 0;
658         mcl[i].args[3] = up->domid;
659         
660         phys_to_machine_mapping[__pa(MMAP_VADDR(pending_idx, i))>>PAGE_SHIFT] =
661             FOREIGN_FRAME((buffer_mach + offset) >> PAGE_SHIFT);
662
663         ASSERT(virt_to_machine(MMAP_VADDR(pending_idx, i))
664                == buffer_mach + i << PAGE_SHIFT);
665     }
666
667     if ( req->pipe_type == 0 && req->num_iso > 0 ) /* Maybe schedule ISO... */
668     {
669         /* Map in ISO schedule, if necessary. */
670         mcl[i].op = __HYPERVISOR_update_va_mapping_otherdomain;
671         mcl[i].args[0] = MMAP_VADDR(pending_idx, i);
672         mcl[i].args[1] = (req->iso_schedule & PAGE_MASK) | remap_prot;
673         mcl[i].args[2] = 0;
674         mcl[i].args[3] = up->domid;
675
676         phys_to_machine_mapping[__pa(MMAP_VADDR(pending_idx, i))>>PAGE_SHIFT] =
677             FOREIGN_FRAME(req->iso_schedule >> PAGE_SHIFT);
678     
679         i++;
680     }
681
682     if ( unlikely(HYPERVISOR_multicall(mcl, i) != 0) )
683         BUG();
684     
685     {
686         int j;
687         for ( j = 0; j < i; j++ )
688         {
689             if ( unlikely(mcl[j].args[5] != 0) )
690             {
691                 printk(KERN_WARNING
692                        "invalid buffer %d -- could not remap it\n", j);
693                 fast_flush_area(pending_idx, i);
694                 goto bad_descriptor;
695             }
696         }
697     }
698     
699  no_remap:
700
701     ASSERT(i <= MMAP_PAGES_PER_REQUEST);
702     ASSERT(i * PAGE_SIZE >= req->length);
703
704     /* We have to do this because some things might complete out of order. */
705     pending_req = &pending_reqs[pending_idx];
706     pending_req->usbif_priv= up;
707     pending_req->id        = req->id;
708     pending_req->operation = req->operation;
709     pending_req->nr_pages  = i;
710
711     pending_cons++;
712
713     usbif_get(up);
714     
715     /* Fill out an actual request for the USB layer. */
716     purb = usb_alloc_urb(req->num_iso);
717
718     if ( purb == NULL )
719     {
720         usbif_put(up);
721         free_pending(pending_idx);
722         goto no_mem;
723     }
724
725     purb->dev = port->dev;
726     purb->context = pending_req;
727     purb->transfer_buffer =
728         (void *)(MMAP_VADDR(pending_idx, 0) + (buffer_mach & ~PAGE_MASK));
729     if(buffer_mach == 0)
730       purb->transfer_buffer = NULL;
731     purb->complete = __end_usb_io_op;
732     purb->transfer_buffer_length = req->length;
733     purb->transfer_flags = req->transfer_flags;
734
735     purb->pipe = 0;
736     purb->pipe |= req->direction << 7;
737     purb->pipe |= port->dev->devnum << 8;
738     purb->pipe |= req->speed << 26;
739     purb->pipe |= req->pipe_type << 30;
740     purb->pipe |= req->endpoint << 15;
741
742     purb->number_of_packets = req->num_iso;
743
744     if ( purb->number_of_packets * sizeof(usbif_iso_t) > PAGE_SIZE )
745         goto urb_error;
746
747     /* Make sure there's always some kind of timeout. */
748     purb->timeout = ( req->timeout > 0 ) ? (req->timeout * HZ) / 1000
749                     :  1000;
750
751     purb->setup_packet = setup;
752
753     if ( req->pipe_type == 0 ) /* ISO */
754     {
755         int j;
756         usbif_iso_t *iso_sched = (usbif_iso_t *)MMAP_VADDR(pending_idx, i - 1);
757
758         /* If we're dealing with an iso pipe, we need to copy in a schedule. */
759         for ( j = 0; j < purb->number_of_packets; j++ )
760         {
761             purb->iso_frame_desc[j].length = iso_sched[j].length;
762             purb->iso_frame_desc[j].offset = iso_sched[j].buffer_offset;
763             iso_sched[j].status = 0;
764         }
765     }
766
767     if ( check_iso_schedule(purb) != 0 )
768         goto urb_error;
769
770     if ( usb_submit_urb(purb) != 0 )
771         goto urb_error;
772
773     return;
774
775  urb_error:
776     dump_urb(purb);    
777     usbif_put(up);
778     free_pending(pending_idx);
779
780  bad_descriptor:
781     kfree ( setup );
782     if ( purb != NULL )
783         usb_free_urb(purb);
784     make_response(up, req->id, req->operation, -EINVAL, 0, 0);
785     return;
786     
787  no_mem:
788     if ( setup != NULL )
789         kfree(setup);
790     make_response(up, req->id, req->operation, -ENOMEM, 0, 0);
791     return;
792
793
794
795
796 /******************************************************************
797  * MISCELLANEOUS SETUP / TEARDOWN / DEBUGGING
798  */
799
800
801 static void make_response(usbif_priv_t *up, unsigned long id,
802                           unsigned short op, int st, int inband,
803                           unsigned long length)
804 {
805     usbif_response_t *resp;
806     unsigned long     flags;
807     usbif_back_ring_t *usb_ring = &up->usb_ring;
808
809     /* Place on the response ring for the relevant domain. */ 
810     spin_lock_irqsave(&up->usb_ring_lock, flags);
811     resp = RING_GET_RESPONSE(usb_ring, usb_ring->rsp_prod_pvt);
812     resp->id        = id;
813     resp->operation = op;
814     resp->status    = st;
815     resp->data      = inband;
816     resp->length = length;
817     wmb(); /* Ensure other side can see the response fields. */
818
819     dump_response(resp);
820
821     usb_ring->rsp_prod_pvt++;
822     RING_PUSH_RESPONSES(usb_ring);
823     spin_unlock_irqrestore(&up->usb_ring_lock, flags);
824
825     /* Kick the relevant domain. */
826     notify_via_evtchn(up->evtchn);
827 }
828
829 /**
830  * usbif_claim_port - claim devices on a port on behalf of guest
831  *
832  * Once completed, this will ensure that any device attached to that
833  * port is claimed by this driver for use by the guest.
834  */
835 int usbif_claim_port(usbif_be_claim_port_t *msg)
836 {
837     owned_port_t *o_p;
838     
839     /* Sanity... */
840     if ( usbif_find_port(msg->path) != NULL )
841     {
842         printk(KERN_WARNING "usbback: Attempted to claim USB port "
843                "we already own!\n");
844         return -EINVAL;
845     }
846
847     /* No need for a slab cache - this should be infrequent. */
848     o_p = kmalloc(sizeof(owned_port_t), GFP_KERNEL);
849
850     if ( o_p == NULL )
851         return -ENOMEM;
852
853     o_p->enabled = 0;
854     o_p->usbif_priv = usbif_find(msg->domid);
855     o_p->guest_port = msg->usbif_port;
856     o_p->dev_present = 0;
857     o_p->guest_address = 0; /* Default address. */
858
859     strcpy(o_p->path, msg->path);
860
861     spin_lock_irq(&owned_ports_lock);
862     
863     list_add(&o_p->list, &owned_ports);
864
865     spin_unlock_irq(&owned_ports_lock);
866
867     printk(KERN_INFO "usbback: Claimed USB port (%s) for %d.%d\n", o_p->path,
868            msg->domid, msg->usbif_port);
869
870     /* Force a reprobe for unclaimed devices. */
871     usb_scan_devices();
872
873     return 0;
874 }
875
876 owned_port_t *find_port_for_request(usbif_priv_t *up, usbif_request_t *req)
877 {
878     unsigned long flags;
879     struct list_head *port;
880
881     /* I'm assuming this is not called from IRQ context - correct?  I think
882      * it's probably only called in response to control messages or plug events
883      * in the USB hub kernel thread, so should be OK. */
884     spin_lock_irqsave(&owned_ports_lock, flags);
885     list_for_each(port, &owned_ports)
886     {
887         owned_port_t *p = list_entry(port, owned_port_t, list);
888         if(p->usbif_priv == up && p->guest_address == req->devnum && p->enabled )
889           {
890               dump_port(p);
891
892               spin_unlock_irqrestore(&owned_ports_lock, flags);
893               return p;
894           }
895     }
896     spin_unlock_irqrestore(&owned_ports_lock, flags);
897
898     return NULL;    
899 }
900
901 owned_port_t *__usbif_find_port(char *path)
902 {
903     struct list_head *port;
904
905     list_for_each(port, &owned_ports)
906     {
907         owned_port_t *p = list_entry(port, owned_port_t, list);
908         if(!strcmp(path, p->path))
909         {
910             return p;
911         }
912     }
913
914     return NULL;
915 }
916
917 owned_port_t *usbif_find_port(char *path)
918 {
919     owned_port_t *ret;
920     unsigned long flags;
921
922     spin_lock_irqsave(&owned_ports_lock, flags);
923     ret = __usbif_find_port(path);    
924     spin_unlock_irqrestore(&owned_ports_lock, flags);
925
926     return ret;
927 }
928
929
930 static void *probe(struct usb_device *dev, unsigned iface,
931                    const struct usb_device_id *id)
932 {
933     owned_port_t *p;
934
935     /* We don't care what the device is - if we own the port, we want it.  We
936      * don't deal with device-specifics in this driver, so we don't care what
937      * the device actually is ;-) */
938     if ( ( p = usbif_find_port(dev->devpath) ) != NULL )
939     {
940         printk(KERN_INFO "usbback: claimed device attached to owned port\n");
941
942         p->dev_present = 1;
943         p->dev = dev;
944         set_bit(iface, &p->ifaces);
945         
946         return p->usbif_priv;
947     }
948     else
949         printk(KERN_INFO "usbback: hotplug for non-owned port (%s), ignoring\n",
950                dev->devpath);
951    
952
953     return NULL;
954 }
955
956 static void disconnect(struct usb_device *dev, void *usbif)
957 {
958     /* Note the device is removed so we can tell the guest when it probes. */
959     owned_port_t *port = usbif_find_port(dev->devpath);
960     port->dev_present = 0;
961     port->dev = NULL;
962     port->ifaces = 0;
963 }
964
965
966 struct usb_driver driver =
967 {
968     .owner      = THIS_MODULE,
969     .name       = "Xen USB Backend",
970     .probe      = probe,
971     .disconnect = disconnect,
972     .id_table   = NULL,
973 };
974
975 /* __usbif_release_port - internal mechanics for releasing a port */
976 void __usbif_release_port(owned_port_t *p)
977 {
978     int i;
979
980     for ( i = 0; p->ifaces != 0; i++)
981         if ( p->ifaces & 1 << i )
982         {
983             usb_driver_release_interface(&driver, usb_ifnum_to_if(p->dev, i));
984             clear_bit(i, &p->ifaces);
985         }
986     list_del(&p->list);
987
988     /* Reset the real device.  We don't simulate disconnect / probe for other
989      * drivers in this kernel because we assume the device is completely under
990      * the control of ourselves (i.e. the guest!).  This should ensure that the
991      * device is in a sane state for the next customer ;-) */
992
993     /* MAW NB: we're not resetting the real device here.  This looks perfectly
994      * valid to me but it causes memory corruption.  We seem to get away with not
995      * resetting for now, although it'd be nice to have this tracked down. */
996 /*     if ( p->dev != NULL) */
997 /*         usb_reset_device(p->dev); */
998
999     kfree(p);
1000 }
1001
1002
1003 /**
1004  * usbif_release_port - stop claiming devices on a port on behalf of guest
1005  */
1006 void usbif_release_port(usbif_be_release_port_t *msg)
1007 {
1008     owned_port_t *p;
1009
1010     spin_lock_irq(&owned_ports_lock);
1011     p = __usbif_find_port(msg->path);
1012     __usbif_release_port(p);
1013     spin_unlock_irq(&owned_ports_lock);
1014 }
1015
1016 void usbif_release_ports(usbif_priv_t *up)
1017 {
1018     struct list_head *port, *tmp;
1019     unsigned long flags;
1020     
1021     spin_lock_irqsave(&owned_ports_lock, flags);
1022     list_for_each_safe(port, tmp, &owned_ports)
1023     {
1024         owned_port_t *p = list_entry(port, owned_port_t, list);
1025         if ( p->usbif_priv == up )
1026             __usbif_release_port(p);
1027     }
1028     spin_unlock_irqrestore(&owned_ports_lock, flags);
1029 }
1030
1031 static int __init usbif_init(void)
1032 {
1033     int i;
1034
1035     if ( !(xen_start_info.flags & SIF_INITDOMAIN) &&
1036          !(xen_start_info.flags & SIF_USB_BE_DOMAIN) )
1037         return 0;
1038     
1039     if ( (mmap_vstart = allocate_empty_lowmem_region(MMAP_PAGES)) == 0 )
1040         BUG();
1041
1042     pending_cons = 0;
1043     pending_prod = MAX_PENDING_REQS;
1044     memset(pending_reqs, 0, sizeof(pending_reqs));
1045     for ( i = 0; i < MAX_PENDING_REQS; i++ )
1046         pending_ring[i] = i;
1047
1048     spin_lock_init(&pend_prod_lock);
1049
1050     spin_lock_init(&owned_ports_lock);
1051     INIT_LIST_HEAD(&owned_ports);
1052
1053     spin_lock_init(&usbio_schedule_list_lock);
1054     INIT_LIST_HEAD(&usbio_schedule_list);
1055
1056     if ( kernel_thread(usbio_schedule, 0, CLONE_FS | CLONE_FILES) < 0 )
1057         BUG();
1058     
1059     usbif_interface_init();
1060
1061     usbif_ctrlif_init();
1062
1063     usb_register(&driver);
1064
1065     printk(KERN_INFO "Xen USB Backend Initialised");
1066
1067     return 0;
1068 }
1069
1070 __initcall(usbif_init);