Added PKEVENT to init_waitqueue_head.
[reactos.git] / reactos / drivers / usb / cromwell / core / message.c
1 /*
2 * message.c - synchronous message handling
3 */
4 #if 0
5 #include <linux/pci.h> /* for scatterlist macros */
6 #include <linux/usb.h>
7 #include <linux/module.h>
8 #include <linux/slab.h>
9 #include <linux/init.h>
10 #include <linux/mm.h>
11 #include <asm/byteorder.h>
12 #else
13 #include "../usb_wrapper.h"
14 #endif
15
16 #include "hcd.h" /* for usbcore internals */
17
18 // ReactOS specific: No WAITQUEUEs here
19 #undef wake_up
20 #define wake_up(a) do {} while(0)
21
22 struct usb_api_data {
23 wait_queue_head_t wqh;
24 int done;
25 };
26
27 static void usb_api_blocking_completion(struct urb *urb, struct pt_regs *regs)
28 {
29 struct usb_api_data *awd = (struct usb_api_data *)urb->context;
30
31 awd->done = 1;
32 wmb();
33 wake_up(&awd->wqh);
34 }
35
36 // Starts urb and waits for completion or timeout
37 static int usb_start_wait_urb(struct urb *urb, int timeout, int* actual_length)
38 {
39 //DECLARE_WAITQUEUE(wait, current); // Fireball, 24Jan05 - silent gcc complaining about unused wait variable
40 struct usb_api_data awd;
41 int status;
42
43 init_waitqueue_head((PKEVENT)&awd.wqh);
44 awd.done = 0;
45
46 set_current_state(TASK_UNINTERRUPTIBLE);
47 add_wait_queue(&awd.wqh, &wait);
48
49 urb->context = &awd;
50 status = usb_submit_urb(urb, GFP_ATOMIC);
51 if (status) {
52 // something went wrong
53 usb_free_urb(urb);
54 set_current_state(TASK_RUNNING);
55 remove_wait_queue(&awd.wqh, &wait);
56 return status;
57 }
58
59 while (timeout && !awd.done)
60 {
61 timeout = schedule_timeout(timeout);
62 set_current_state(TASK_UNINTERRUPTIBLE);
63 rmb();
64 }
65
66 set_current_state(TASK_RUNNING);
67 remove_wait_queue(&awd.wqh, &wait);
68
69 if (!timeout && !awd.done) {
70 if (urb->status != -EINPROGRESS) { /* No callback?!! */
71 printk(KERN_ERR "usb: raced timeout, "
72 "pipe 0x%x status %d time left %d\n",
73 urb->pipe, urb->status, timeout);
74 status = urb->status;
75 } else {
76 warn("usb_control/bulk_msg: timeout");
77 usb_unlink_urb(urb); // remove urb safely
78 status = -ETIMEDOUT;
79 }
80 } else
81 status = urb->status;
82
83 if (actual_length)
84 *actual_length = urb->actual_length;
85
86 usb_free_urb(urb);
87 return status;
88 }
89
90 /*-------------------------------------------------------------------*/
91 // returns status (negative) or length (positive)
92 int usb_internal_control_msg(struct usb_device *usb_dev, unsigned int pipe,
93 struct usb_ctrlrequest *cmd, void *data, int len, int timeout)
94 {
95 struct urb *urb;
96 int retv;
97 int length;
98
99 urb = usb_alloc_urb(0, GFP_NOIO);
100 if (!urb)
101 return -ENOMEM;
102
103 usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char*)cmd, data, len,
104 usb_api_blocking_completion, 0);
105
106 retv = usb_start_wait_urb(urb, timeout, &length);
107
108 if (retv < 0)
109 return retv;
110 else
111 return length;
112 }
113
114 /**
115 * usb_control_msg - Builds a control urb, sends it off and waits for completion
116 * @dev: pointer to the usb device to send the message to
117 * @pipe: endpoint "pipe" to send the message to
118 * @request: USB message request value
119 * @requesttype: USB message request type value
120 * @value: USB message value
121 * @index: USB message index value
122 * @data: pointer to the data to send
123 * @size: length in bytes of the data to send
124 * @timeout: time in jiffies to wait for the message to complete before
125 * timing out (if 0 the wait is forever)
126 * Context: !in_interrupt ()
127 *
128 * This function sends a simple control message to a specified endpoint
129 * and waits for the message to complete, or timeout.
130 *
131 * If successful, it returns the number of bytes transferred, otherwise a negative error number.
132 *
133 * Don't use this function from within an interrupt context, like a
134 * bottom half handler. If you need an asynchronous message, or need to send
135 * a message from within interrupt context, use usb_submit_urb()
136 * If a thread in your driver uses this call, make sure your disconnect()
137 * method can wait for it to complete. Since you don't have a handle on
138 * the URB used, you can't cancel the request.
139 */
140 int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype,
141 __u16 value, __u16 index, void *data, __u16 size, int timeout)
142 {
143 struct usb_ctrlrequest *dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
144 int ret;
145
146 if (!dr)
147 return -ENOMEM;
148
149 dr->bRequestType= requesttype;
150 dr->bRequest = request;
151 dr->wValue = cpu_to_le16p(&value);
152 dr->wIndex = cpu_to_le16p(&index);
153 dr->wLength = cpu_to_le16p(&size);
154
155 //dbg("usb_control_msg");
156
157 ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
158
159 kfree(dr);
160
161 return ret;
162 }
163
164
165 /**
166 * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
167 * @usb_dev: pointer to the usb device to send the message to
168 * @pipe: endpoint "pipe" to send the message to
169 * @data: pointer to the data to send
170 * @len: length in bytes of the data to send
171 * @actual_length: pointer to a location to put the actual length transferred in bytes
172 * @timeout: time in jiffies to wait for the message to complete before
173 * timing out (if 0 the wait is forever)
174 * Context: !in_interrupt ()
175 *
176 * This function sends a simple bulk message to a specified endpoint
177 * and waits for the message to complete, or timeout.
178 *
179 * If successful, it returns 0, otherwise a negative error number.
180 * The number of actual bytes transferred will be stored in the
181 * actual_length paramater.
182 *
183 * Don't use this function from within an interrupt context, like a
184 * bottom half handler. If you need an asynchronous message, or need to
185 * send a message from within interrupt context, use usb_submit_urb()
186 * If a thread in your driver uses this call, make sure your disconnect()
187 * method can wait for it to complete. Since you don't have a handle on
188 * the URB used, you can't cancel the request.
189 */
190 int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
191 void *data, int len, int *actual_length, int timeout)
192 {
193 struct urb *urb;
194
195 if (len < 0)
196 return -EINVAL;
197
198 urb=usb_alloc_urb(0, GFP_KERNEL);
199 if (!urb)
200 return -ENOMEM;
201
202 usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
203 usb_api_blocking_completion, 0);
204
205 return usb_start_wait_urb(urb,timeout,actual_length);
206 }
207
208 /*-------------------------------------------------------------------*/
209 //#warning "Scatter-gather stuff disabled"
210 #if 0
211 static void sg_clean (struct usb_sg_request *io)
212 {
213 if (io->urbs) {
214 while (io->entries--)
215 usb_free_urb (io->urbs [io->entries]);
216 kfree (io->urbs);
217 io->urbs = 0;
218 }
219 if (io->dev->dev.dma_mask != 0)
220 usb_buffer_unmap_sg (io->dev, io->pipe, io->sg, io->nents);
221 io->dev = 0;
222 }
223
224 static void sg_complete (struct urb *urb, struct pt_regs *regs)
225 {
226 struct usb_sg_request *io = (struct usb_sg_request *) urb->context;
227 unsigned long flags;
228
229 spin_lock_irqsave (&io->lock, flags);
230
231 /* In 2.5 we require hcds' endpoint queues not to progress after fault
232 * reports, until the completion callback (this!) returns. That lets
233 * device driver code (like this routine) unlink queued urbs first,
234 * if it needs to, since the HC won't work on them at all. So it's
235 * not possible for page N+1 to overwrite page N, and so on.
236 *
237 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
238 * complete before the HCD can get requests away from hardware,
239 * though never during cleanup after a hard fault.
240 */
241 if (io->status
242 && (io->status != -ECONNRESET
243 || urb->status != -ECONNRESET)
244 && urb->actual_length) {
245 dev_err (io->dev->bus->controller,
246 "dev %s ep%d%s scatterlist error %d/%d\n",
247 io->dev->devpath,
248 usb_pipeendpoint (urb->pipe),
249 usb_pipein (urb->pipe) ? "in" : "out",
250 urb->status, io->status);
251 // BUG ();
252 }
253
254 if (urb->status && urb->status != -ECONNRESET) {
255 int i, found, status;
256
257 io->status = urb->status;
258
259 /* the previous urbs, and this one, completed already.
260 * unlink the later ones so they won't rx/tx bad data,
261 *
262 * FIXME don't bother unlinking urbs that haven't yet been
263 * submitted; those non-error cases shouldn't be syslogged
264 */
265 for (i = 0, found = 0; i < io->entries; i++) {
266 if (found) {
267 status = usb_unlink_urb (io->urbs [i]);
268 if (status && status != -EINPROGRESS)
269 err ("sg_complete, unlink --> %d",
270 status);
271 } else if (urb == io->urbs [i])
272 found = 1;
273 }
274 }
275
276 /* on the last completion, signal usb_sg_wait() */
277 io->bytes += urb->actual_length;
278 io->count--;
279 if (!io->count)
280 complete (&io->complete);
281
282 spin_unlock_irqrestore (&io->lock, flags);
283 }
284
285
286 /**
287 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
288 * @io: request block being initialized. until usb_sg_wait() returns,
289 * treat this as a pointer to an opaque block of memory,
290 * @dev: the usb device that will send or receive the data
291 * @pipe: endpoint "pipe" used to transfer the data
292 * @period: polling rate for interrupt endpoints, in frames or
293 * (for high speed endpoints) microframes; ignored for bulk
294 * @sg: scatterlist entries
295 * @nents: how many entries in the scatterlist
296 * @length: how many bytes to send from the scatterlist, or zero to
297 * send every byte identified in the list.
298 * @mem_flags: SLAB_* flags affecting memory allocations in this call
299 *
300 * Returns zero for success, else a negative errno value. This initializes a
301 * scatter/gather request, allocating resources such as I/O mappings and urb
302 * memory (except maybe memory used by USB controller drivers).
303 *
304 * The request must be issued using usb_sg_wait(), which waits for the I/O to
305 * complete (or to be canceled) and then cleans up all resources allocated by
306 * usb_sg_init().
307 *
308 * The request may be canceled with usb_sg_cancel(), either before or after
309 * usb_sg_wait() is called.
310 */
311 int usb_sg_init (
312 struct usb_sg_request *io,
313 struct usb_device *dev,
314 unsigned pipe,
315 unsigned period,
316 struct scatterlist *sg,
317 int nents,
318 size_t length,
319 int mem_flags
320 )
321 {
322 int i;
323 int urb_flags;
324 int dma;
325
326 if (!io || !dev || !sg
327 || usb_pipecontrol (pipe)
328 || usb_pipeisoc (pipe)
329 || nents <= 0)
330 return -EINVAL;
331
332 spin_lock_init (&io->lock);
333 io->dev = dev;
334 io->pipe = pipe;
335 io->sg = sg;
336 io->nents = nents;
337
338 /* not all host controllers use DMA (like the mainstream pci ones);
339 * they can use PIO (sl811) or be software over another transport.
340 */
341 dma = (dev->dev.dma_mask != 0);
342 if (dma)
343 io->entries = usb_buffer_map_sg (dev, pipe, sg, nents);
344 else
345 io->entries = nents;
346
347 /* initialize all the urbs we'll use */
348 if (io->entries <= 0)
349 return io->entries;
350
351 io->count = 0;
352 io->urbs = kmalloc (io->entries * sizeof *io->urbs, mem_flags);
353 if (!io->urbs)
354 goto nomem;
355
356 urb_flags = URB_ASYNC_UNLINK | URB_NO_DMA_MAP | URB_NO_INTERRUPT;
357 if (usb_pipein (pipe))
358 urb_flags |= URB_SHORT_NOT_OK;
359
360 for (i = 0; i < io->entries; i++, io->count = i) {
361 unsigned len;
362
363 io->urbs [i] = usb_alloc_urb (0, mem_flags);
364 if (!io->urbs [i]) {
365 io->entries = i;
366 goto nomem;
367 }
368
369 io->urbs [i]->dev = dev;
370 io->urbs [i]->pipe = pipe;
371 io->urbs [i]->interval = period;
372 io->urbs [i]->transfer_flags = urb_flags;
373
374 io->urbs [i]->complete = sg_complete;
375 io->urbs [i]->context = io;
376 io->urbs [i]->status = -EINPROGRESS;
377 io->urbs [i]->actual_length = 0;
378
379 if (dma) {
380 /* hc may use _only_ transfer_dma */
381 io->urbs [i]->transfer_dma = sg_dma_address (sg + i);
382 len = sg_dma_len (sg + i);
383 } else {
384 /* hc may use _only_ transfer_buffer */
385 io->urbs [i]->transfer_buffer =
386 page_address (sg [i].page) + sg [i].offset;
387 len = sg [i].length;
388 }
389
390 if (length) {
391 len = min_t (unsigned, len, length);
392 length -= len;
393 if (length == 0)
394 io->entries = i + 1;
395 }
396 io->urbs [i]->transfer_buffer_length = len;
397 }
398 io->urbs [--i]->transfer_flags &= ~URB_NO_INTERRUPT;
399
400 /* transaction state */
401 io->status = 0;
402 io->bytes = 0;
403 init_completion (&io->complete);
404 return 0;
405
406 nomem:
407 sg_clean (io);
408 return -ENOMEM;
409 }
410
411
412 /**
413 * usb_sg_wait - synchronously execute scatter/gather request
414 * @io: request block handle, as initialized with usb_sg_init().
415 * some fields become accessible when this call returns.
416 * Context: !in_interrupt ()
417 *
418 * This function blocks until the specified I/O operation completes. It
419 * leverages the grouping of the related I/O requests to get good transfer
420 * rates, by queueing the requests. At higher speeds, such queuing can
421 * significantly improve USB throughput.
422 *
423 * There are three kinds of completion for this function.
424 * (1) success, where io->status is zero. The number of io->bytes
425 * transferred is as requested.
426 * (2) error, where io->status is a negative errno value. The number
427 * of io->bytes transferred before the error is usually less
428 * than requested, and can be nonzero.
429 * (3) cancelation, a type of error with status -ECONNRESET that
430 * is initiated by usb_sg_cancel().
431 *
432 * When this function returns, all memory allocated through usb_sg_init() or
433 * this call will have been freed. The request block parameter may still be
434 * passed to usb_sg_cancel(), or it may be freed. It could also be
435 * reinitialized and then reused.
436 *
437 * Data Transfer Rates:
438 *
439 * Bulk transfers are valid for full or high speed endpoints.
440 * The best full speed data rate is 19 packets of 64 bytes each
441 * per frame, or 1216 bytes per millisecond.
442 * The best high speed data rate is 13 packets of 512 bytes each
443 * per microframe, or 52 KBytes per millisecond.
444 *
445 * The reason to use interrupt transfers through this API would most likely
446 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
447 * could be transferred. That capability is less useful for low or full
448 * speed interrupt endpoints, which allow at most one packet per millisecond,
449 * of at most 8 or 64 bytes (respectively).
450 */
451 void usb_sg_wait (struct usb_sg_request *io)
452 {
453 int i;
454 unsigned long flags;
455
456 /* queue the urbs. */
457 spin_lock_irqsave (&io->lock, flags);
458 for (i = 0; i < io->entries && !io->status; i++) {
459 int retval;
460
461 retval = usb_submit_urb (io->urbs [i], SLAB_ATOMIC);
462
463 /* after we submit, let completions or cancelations fire;
464 * we handshake using io->status.
465 */
466 spin_unlock_irqrestore (&io->lock, flags);
467 switch (retval) {
468 /* maybe we retrying will recover */
469 case -ENXIO: // hc didn't queue this one
470 case -EAGAIN:
471 case -ENOMEM:
472 retval = 0;
473 i--;
474 // FIXME: should it usb_sg_cancel() on INTERRUPT?
475 yield ();
476 break;
477
478 /* no error? continue immediately.
479 *
480 * NOTE: to work better with UHCI (4K I/O buffer may
481 * need 3K of TDs) it may be good to limit how many
482 * URBs are queued at once; N milliseconds?
483 */
484 case 0:
485 cpu_relax ();
486 break;
487
488 /* fail any uncompleted urbs */
489 default:
490 io->urbs [i]->status = retval;
491 dbg ("usb_sg_msg, submit --> %d", retval);
492 usb_sg_cancel (io);
493 }
494 spin_lock_irqsave (&io->lock, flags);
495 if (retval && io->status == -ECONNRESET)
496 io->status = retval;
497 }
498 spin_unlock_irqrestore (&io->lock, flags);
499
500 /* OK, yes, this could be packaged as non-blocking.
501 * So could the submit loop above ... but it's easier to
502 * solve neither problem than to solve both!
503 */
504 wait_for_completion (&io->complete);
505
506 sg_clean (io);
507 }
508
509 /**
510 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
511 * @io: request block, initialized with usb_sg_init()
512 *
513 * This stops a request after it has been started by usb_sg_wait().
514 * It can also prevents one initialized by usb_sg_init() from starting,
515 * so that call just frees resources allocated to the request.
516 */
517 void usb_sg_cancel (struct usb_sg_request *io)
518 {
519 unsigned long flags;
520
521 spin_lock_irqsave (&io->lock, flags);
522
523 /* shut everything down, if it didn't already */
524 if (!io->status) {
525 int i;
526
527 io->status = -ECONNRESET;
528 for (i = 0; i < io->entries; i++) {
529 int retval;
530
531 if (!io->urbs [i]->dev)
532 continue;
533 retval = usb_unlink_urb (io->urbs [i]);
534 if (retval && retval != -EINPROGRESS)
535 warn ("usb_sg_cancel, unlink --> %d", retval);
536 // FIXME don't warn on "not yet submitted" error
537 }
538 }
539 spin_unlock_irqrestore (&io->lock, flags);
540 }
541 #endif
542 /*-------------------------------------------------------------------*/
543
544 /**
545 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
546 * @dev: the device whose descriptor is being retrieved
547 * @type: the descriptor type (USB_DT_*)
548 * @index: the number of the descriptor
549 * @buf: where to put the descriptor
550 * @size: how big is "buf"?
551 * Context: !in_interrupt ()
552 *
553 * Gets a USB descriptor. Convenience functions exist to simplify
554 * getting some types of descriptors. Use
555 * usb_get_device_descriptor() for USB_DT_DEVICE,
556 * and usb_get_string() or usb_string() for USB_DT_STRING.
557 * Configuration descriptors (USB_DT_CONFIG) are part of the device
558 * structure, at least for the current configuration.
559 * In addition to a number of USB-standard descriptors, some
560 * devices also use class-specific or vendor-specific descriptors.
561 *
562 * This call is synchronous, and may not be used in an interrupt context.
563 *
564 * Returns the number of bytes received on success, or else the status code
565 * returned by the underlying usb_control_msg() call.
566 */
567 int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
568 {
569 int i = 5;
570 int result;
571
572 memset(buf,0,size); // Make sure we parse really received data
573
574 while (i--) {
575 /* retries if the returned length was 0; flakey device */
576 if ((result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
577 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
578 (type << 8) + index, 0, buf, size,
579 HZ * USB_CTRL_GET_TIMEOUT)) > 0
580 || result == -EPIPE)
581 break;
582 }
583 return result;
584 }
585
586 /**
587 * usb_get_string - gets a string descriptor
588 * @dev: the device whose string descriptor is being retrieved
589 * @langid: code for language chosen (from string descriptor zero)
590 * @index: the number of the descriptor
591 * @buf: where to put the string
592 * @size: how big is "buf"?
593 * Context: !in_interrupt ()
594 *
595 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
596 * in little-endian byte order).
597 * The usb_string() function will often be a convenient way to turn
598 * these strings into kernel-printable form.
599 *
600 * Strings may be referenced in device, configuration, interface, or other
601 * descriptors, and could also be used in vendor-specific ways.
602 *
603 * This call is synchronous, and may not be used in an interrupt context.
604 *
605 * Returns the number of bytes received on success, or else the status code
606 * returned by the underlying usb_control_msg() call.
607 */
608 int usb_get_string(struct usb_device *dev, unsigned short langid, unsigned char index, void *buf, int size)
609 {
610 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
611 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
612 (USB_DT_STRING << 8) + index, langid, buf, size,
613 HZ * USB_CTRL_GET_TIMEOUT);
614 }
615
616 /**
617 * usb_get_device_descriptor - (re)reads the device descriptor
618 * @dev: the device whose device descriptor is being updated
619 * Context: !in_interrupt ()
620 *
621 * Updates the copy of the device descriptor stored in the device structure,
622 * which dedicates space for this purpose. Note that several fields are
623 * converted to the host CPU's byte order: the USB version (bcdUSB), and
624 * vendors product and version fields (idVendor, idProduct, and bcdDevice).
625 * That lets device drivers compare against non-byteswapped constants.
626 *
627 * There's normally no need to use this call, although some devices
628 * will change their descriptors after events like updating firmware.
629 *
630 * This call is synchronous, and may not be used in an interrupt context.
631 *
632 * Returns the number of bytes received on success, or else the status code
633 * returned by the underlying usb_control_msg() call.
634 */
635 int usb_get_device_descriptor(struct usb_device *dev)
636 {
637 int ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, &dev->descriptor,
638 sizeof(dev->descriptor));
639 if (ret >= 0) {
640 le16_to_cpus(&dev->descriptor.bcdUSB);
641 le16_to_cpus(&dev->descriptor.idVendor);
642 le16_to_cpus(&dev->descriptor.idProduct);
643 le16_to_cpus(&dev->descriptor.bcdDevice);
644 }
645 return ret;
646 }
647
648 /**
649 * usb_get_status - issues a GET_STATUS call
650 * @dev: the device whose status is being checked
651 * @type: USB_RECIP_*; for device, interface, or endpoint
652 * @target: zero (for device), else interface or endpoint number
653 * @data: pointer to two bytes of bitmap data
654 * Context: !in_interrupt ()
655 *
656 * Returns device, interface, or endpoint status. Normally only of
657 * interest to see if the device is self powered, or has enabled the
658 * remote wakeup facility; or whether a bulk or interrupt endpoint
659 * is halted ("stalled").
660 *
661 * Bits in these status bitmaps are set using the SET_FEATURE request,
662 * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
663 * function should be used to clear halt ("stall") status.
664 *
665 * This call is synchronous, and may not be used in an interrupt context.
666 *
667 * Returns the number of bytes received on success, or else the status code
668 * returned by the underlying usb_control_msg() call.
669 */
670 int usb_get_status(struct usb_device *dev, int type, int target, void *data)
671 {
672 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
673 USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, data, 2,
674 HZ * USB_CTRL_GET_TIMEOUT);
675 }
676
677
678 // hub-only!! ... and only exported for reset/reinit path.
679 // otherwise used internally, when setting up a config
680 void usb_set_maxpacket(struct usb_device *dev)
681 {
682 int i, b;
683
684 /* NOTE: affects all endpoints _except_ ep0 */
685 for (i=0; i<dev->actconfig->desc.bNumInterfaces; i++) {
686 struct usb_interface *ifp = dev->actconfig->interface + i;
687 struct usb_host_interface *as = ifp->altsetting + ifp->act_altsetting;
688 struct usb_host_endpoint *ep = as->endpoint;
689 int e;
690
691 for (e=0; e<as->desc.bNumEndpoints; e++) {
692 struct usb_endpoint_descriptor *d;
693 d = &ep [e].desc;
694 b = d->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
695 if ((d->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
696 USB_ENDPOINT_XFER_CONTROL) { /* Control => bidirectional */
697 dev->epmaxpacketout[b] = d->wMaxPacketSize;
698 dev->epmaxpacketin [b] = d->wMaxPacketSize;
699 }
700 else if (usb_endpoint_out(d->bEndpointAddress)) {
701 if (d->wMaxPacketSize > dev->epmaxpacketout[b])
702 dev->epmaxpacketout[b] = d->wMaxPacketSize;
703 }
704 else {
705 if (d->wMaxPacketSize > dev->epmaxpacketin [b])
706 dev->epmaxpacketin [b] = d->wMaxPacketSize;
707 }
708 }
709 }
710 }
711
712 /**
713 * usb_clear_halt - tells device to clear endpoint halt/stall condition
714 * @dev: device whose endpoint is halted
715 * @pipe: endpoint "pipe" being cleared
716 * Context: !in_interrupt ()
717 *
718 * This is used to clear halt conditions for bulk and interrupt endpoints,
719 * as reported by URB completion status. Endpoints that are halted are
720 * sometimes referred to as being "stalled". Such endpoints are unable
721 * to transmit or receive data until the halt status is cleared. Any URBs
722 * queued for such an endpoint should normally be unlinked by the driver
723 * before clearing the halt condition, as described in sections 5.7.5
724 * and 5.8.5 of the USB 2.0 spec.
725 *
726 * Note that control and isochronous endpoints don't halt, although control
727 * endpoints report "protocol stall" (for unsupported requests) using the
728 * same status code used to report a true stall.
729 *
730 * This call is synchronous, and may not be used in an interrupt context.
731 *
732 * Returns zero on success, or else the status code returned by the
733 * underlying usb_control_msg() call.
734 */
735 int usb_clear_halt(struct usb_device *dev, int pipe)
736 {
737 int result;
738 int endp = usb_pipeendpoint(pipe);
739
740 if (usb_pipein (pipe))
741 endp |= USB_DIR_IN;
742
743 /* we don't care if it wasn't halted first. in fact some devices
744 * (like some ibmcam model 1 units) seem to expect hosts to make
745 * this request for iso endpoints, which can't halt!
746 */
747 result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
748 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT, 0, endp, NULL, 0,
749 HZ * USB_CTRL_SET_TIMEOUT);
750
751 /* don't un-halt or force to DATA0 except on success */
752 if (result < 0)
753 return result;
754
755 /* NOTE: seems like Microsoft and Apple don't bother verifying
756 * the clear "took", so some devices could lock up if you check...
757 * such as the Hagiwara FlashGate DUAL. So we won't bother.
758 *
759 * NOTE: make sure the logic here doesn't diverge much from
760 * the copy in usb-storage, for as long as we need two copies.
761 */
762
763 /* toggle was reset by the clear, then ep was reactivated */
764 usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
765 usb_endpoint_running(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe));
766
767 return 0;
768 }
769
770 /**
771 * usb_set_interface - Makes a particular alternate setting be current
772 * @dev: the device whose interface is being updated
773 * @interface: the interface being updated
774 * @alternate: the setting being chosen.
775 * Context: !in_interrupt ()
776 *
777 * This is used to enable data transfers on interfaces that may not
778 * be enabled by default. Not all devices support such configurability.
779 * Only the driver bound to an interface may change its setting.
780 *
781 * Within any given configuration, each interface may have several
782 * alternative settings. These are often used to control levels of
783 * bandwidth consumption. For example, the default setting for a high
784 * speed interrupt endpoint may not send more than 64 bytes per microframe,
785 * while interrupt transfers of up to 3KBytes per microframe are legal.
786 * Also, isochronous endpoints may never be part of an
787 * interface's default setting. To access such bandwidth, alternate
788 * interface settings must be made current.
789 *
790 * Note that in the Linux USB subsystem, bandwidth associated with
791 * an endpoint in a given alternate setting is not reserved until an URB
792 * is submitted that needs that bandwidth. Some other operating systems
793 * allocate bandwidth early, when a configuration is chosen.
794 *
795 * This call is synchronous, and may not be used in an interrupt context.
796 * Also, drivers must not change altsettings while urbs are scheduled for
797 * endpoints in that interface; all such urbs must first be completed
798 * (perhaps forced by unlinking).
799 *
800 * Returns zero on success, or else the status code returned by the
801 * underlying usb_control_msg() call.
802 */
803 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
804 {
805 struct usb_interface *iface;
806 struct usb_host_interface *iface_as;
807 int i, ret;
808 void (*disable)(struct usb_device *, int) = dev->bus->op->disable;
809
810 iface = usb_ifnum_to_if(dev, interface);
811 if (!iface) {
812 warn("selecting invalid interface %d", interface);
813 return -EINVAL;
814 }
815
816 /* 9.4.10 says devices don't need this, if the interface
817 only has one alternate setting */
818 if (iface->num_altsetting == 1) {
819 dbg("ignoring set_interface for dev %d, iface %d, alt %d",
820 dev->devnum, interface, alternate);
821 return 0;
822 }
823
824 if (alternate < 0 || alternate >= iface->num_altsetting)
825 return -EINVAL;
826
827 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
828 USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
829 iface->altsetting[alternate]
830 .desc.bAlternateSetting,
831 interface, NULL, 0, HZ * 5)) < 0)
832 return ret;
833
834 /* FIXME drivers shouldn't need to replicate/bugfix the logic here
835 * when they implement async or easily-killable versions of this or
836 * other "should-be-internal" functions (like clear_halt).
837 * should hcd+usbcore postprocess control requests?
838 */
839
840 /* prevent submissions using previous endpoint settings */
841 iface_as = iface->altsetting + iface->act_altsetting;
842 for (i = 0; i < iface_as->desc.bNumEndpoints; i++) {
843 u8 ep = iface_as->endpoint [i].desc.bEndpointAddress;
844 int out = !(ep & USB_DIR_IN);
845
846 /* clear out hcd state, then usbcore state */
847 if (disable)
848 disable (dev, ep);
849 ep &= USB_ENDPOINT_NUMBER_MASK;
850 (out ? dev->epmaxpacketout : dev->epmaxpacketin ) [ep] = 0;
851 }
852 iface->act_altsetting = alternate;
853
854 /* 9.1.1.5: reset toggles for all endpoints affected by this iface-as
855 *
856 * Note:
857 * Despite EP0 is always present in all interfaces/AS, the list of
858 * endpoints from the descriptor does not contain EP0. Due to its
859 * omnipresence one might expect EP0 being considered "affected" by
860 * any SetInterface request and hence assume toggles need to be reset.
861 * However, EP0 toggles are re-synced for every individual transfer
862 * during the SETUP stage - hence EP0 toggles are "don't care" here.
863 * (Likewise, EP0 never "halts" on well designed devices.)
864 */
865
866 iface_as = &iface->altsetting[alternate];
867 for (i = 0; i < iface_as->desc.bNumEndpoints; i++) {
868 u8 ep = iface_as->endpoint[i].desc.bEndpointAddress;
869 int out = !(ep & USB_DIR_IN);
870
871 ep &= USB_ENDPOINT_NUMBER_MASK;
872 usb_settoggle (dev, ep, out, 0);
873 (out ? dev->epmaxpacketout : dev->epmaxpacketin) [ep]
874 = iface_as->endpoint [i].desc.wMaxPacketSize;
875 usb_endpoint_running (dev, ep, out);
876 }
877
878 return 0;
879 }
880
881 /**
882 * usb_set_configuration - Makes a particular device setting be current
883 * @dev: the device whose configuration is being updated
884 * @configuration: the configuration being chosen.
885 * Context: !in_interrupt ()
886 *
887 * This is used to enable non-default device modes. Not all devices
888 * support this kind of configurability. By default, configuration
889 * zero is selected after enumeration; many devices only have a single
890 * configuration.
891 *
892 * USB devices may support one or more configurations, which affect
893 * power consumption and the functionality available. For example,
894 * the default configuration is limited to using 100mA of bus power,
895 * so that when certain device functionality requires more power,
896 * and the device is bus powered, that functionality will be in some
897 * non-default device configuration. Other device modes may also be
898 * reflected as configuration options, such as whether two ISDN
899 * channels are presented as independent 64Kb/s interfaces or as one
900 * bonded 128Kb/s interface.
901 *
902 * Note that USB has an additional level of device configurability,
903 * associated with interfaces. That configurability is accessed using
904 * usb_set_interface().
905 *
906 * This call is synchronous, and may not be used in an interrupt context.
907 *
908 * Returns zero on success, or else the status code returned by the
909 * underlying usb_control_msg() call.
910 */
911 int usb_set_configuration(struct usb_device *dev, int configuration)
912 {
913 int i, ret;
914 struct usb_host_config *cp = NULL;
915 void (*disable)(struct usb_device *, int) = dev->bus->op->disable;
916
917 for (i=0; i<dev->descriptor.bNumConfigurations; i++) {
918 if (dev->config[i].desc.bConfigurationValue == configuration) {
919 cp = &dev->config[i];
920 break;
921 }
922 }
923 if ((!cp && configuration != 0) || (cp && configuration == 0)) {
924 warn("selecting invalid configuration %d", configuration);
925 return -EINVAL;
926 }
927
928 /* if it's already configured, clear out old state first. */
929 if (dev->state != USB_STATE_ADDRESS && disable) {
930 for (i = 1 /* skip ep0 */; i < 15; i++) {
931 disable (dev, i);
932 disable (dev, USB_DIR_IN | i);
933 }
934 }
935 dev->toggle[0] = dev->toggle[1] = 0;
936 dev->halted[0] = dev->halted[1] = 0;
937 dev->state = USB_STATE_ADDRESS;
938
939 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
940 USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
941 NULL, 0, HZ * USB_CTRL_SET_TIMEOUT)) < 0)
942 return ret;
943 if (configuration)
944 dev->state = USB_STATE_CONFIGURED;
945 dev->actconfig = cp;
946
947 /* reset more hc/hcd endpoint state */
948 usb_set_maxpacket(dev);
949
950 return 0;
951 }
952
953
954 /**
955 * usb_string - returns ISO 8859-1 version of a string descriptor
956 * @dev: the device whose string descriptor is being retrieved
957 * @index: the number of the descriptor
958 * @buf: where to put the string
959 * @size: how big is "buf"?
960 * Context: !in_interrupt ()
961 *
962 * This converts the UTF-16LE encoded strings returned by devices, from
963 * usb_get_string_descriptor(), to null-terminated ISO-8859-1 encoded ones
964 * that are more usable in most kernel contexts. Note that all characters
965 * in the chosen descriptor that can't be encoded using ISO-8859-1
966 * are converted to the question mark ("?") character, and this function
967 * chooses strings in the first language supported by the device.
968 *
969 * The ASCII (or, redundantly, "US-ASCII") character set is the seven-bit
970 * subset of ISO 8859-1. ISO-8859-1 is the eight-bit subset of Unicode,
971 * and is appropriate for use many uses of English and several other
972 * Western European languages. (But it doesn't include the "Euro" symbol.)
973 *
974 * This call is synchronous, and may not be used in an interrupt context.
975 *
976 * Returns length of the string (>= 0) or usb_control_msg status (< 0).
977 */
978 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
979 {
980 unsigned char *tbuf;
981 int err, len;
982 unsigned int u, idx;
983
984 if (size <= 0 || !buf || !index)
985 return -EINVAL;
986 buf[0] = 0;
987 tbuf = kmalloc(256, GFP_KERNEL);
988 if (!tbuf)
989 return -ENOMEM;
990
991 /* get langid for strings if it's not yet known */
992 if (!dev->have_langid) {
993 err = usb_get_string(dev, 0, 0, tbuf, 4);
994 if (err < 0) {
995 err("error getting string descriptor 0 (error=%d)", err);
996 goto errout;
997 } else if (tbuf[0] < 4) {
998 err("string descriptor 0 too short");
999 err = -EINVAL;
1000 goto errout;
1001 } else {
1002 dev->have_langid = -1;
1003 dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
1004 /* always use the first langid listed */
1005 dbg("USB device number %d default language ID 0x%x",
1006 dev->devnum, dev->string_langid);
1007 }
1008 }
1009
1010 /*
1011 * ask for the length of the string
1012 */
1013
1014 err = usb_get_string(dev, dev->string_langid, index, tbuf, 2);
1015 if(err<2)
1016 goto errout;
1017 len=tbuf[0];
1018
1019 err = usb_get_string(dev, dev->string_langid, index, tbuf, len);
1020 if (err < 0)
1021 goto errout;
1022
1023 size--; /* leave room for trailing NULL char in output buffer */
1024 for (idx = 0, u = 2; u < err; u += 2) {
1025 if (idx >= size)
1026 break;
1027 if (tbuf[u+1]) /* high byte */
1028 buf[idx++] = '?'; /* non ISO-8859-1 character */
1029 else
1030 buf[idx++] = tbuf[u];
1031 }
1032 buf[idx] = 0;
1033 err = idx;
1034
1035 errout:
1036 kfree(tbuf);
1037 return err;
1038 }
1039
1040 // synchronous request completion model
1041 EXPORT_SYMBOL(usb_control_msg);
1042 EXPORT_SYMBOL(usb_bulk_msg);
1043
1044 EXPORT_SYMBOL(usb_sg_init);
1045 EXPORT_SYMBOL(usb_sg_cancel);
1046 EXPORT_SYMBOL(usb_sg_wait);
1047
1048 // synchronous control message convenience routines
1049 EXPORT_SYMBOL(usb_get_descriptor);
1050 EXPORT_SYMBOL(usb_get_device_descriptor);
1051 EXPORT_SYMBOL(usb_get_status);
1052 EXPORT_SYMBOL(usb_get_string);
1053 EXPORT_SYMBOL(usb_string);
1054 EXPORT_SYMBOL(usb_clear_halt);
1055 EXPORT_SYMBOL(usb_set_configuration);
1056 EXPORT_SYMBOL(usb_set_interface);
1057