ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / usb / core / urb.c
1 #include <linux/config.h>
2 #include <linux/module.h>
3 #include <linux/string.h>
4 #include <linux/bitops.h>
5 #include <linux/slab.h>
6 #include <linux/init.h>
7
8 #ifdef CONFIG_USB_DEBUG
9         #define DEBUG
10 #else
11         #undef DEBUG
12 #endif
13 #include <linux/usb.h>
14 #include "hcd.h"
15
16 /**
17  * usb_init_urb - initializes a urb so that it can be used by a USB driver
18  * @urb: pointer to the urb to initialize
19  *
20  * Initializes a urb so that the USB subsystem can use it properly.
21  *
22  * If a urb is created with a call to usb_alloc_urb() it is not
23  * necessary to call this function.  Only use this if you allocate the
24  * space for a struct urb on your own.  If you call this function, be
25  * careful when freeing the memory for your urb that it is no longer in
26  * use by the USB core.
27  *
28  * Only use this function if you _really_ understand what you are doing.
29  */
30 void usb_init_urb(struct urb *urb)
31 {
32         if (urb) {
33                 memset(urb, 0, sizeof(*urb));
34                 urb->count = (atomic_t)ATOMIC_INIT(1);
35                 spin_lock_init(&urb->lock);
36         }
37 }
38
39 /**
40  * usb_alloc_urb - creates a new urb for a USB driver to use
41  * @iso_packets: number of iso packets for this urb
42  * @mem_flags: the type of memory to allocate, see kmalloc() for a list of
43  *      valid options for this.
44  *
45  * Creates an urb for the USB driver to use, initializes a few internal
46  * structures, incrementes the usage counter, and returns a pointer to it.
47  *
48  * If no memory is available, NULL is returned.
49  *
50  * If the driver want to use this urb for interrupt, control, or bulk
51  * endpoints, pass '0' as the number of iso packets.
52  *
53  * The driver must call usb_free_urb() when it is finished with the urb.
54  */
55 struct urb *usb_alloc_urb(int iso_packets, int mem_flags)
56 {
57         struct urb *urb;
58
59         urb = (struct urb *)kmalloc(sizeof(struct urb) + 
60                 iso_packets * sizeof(struct usb_iso_packet_descriptor),
61                 mem_flags);
62         if (!urb) {
63                 err("alloc_urb: kmalloc failed");
64                 return NULL;
65         }
66         usb_init_urb(urb);
67         return urb;
68 }
69
70 /**
71  * usb_free_urb - frees the memory used by a urb when all users of it are finished
72  * @urb: pointer to the urb to free
73  *
74  * Must be called when a user of a urb is finished with it.  When the last user
75  * of the urb calls this function, the memory of the urb is freed.
76  *
77  * Note: The transfer buffer associated with the urb is not freed, that must be
78  * done elsewhere.
79  */
80 void usb_free_urb(struct urb *urb)
81 {
82         if (urb)
83                 if (atomic_dec_and_test(&urb->count))
84                         kfree(urb);
85 }
86
87 /**
88  * usb_get_urb - increments the reference count of the urb
89  * @urb: pointer to the urb to modify
90  *
91  * This must be  called whenever a urb is transferred from a device driver to a
92  * host controller driver.  This allows proper reference counting to happen
93  * for urbs.
94  *
95  * A pointer to the urb with the incremented reference counter is returned.
96  */
97 struct urb * usb_get_urb(struct urb *urb)
98 {
99         if (urb) {
100                 atomic_inc(&urb->count);
101                 return urb;
102         } else
103                 return NULL;
104 }
105                 
106                 
107 /*-------------------------------------------------------------------*/
108
109 /**
110  * usb_submit_urb - issue an asynchronous transfer request for an endpoint
111  * @urb: pointer to the urb describing the request
112  * @mem_flags: the type of memory to allocate, see kmalloc() for a list
113  *      of valid options for this.
114  *
115  * This submits a transfer request, and transfers control of the URB
116  * describing that request to the USB subsystem.  Request completion will
117  * be indicated later, asynchronously, by calling the completion handler.
118  * The three types of completion are success, error, and unlink
119  * (a software-induced fault, also called "request cancelation").  
120  *
121  * URBs may be submitted in interrupt context.
122  *
123  * The caller must have correctly initialized the URB before submitting
124  * it.  Functions such as usb_fill_bulk_urb() and usb_fill_control_urb() are
125  * available to ensure that most fields are correctly initialized, for
126  * the particular kind of transfer, although they will not initialize
127  * any transfer flags.
128  *
129  * Successful submissions return 0; otherwise this routine returns a
130  * negative error number.  If the submission is successful, the complete()
131  * callback from the URB will be called exactly once, when the USB core and
132  * Host Controller Driver (HCD) are finished with the URB.  When the completion
133  * function is called, control of the URB is returned to the device
134  * driver which issued the request.  The completion handler may then
135  * immediately free or reuse that URB.
136  *
137  * With few exceptions, USB device drivers should never access URB fields
138  * provided by usbcore or the HCD until its complete() is called.
139  * The exceptions relate to periodic transfer scheduling.  For both
140  * interrupt and isochronous urbs, as part of successful URB submission
141  * urb->interval is modified to reflect the actual transfer period used
142  * (normally some power of two units).  And for isochronous urbs,
143  * urb->start_frame is modified to reflect when the URB's transfers were
144  * scheduled to start.  Not all isochronous transfer scheduling policies
145  * will work, but most host controller drivers should easily handle ISO
146  * queues going from now until 10-200 msec into the future.
147  *
148  * For control endpoints, the synchronous usb_control_msg() call is
149  * often used (in non-interrupt context) instead of this call.
150  * That is often used through convenience wrappers, for the requests
151  * that are standardized in the USB 2.0 specification.  For bulk
152  * endpoints, a synchronous usb_bulk_msg() call is available.
153  *
154  * Request Queuing:
155  *
156  * URBs may be submitted to endpoints before previous ones complete, to
157  * minimize the impact of interrupt latencies and system overhead on data
158  * throughput.  With that queuing policy, an endpoint's queue would never
159  * be empty.  This is required for continuous isochronous data streams,
160  * and may also be required for some kinds of interrupt transfers. Such
161  * queuing also maximizes bandwidth utilization by letting USB controllers
162  * start work on later requests before driver software has finished the
163  * completion processing for earlier (successful) requests.
164  *
165  * As of Linux 2.6, all USB endpoint transfer queues support depths greater
166  * than one.  This was previously a HCD-specific behavior, except for ISO
167  * transfers.  Non-isochronous endpoint queues are inactive during cleanup
168  * after faults (transfer errors or cancelation).
169  *
170  * Reserved Bandwidth Transfers:
171  *
172  * Periodic transfers (interrupt or isochronous) are performed repeatedly,
173  * using the interval specified in the urb.  Submitting the first urb to
174  * the endpoint reserves the bandwidth necessary to make those transfers.
175  * If the USB subsystem can't allocate sufficient bandwidth to perform
176  * the periodic request, submitting such a periodic request should fail.
177  *
178  * Device drivers must explicitly request that repetition, by ensuring that
179  * some URB is always on the endpoint's queue (except possibly for short
180  * periods during completion callacks).  When there is no longer an urb
181  * queued, the endpoint's bandwidth reservation is canceled.  This means
182  * drivers can use their completion handlers to ensure they keep bandwidth
183  * they need, by reinitializing and resubmitting the just-completed urb
184  * until the driver longer needs that periodic bandwidth.
185  *
186  * Memory Flags:
187  *
188  * The general rules for how to decide which mem_flags to use
189  * are the same as for kmalloc.  There are four
190  * different possible values; GFP_KERNEL, GFP_NOFS, GFP_NOIO and
191  * GFP_ATOMIC.
192  *
193  * GFP_NOFS is not ever used, as it has not been implemented yet.
194  *
195  * GFP_ATOMIC is used when
196  *   (a) you are inside a completion handler, an interrupt, bottom half,
197  *       tasklet or timer, or
198  *   (b) you are holding a spinlock or rwlock (does not apply to
199  *       semaphores), or
200  *   (c) current->state != TASK_RUNNING, this is the case only after
201  *       you've changed it.
202  * 
203  * GFP_NOIO is used in the block io path and error handling of storage
204  * devices.
205  *
206  * All other situations use GFP_KERNEL.
207  *
208  * Some more specific rules for mem_flags can be inferred, such as
209  *  (1) start_xmit, timeout, and receive methods of network drivers must
210  *      use GFP_ATOMIC (they are called with a spinlock held);
211  *  (2) queuecommand methods of scsi drivers must use GFP_ATOMIC (also
212  *      called with a spinlock held);
213  *  (3) If you use a kernel thread with a network driver you must use
214  *      GFP_NOIO, unless (b) or (c) apply;
215  *  (4) after you have done a down() you can use GFP_KERNEL, unless (b) or (c)
216  *      apply or your are in a storage driver's block io path;
217  *  (5) USB probe and disconnect can use GFP_KERNEL unless (b) or (c) apply; and
218  *  (6) changing firmware on a running storage or net device uses
219  *      GFP_NOIO, unless b) or c) apply
220  *
221  */
222 int usb_submit_urb(struct urb *urb, int mem_flags)
223 {
224         int                     pipe, temp, max;
225         struct usb_device       *dev;
226         struct usb_operations   *op;
227         int                     is_out;
228
229         if (!urb || urb->hcpriv || !urb->complete)
230                 return -EINVAL;
231         if (!(dev = urb->dev) ||
232             (dev->state < USB_STATE_DEFAULT) ||
233             (!dev->bus) || (dev->devnum <= 0))
234                 return -ENODEV;
235         if (!(op = dev->bus->op) || !op->submit_urb)
236                 return -ENODEV;
237
238         urb->status = -EINPROGRESS;
239         urb->actual_length = 0;
240         urb->bandwidth = 0;
241
242         /* Lots of sanity checks, so HCDs can rely on clean data
243          * and don't need to duplicate tests
244          */
245         pipe = urb->pipe;
246         temp = usb_pipetype (pipe);
247         is_out = usb_pipeout (pipe);
248
249         if (!usb_pipecontrol (pipe) && dev->state < USB_STATE_CONFIGURED)
250                 return -ENODEV;
251
252         /* (actually HCDs may need to duplicate this, endpoint might yet
253          * stall due to queued bulk/intr transactions that complete after
254          * we check)
255          */
256         if (usb_endpoint_halted (dev, usb_pipeendpoint (pipe), is_out))
257                 return -EPIPE;
258
259         /* FIXME there should be a sharable lock protecting us against
260          * config/altsetting changes and disconnects, kicking in here.
261          * (here == before maxpacket, and eventually endpoint type,
262          * checks get made.)
263          */
264
265         max = usb_maxpacket (dev, pipe, is_out);
266         if (max <= 0) {
267                 dbg ("%s: bogus endpoint %d-%s on usb-%s-%s (bad maxpacket %d)",
268                         __FUNCTION__,
269                         usb_pipeendpoint (pipe), is_out ? "OUT" : "IN",
270                         dev->bus->bus_name, dev->devpath,
271                         max);
272                 return -EMSGSIZE;
273         }
274
275         /* periodic transfers limit size per frame/uframe,
276          * but drivers only control those sizes for ISO.
277          * while we're checking, initialize return status.
278          */
279         if (temp == PIPE_ISOCHRONOUS) {
280                 int     n, len;
281
282                 /* "high bandwidth" mode, 1-3 packets/uframe? */
283                 if (dev->speed == USB_SPEED_HIGH) {
284                         int     mult = 1 + ((max >> 11) & 0x03);
285                         max &= 0x07ff;
286                         max *= mult;
287                 }
288
289                 if (urb->number_of_packets <= 0)                    
290                         return -EINVAL;
291                 for (n = 0; n < urb->number_of_packets; n++) {
292                         len = urb->iso_frame_desc [n].length;
293                         if (len < 0 || len > max) 
294                                 return -EMSGSIZE;
295                         urb->iso_frame_desc [n].status = -EXDEV;
296                         urb->iso_frame_desc [n].actual_length = 0;
297                 }
298         }
299
300         /* the I/O buffer must be mapped/unmapped, except when length=0 */
301         if (urb->transfer_buffer_length < 0)
302                 return -EMSGSIZE;
303
304 #ifdef DEBUG
305         /* stuff that drivers shouldn't do, but which shouldn't
306          * cause problems in HCDs if they get it wrong.
307          */
308         {
309         unsigned int    orig_flags = urb->transfer_flags;
310         unsigned int    allowed;
311
312         /* enforce simple/standard policy */
313         allowed = URB_ASYNC_UNLINK;     // affects later unlinks
314         allowed |= (URB_NO_TRANSFER_DMA_MAP | URB_NO_SETUP_DMA_MAP);
315         allowed |= URB_NO_INTERRUPT;
316         switch (temp) {
317         case PIPE_BULK:
318                 if (is_out)
319                         allowed |= URB_ZERO_PACKET;
320                 /* FALLTHROUGH */
321         case PIPE_CONTROL:
322                 allowed |= URB_NO_FSBR; /* only affects UHCI */
323                 /* FALLTHROUGH */
324         default:                        /* all non-iso endpoints */
325                 if (!is_out)
326                         allowed |= URB_SHORT_NOT_OK;
327                 break;
328         case PIPE_ISOCHRONOUS:
329                 allowed |= URB_ISO_ASAP;
330                 break;
331         }
332         urb->transfer_flags &= allowed;
333
334         /* fail if submitter gave bogus flags */
335         if (urb->transfer_flags != orig_flags) {
336                 err ("BOGUS urb flags, %x --> %x",
337                         orig_flags, urb->transfer_flags);
338                 return -EINVAL;
339         }
340         }
341 #endif
342         /*
343          * Force periodic transfer intervals to be legal values that are
344          * a power of two (so HCDs don't need to).
345          *
346          * FIXME want bus->{intr,iso}_sched_horizon values here.  Each HC
347          * supports different values... this uses EHCI/UHCI defaults (and
348          * EHCI can use smaller non-default values).
349          */
350         switch (temp) {
351         case PIPE_ISOCHRONOUS:
352         case PIPE_INTERRUPT:
353                 /* too small? */
354                 if (urb->interval <= 0)
355                         return -EINVAL;
356                 /* too big? */
357                 switch (dev->speed) {
358                 case USB_SPEED_HIGH:    /* units are microframes */
359                         // NOTE usb handles 2^15
360                         if (urb->interval > (1024 * 8))
361                                 urb->interval = 1024 * 8;
362                         temp = 1024 * 8;
363                         break;
364                 case USB_SPEED_FULL:    /* units are frames/msec */
365                 case USB_SPEED_LOW:
366                         if (temp == PIPE_INTERRUPT) {
367                                 if (urb->interval > 255)
368                                         return -EINVAL;
369                                 // NOTE ohci only handles up to 32
370                                 temp = 128;
371                         } else {
372                                 if (urb->interval > 1024)
373                                         urb->interval = 1024;
374                                 // NOTE usb and ohci handle up to 2^15
375                                 temp = 1024;
376                         }
377                         break;
378                 default:
379                         return -EINVAL;
380                 }
381                 /* power of two? */
382                 while (temp > urb->interval)
383                         temp >>= 1;
384                 urb->interval = temp;
385         }
386
387         return op->submit_urb (urb, mem_flags);
388 }
389
390 /*-------------------------------------------------------------------*/
391
392 /**
393  * usb_unlink_urb - abort/cancel a transfer request for an endpoint
394  * @urb: pointer to urb describing a previously submitted request
395  *
396  * This routine cancels an in-progress request.  URBs complete only
397  * once per submission, and may be canceled only once per submission.
398  * Successful cancelation means the requests's completion handler will
399  * be called with a status code indicating that the request has been
400  * canceled (rather than any other code) and will quickly be removed
401  * from host controller data structures.
402  *
403  * When the URB_ASYNC_UNLINK transfer flag for the URB is clear, this
404  * request is synchronous.  Success is indicated by returning zero,
405  * at which time the urb will have been unlinked and its completion
406  * handler will have been called with urb->status == -ENOENT.  Failure is
407  * indicated by any other return value.
408  *
409  * The synchronous cancelation mode may not be used
410  * when unlinking an urb from an interrupt context, such as a bottom
411  * half or a completion handler; or when holding a spinlock; or in
412  * other cases when the caller can't schedule().
413  *
414  * When the URB_ASYNC_UNLINK transfer flag for the URB is set, this
415  * request is asynchronous.  Success is indicated by returning -EINPROGRESS,
416  * at which time the urb will normally not have been unlinked.
417  * The completion function will see urb->status == -ECONNRESET.  Failure
418  * is indicated by any other return value.
419  *
420  * Unlinking and Endpoint Queues:
421  *
422  * Host Controller Driver (HCDs) place all the URBs for a particular
423  * endpoint in a queue.  Normally the queue advances as the controller
424  * hardware processes each request.  But when an URB terminates with any
425  * fault (such as an error, or being unlinked) its queue stops, at least
426  * until that URB's completion routine returns.  It is guaranteed that
427  * the queue will not restart until all its unlinked URBs have been fully
428  * retired, with their completion routines run, even if that's not until
429  * some time after the original completion handler returns.
430  *
431  * This means that USB device drivers can safely build deep queues for
432  * large or complex transfers, and clean them up reliably after any sort
433  * of aborted transfer by unlinking all pending URBs at the first fault.
434  *
435  * Note that an URB terminating early because a short packet was received
436  * will count as an error if and only if the URB_SHORT_NOT_OK flag is set.
437  * Also, that all unlinks performed in any URB completion handler must
438  * be asynchronous.
439  *
440  * Queues for isochronous endpoints are treated differently, because they
441  * advance at fixed rates.  Such queues do not stop when an URB is unlinked.
442  * An unlinked URB may leave a gap in the stream of packets.  It is undefined
443  * whether such gaps can be filled in.
444  *
445  * When control URBs terminates with an error, it is likely that the
446  * status stage of the transfer will not take place, even if it is merely
447  * a soft error resulting from a short-packet with URB_SHORT_NOT_OK set.
448  */
449 int usb_unlink_urb(struct urb *urb)
450 {
451         if (urb && urb->dev && urb->dev->bus && urb->dev->bus->op)
452                 return urb->dev->bus->op->unlink_urb(urb);
453         else
454                 return -ENODEV;
455 }
456
457 EXPORT_SYMBOL(usb_init_urb);
458 EXPORT_SYMBOL(usb_alloc_urb);
459 EXPORT_SYMBOL(usb_free_urb);
460 EXPORT_SYMBOL(usb_get_urb);
461 EXPORT_SYMBOL(usb_submit_urb);
462 EXPORT_SYMBOL(usb_unlink_urb);
463