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>
8 #ifdef CONFIG_USB_DEBUG
13 #include <linux/usb.h>
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
20 * Initializes a urb so that the USB subsystem can use it properly.
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.
28 * Only use this function if you _really_ understand what you are doing.
30 void usb_init_urb(struct urb *urb)
33 memset(urb, 0, sizeof(*urb));
34 urb->count = (atomic_t)ATOMIC_INIT(1);
35 spin_lock_init(&urb->lock);
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.
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.
48 * If no memory is available, NULL is returned.
50 * If the driver want to use this urb for interrupt, control, or bulk
51 * endpoints, pass '0' as the number of iso packets.
53 * The driver must call usb_free_urb() when it is finished with the urb.
55 struct urb *usb_alloc_urb(int iso_packets, int mem_flags)
59 urb = (struct urb *)kmalloc(sizeof(struct urb) +
60 iso_packets * sizeof(struct usb_iso_packet_descriptor),
63 err("alloc_urb: kmalloc failed");
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
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.
77 * Note: The transfer buffer associated with the urb is not freed, that must be
80 void usb_free_urb(struct urb *urb)
83 if (atomic_dec_and_test(&urb->count))
88 * usb_get_urb - increments the reference count of the urb
89 * @urb: pointer to the urb to modify
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
95 * A pointer to the urb with the incremented reference counter is returned.
97 struct urb * usb_get_urb(struct urb *urb)
100 atomic_inc(&urb->count);
107 /*-------------------------------------------------------------------*/
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.
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").
121 * URBs may be submitted in interrupt context.
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.
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.
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.
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.
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.
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).
170 * Reserved Bandwidth Transfers:
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.
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.
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
193 * GFP_NOFS is not ever used, as it has not been implemented yet.
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
200 * (c) current->state != TASK_RUNNING, this is the case only after
203 * GFP_NOIO is used in the block io path and error handling of storage
206 * All other situations use GFP_KERNEL.
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
222 int usb_submit_urb(struct urb *urb, int mem_flags)
225 struct usb_device *dev;
226 struct usb_operations *op;
229 if (!urb || urb->hcpriv || !urb->complete)
231 if (!(dev = urb->dev) ||
232 (dev->state < USB_STATE_DEFAULT) ||
233 (!dev->bus) || (dev->devnum <= 0))
235 if (!(op = dev->bus->op) || !op->submit_urb)
238 urb->status = -EINPROGRESS;
239 urb->actual_length = 0;
242 /* Lots of sanity checks, so HCDs can rely on clean data
243 * and don't need to duplicate tests
246 temp = usb_pipetype (pipe);
247 is_out = usb_pipeout (pipe);
249 if (!usb_pipecontrol (pipe) && dev->state < USB_STATE_CONFIGURED)
252 /* (actually HCDs may need to duplicate this, endpoint might yet
253 * stall due to queued bulk/intr transactions that complete after
256 if (usb_endpoint_halted (dev, usb_pipeendpoint (pipe), is_out))
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,
265 max = usb_maxpacket (dev, pipe, is_out);
267 dbg ("%s: bogus endpoint %d-%s on usb-%s-%s (bad maxpacket %d)",
269 usb_pipeendpoint (pipe), is_out ? "OUT" : "IN",
270 dev->bus->bus_name, dev->devpath,
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.
279 if (temp == PIPE_ISOCHRONOUS) {
282 /* "high bandwidth" mode, 1-3 packets/uframe? */
283 if (dev->speed == USB_SPEED_HIGH) {
284 int mult = 1 + ((max >> 11) & 0x03);
289 if (urb->number_of_packets <= 0)
291 for (n = 0; n < urb->number_of_packets; n++) {
292 len = urb->iso_frame_desc [n].length;
293 if (len < 0 || len > max)
295 urb->iso_frame_desc [n].status = -EXDEV;
296 urb->iso_frame_desc [n].actual_length = 0;
300 /* the I/O buffer must be mapped/unmapped, except when length=0 */
301 if (urb->transfer_buffer_length < 0)
305 /* stuff that drivers shouldn't do, but which shouldn't
306 * cause problems in HCDs if they get it wrong.
309 unsigned int orig_flags = urb->transfer_flags;
310 unsigned int allowed;
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;
319 allowed |= URB_ZERO_PACKET;
322 allowed |= URB_NO_FSBR; /* only affects UHCI */
324 default: /* all non-iso endpoints */
326 allowed |= URB_SHORT_NOT_OK;
328 case PIPE_ISOCHRONOUS:
329 allowed |= URB_ISO_ASAP;
332 urb->transfer_flags &= allowed;
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);
343 * Force periodic transfer intervals to be legal values that are
344 * a power of two (so HCDs don't need to).
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).
351 case PIPE_ISOCHRONOUS:
354 if (urb->interval <= 0)
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;
364 case USB_SPEED_FULL: /* units are frames/msec */
366 if (temp == PIPE_INTERRUPT) {
367 if (urb->interval > 255)
369 // NOTE ohci only handles up to 32
372 if (urb->interval > 1024)
373 urb->interval = 1024;
374 // NOTE usb and ohci handle up to 2^15
382 while (temp > urb->interval)
384 urb->interval = temp;
387 return op->submit_urb (urb, mem_flags);
390 /*-------------------------------------------------------------------*/
393 * usb_unlink_urb - abort/cancel a transfer request for an endpoint
394 * @urb: pointer to urb describing a previously submitted request
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.
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.
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().
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.
420 * Unlinking and Endpoint Queues:
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.
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.
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
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.
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.
449 int usb_unlink_urb(struct urb *urb)
451 if (urb && urb->dev && urb->dev->bus && urb->dev->bus->op)
452 return urb->dev->bus->op->unlink_urb(urb);
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);