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