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