source: mainline/uspace/lib/usbhost/src/bus.c@ eec201d

Last change on this file since eec201d was 64532a97, checked in by Jiří Zárevúcky <jiri.zarevucky@…>, 7 years ago

Fix insufficient buffer size.

  • Property mode set to 100644
File size: 17.3 KB
Line 
1/*
2 * Copyright (c) 2018 Ondrej Hlavaty, Petr Manek
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * - Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * - The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29/** @addtogroup libusbhost
30 * @{
31 */
32/** @file
33 *
34 * The Bus is a structure that serves as an interface of the HC driver
35 * implementation for the usbhost library. Every HC driver that uses libusbhost
36 * must use a bus_t (or its child), fill it with bus_ops and present it to the
37 * library. The library then handles the DDF interface and translates it to the
38 * bus callbacks.
39 */
40
41#include <ddf/driver.h>
42#include <errno.h>
43#include <mem.h>
44#include <macros.h>
45#include <stdio.h>
46#include <str_error.h>
47#include <usb/debug.h>
48#include <usb/dma_buffer.h>
49
50#include "endpoint.h"
51#include "bus.h"
52
53/**
54 * Initializes the base bus structure.
55 */
56void bus_init(bus_t *bus, size_t device_size)
57{
58 assert(bus);
59 assert(device_size >= sizeof(device_t));
60 memset(bus, 0, sizeof(bus_t));
61
62 fibril_mutex_initialize(&bus->guard);
63 bus->device_size = device_size;
64}
65
66/**
67 * Initialize the device_t structure belonging to a bus.
68 */
69int bus_device_init(device_t *dev, bus_t *bus)
70{
71 assert(bus);
72
73 memset(dev, 0, sizeof(*dev));
74
75 dev->bus = bus;
76
77 link_initialize(&dev->link);
78 list_initialize(&dev->devices);
79 fibril_mutex_initialize(&dev->guard);
80
81 return EOK;
82}
83
84/**
85 * Create a name of the ddf function node.
86 */
87int bus_device_set_default_name(device_t *dev)
88{
89 assert(dev);
90 assert(dev->fun);
91
92 char buf[12] = { 0 }; /* usbxyz-ss */
93 snprintf(buf, sizeof(buf), "usb%u-%cs",
94 dev->address, usb_str_speed(dev->speed)[0]);
95
96 return ddf_fun_set_name(dev->fun, buf);
97}
98
99/**
100 * Setup devices Transaction Translation.
101 *
102 * This applies for Low/Full speed devices under High speed hub only. Other
103 * devices just inherit TT from the hub.
104 *
105 * Roothub must be handled specially.
106 */
107static void device_setup_tt(device_t *dev)
108{
109 if (!dev->hub)
110 return;
111
112 if (dev->hub->speed == USB_SPEED_HIGH && usb_speed_is_11(dev->speed)) {
113 /* For LS devices under HS hub */
114 dev->tt.dev = dev->hub;
115 dev->tt.port = dev->port;
116 } else {
117 /* Inherit hub's TT */
118 dev->tt = dev->hub->tt;
119 }
120}
121
122/**
123 * Invoke the device_enumerate bus operation.
124 *
125 * There's no need to synchronize here, because no one knows the device yet.
126 */
127int bus_device_enumerate(device_t *dev)
128{
129 assert(dev);
130
131 if (!dev->bus->ops->device_enumerate)
132 return ENOTSUP;
133
134 if (dev->online)
135 return EINVAL;
136
137 device_setup_tt(dev);
138
139 const int r = dev->bus->ops->device_enumerate(dev);
140 if (r)
141 return r;
142
143 dev->online = true;
144
145 if (dev->hub) {
146 fibril_mutex_lock(&dev->hub->guard);
147 list_append(&dev->link, &dev->hub->devices);
148 fibril_mutex_unlock(&dev->hub->guard);
149 }
150
151 return EOK;
152}
153
154/**
155 * Clean endpoints and children that could have been left behind after
156 * asking the driver of device to offline/remove a device.
157 *
158 * Note that EP0's lifetime is shared with the device, and as such is not
159 * touched.
160 */
161static void device_clean_ep_children(device_t *dev, const char *op)
162{
163 assert(fibril_mutex_is_locked(&dev->guard));
164
165 /* Unregister endpoints left behind. */
166 for (usb_endpoint_t i = 1; i < USB_ENDPOINT_MAX; ++i) {
167 if (!dev->endpoints[i])
168 continue;
169
170 usb_log_warning("USB device '%s' driver left endpoint %u registered after %s.",
171 ddf_fun_get_name(dev->fun), i, op);
172
173 endpoint_t *const ep = dev->endpoints[i];
174 endpoint_add_ref(ep);
175
176 fibril_mutex_unlock(&dev->guard);
177 const int err = bus_endpoint_remove(ep);
178 if (err)
179 usb_log_warning("Endpoint %u cannot be removed. "
180 "Some deffered cleanup was faster?", ep->endpoint);
181
182 endpoint_del_ref(ep);
183 fibril_mutex_lock(&dev->guard);
184 }
185
186 for (usb_endpoint_t i = 1; i < USB_ENDPOINT_MAX; ++i)
187 assert(dev->endpoints[i] == NULL);
188
189 /* Remove also orphaned children. */
190 while (!list_empty(&dev->devices)) {
191 device_t *const child = list_get_instance(list_first(&dev->devices), device_t, link);
192
193 /*
194 * This is not an error condition, as devices cannot remove
195 * their children devices while they are removed, because for
196 * DDF, they are siblings.
197 */
198 usb_log_debug("USB device '%s' driver left device '%s' behind after %s.",
199 ddf_fun_get_name(dev->fun), ddf_fun_get_name(child->fun), op);
200
201 /*
202 * The child node won't disappear, because its parent's driver
203 * is already dead. And the child will need the guard to remove
204 * itself from the list.
205 */
206 fibril_mutex_unlock(&dev->guard);
207 bus_device_gone(child);
208 fibril_mutex_lock(&dev->guard);
209 }
210 assert(list_empty(&dev->devices));
211}
212
213/**
214 * Resolve a USB device that is gone.
215 */
216void bus_device_gone(device_t *dev)
217{
218 assert(dev);
219 assert(dev->fun != NULL);
220
221 const bus_ops_t *ops = dev->bus->ops;
222
223 /* First, block new transfers and operations. */
224 fibril_mutex_lock(&dev->guard);
225 dev->online = false;
226
227 /* Unbinding will need guard unlocked. */
228 fibril_mutex_unlock(&dev->guard);
229
230 /* Remove our device from our hub's children. */
231 if (dev->hub) {
232 fibril_mutex_lock(&dev->hub->guard);
233 list_remove(&dev->link);
234 fibril_mutex_unlock(&dev->hub->guard);
235 }
236
237 /*
238 * Unbind the DDF function. That will result in dev_gone called in
239 * driver, which shall destroy its pipes and remove its children.
240 */
241 const int err = ddf_fun_unbind(dev->fun);
242 if (err) {
243 usb_log_error("Failed to unbind USB device '%s': %s",
244 ddf_fun_get_name(dev->fun), str_error(err));
245 return;
246 }
247
248 /* Remove what driver left behind */
249 fibril_mutex_lock(&dev->guard);
250 device_clean_ep_children(dev, "removing");
251
252 /* Tell the HC to release its resources. */
253 if (ops->device_gone)
254 ops->device_gone(dev);
255
256 /* Check whether the driver didn't forgot EP0 */
257 if (dev->endpoints[0]) {
258 if (ops->endpoint_unregister)
259 ops->endpoint_unregister(dev->endpoints[0]);
260 /* Release the EP0 bus reference */
261 endpoint_del_ref(dev->endpoints[0]);
262 }
263
264 /* Destroy the function, freeing also the device, unlocking mutex. */
265 ddf_fun_destroy(dev->fun);
266}
267
268/**
269 * The user wants this device back online.
270 */
271int bus_device_online(device_t *dev)
272{
273 int rc;
274 assert(dev);
275
276 fibril_mutex_lock(&dev->guard);
277 if (dev->online) {
278 rc = EINVAL;
279 goto err_lock;
280 }
281
282 /* First, tell the HC driver. */
283 const bus_ops_t *ops = dev->bus->ops;
284 if (ops->device_online && (rc = ops->device_online(dev))) {
285 usb_log_warning("Host controller failed to make device '%s' online: %s",
286 ddf_fun_get_name(dev->fun), str_error(rc));
287 goto err_lock;
288 }
289
290 /* Allow creation of new endpoints and communication with the device. */
291 dev->online = true;
292
293 /* Onlining will need the guard */
294 fibril_mutex_unlock(&dev->guard);
295
296 if ((rc = ddf_fun_online(dev->fun))) {
297 usb_log_warning("Failed to take device '%s' online: %s",
298 ddf_fun_get_name(dev->fun), str_error(rc));
299 goto err;
300 }
301
302 usb_log_info("USB Device '%s' is now online.", ddf_fun_get_name(dev->fun));
303 return EOK;
304
305err_lock:
306 fibril_mutex_unlock(&dev->guard);
307err:
308 return rc;
309}
310
311/**
312 * The user requested to take this device offline.
313 */
314int bus_device_offline(device_t *dev)
315{
316 int rc;
317 assert(dev);
318
319 /* Make sure we're the one who offlines this device */
320 if (!dev->online) {
321 rc = ENOENT;
322 goto err;
323 }
324
325 /*
326 * XXX: If the device is removed/offlined just now, this can fail on
327 * assertion. We most probably need some kind of enum status field to
328 * make the synchronization work.
329 */
330
331 /* Tear down all drivers working with the device. */
332 if ((rc = ddf_fun_offline(dev->fun))) {
333 goto err;
334 }
335
336 fibril_mutex_lock(&dev->guard);
337 dev->online = false;
338 device_clean_ep_children(dev, "offlining");
339
340 /* Tell also the HC driver. */
341 const bus_ops_t *ops = dev->bus->ops;
342 if (ops->device_offline)
343 ops->device_offline(dev);
344
345 fibril_mutex_unlock(&dev->guard);
346 usb_log_info("USB Device '%s' is now offline.", ddf_fun_get_name(dev->fun));
347 return EOK;
348
349err:
350 return rc;
351}
352
353/**
354 * Calculate an index to the endpoint array.
355 * For the default control endpoint 0, it must return 0.
356 * For different arguments, the result is stable but not defined.
357 */
358static size_t bus_endpoint_index(usb_endpoint_t ep, usb_direction_t dir)
359{
360 return 2 * ep + (dir == USB_DIRECTION_OUT);
361}
362
363/**
364 * Create and register new endpoint to the bus.
365 *
366 * @param[in] device The device of which the endpoint shall be created
367 * @param[in] desc Endpoint descriptors as reported by the device
368 * @param[out] out_ep The resulting new endpoint reference, if any. Can be NULL.
369 */
370int bus_endpoint_add(device_t *device, const usb_endpoint_descriptors_t *desc, endpoint_t **out_ep)
371{
372 int err;
373 assert(device);
374
375 bus_t *bus = device->bus;
376
377 if (!bus->ops->endpoint_register)
378 return ENOTSUP;
379
380 endpoint_t *ep;
381 if (bus->ops->endpoint_create) {
382 ep = bus->ops->endpoint_create(device, desc);
383 if (!ep)
384 return ENOMEM;
385 } else {
386 ep = calloc(1, sizeof(endpoint_t));
387 if (!ep)
388 return ENOMEM;
389 endpoint_init(ep, device, desc);
390 }
391
392 assert((ep->required_transfer_buffer_policy & ~ep->transfer_buffer_policy) == 0);
393
394 /* Bus reference */
395 endpoint_add_ref(ep);
396
397 const size_t idx = bus_endpoint_index(ep->endpoint, ep->direction);
398 if (idx >= ARRAY_SIZE(device->endpoints)) {
399 usb_log_warning("Invalid endpoint description (ep no %u out of "
400 "bounds)", ep->endpoint);
401 goto drop;
402 }
403
404 if (ep->max_transfer_size == 0) {
405 usb_log_warning("Invalid endpoint description (mps %zu, "
406 "%u packets)", ep->max_packet_size, ep->packets_per_uframe);
407 goto drop;
408 }
409
410 usb_log_debug("Register endpoint %d:%d %s-%s %zuB.",
411 device->address, ep->endpoint,
412 usb_str_transfer_type(ep->transfer_type),
413 usb_str_direction(ep->direction),
414 ep->max_transfer_size);
415
416 fibril_mutex_lock(&device->guard);
417 if (!device->online && ep->endpoint != 0) {
418 err = EAGAIN;
419 } else if (device->endpoints[idx] != NULL) {
420 err = EEXIST;
421 } else {
422 err = bus->ops->endpoint_register(ep);
423 if (!err)
424 device->endpoints[idx] = ep;
425 }
426 fibril_mutex_unlock(&device->guard);
427 if (err) {
428 endpoint_del_ref(ep);
429 return err;
430 }
431
432 if (out_ep) {
433 /* Exporting reference */
434 endpoint_add_ref(ep);
435 *out_ep = ep;
436 }
437
438 return EOK;
439drop:
440 /* Bus reference */
441 endpoint_del_ref(ep);
442 return EINVAL;
443}
444
445/**
446 * Search for an endpoint. Returns a reference.
447 */
448endpoint_t *bus_find_endpoint(device_t *device, usb_endpoint_t endpoint,
449 usb_direction_t dir)
450{
451 assert(device);
452
453 const size_t idx = bus_endpoint_index(endpoint, dir);
454 const size_t ctrl_idx = bus_endpoint_index(endpoint, USB_DIRECTION_BOTH);
455
456 endpoint_t *ep = NULL;
457
458 fibril_mutex_lock(&device->guard);
459 if (idx < ARRAY_SIZE(device->endpoints))
460 ep = device->endpoints[idx];
461 /*
462 * If the endpoint was not found, it's still possible it is a control
463 * endpoint having direction BOTH.
464 */
465 if (!ep && ctrl_idx < ARRAY_SIZE(device->endpoints)) {
466 ep = device->endpoints[ctrl_idx];
467 if (ep && ep->transfer_type != USB_TRANSFER_CONTROL)
468 ep = NULL;
469 }
470 if (ep) {
471 /* Exporting reference */
472 endpoint_add_ref(ep);
473 }
474 fibril_mutex_unlock(&device->guard);
475 return ep;
476}
477
478/**
479 * Remove an endpoint from the device.
480 */
481int bus_endpoint_remove(endpoint_t *ep)
482{
483 assert(ep);
484 assert(ep->device);
485
486 device_t *device = ep->device;
487 if (!device)
488 return ENOENT;
489
490 bus_t *bus = device->bus;
491
492 if (!bus->ops->endpoint_unregister)
493 return ENOTSUP;
494
495 usb_log_debug("Unregister endpoint %d:%d %s-%s %zuB.",
496 device->address, ep->endpoint,
497 usb_str_transfer_type(ep->transfer_type),
498 usb_str_direction(ep->direction),
499 ep->max_transfer_size);
500
501 const size_t idx = bus_endpoint_index(ep->endpoint, ep->direction);
502
503 if (idx >= ARRAY_SIZE(device->endpoints))
504 return EINVAL;
505
506 fibril_mutex_lock(&device->guard);
507
508 /* Check whether the endpoint is registered */
509 if (device->endpoints[idx] != ep) {
510 fibril_mutex_unlock(&device->guard);
511 return EINVAL;
512 }
513
514 bus->ops->endpoint_unregister(ep);
515 device->endpoints[idx] = NULL;
516 fibril_mutex_unlock(&device->guard);
517
518 /* Bus reference */
519 endpoint_del_ref(ep);
520
521 return EOK;
522}
523
524/**
525 * Reserve the default address on the bus for the specified device (hub).
526 */
527int bus_reserve_default_address(bus_t *bus, device_t *dev)
528{
529 assert(bus);
530
531 int err;
532 fibril_mutex_lock(&bus->guard);
533 if (bus->default_address_owner != NULL) {
534 err = (bus->default_address_owner == dev) ? EINVAL : EAGAIN;
535 } else {
536 bus->default_address_owner = dev;
537 err = EOK;
538 }
539 fibril_mutex_unlock(&bus->guard);
540 return err;
541}
542
543/**
544 * Release the default address.
545 */
546void bus_release_default_address(bus_t *bus, device_t *dev)
547{
548 assert(bus);
549
550 fibril_mutex_lock(&bus->guard);
551 if (bus->default_address_owner != dev) {
552 usb_log_error("Device %d tried to release default address, "
553 "which is not reserved for it.", dev->address);
554 } else {
555 bus->default_address_owner = NULL;
556 }
557 fibril_mutex_unlock(&bus->guard);
558}
559
560/**
561 * Assert some conditions on transfer request. As the request is an entity of
562 * HC driver only, we can force these conditions harder. Invalid values from
563 * devices shall be caught on DDF interface already.
564 */
565static void check_request(const transfer_request_t *request)
566{
567 assert(usb_target_is_valid(&request->target));
568 assert(request->dir != USB_DIRECTION_BOTH);
569 /* Non-zero offset => size is non-zero */
570 assert(request->offset == 0 || request->size != 0);
571 /* Non-zero size => buffer is set */
572 assert(request->size == 0 || dma_buffer_is_set(&request->buffer));
573 /* Non-null arg => callback is set */
574 assert(request->arg == NULL || request->on_complete != NULL);
575 assert(request->name);
576}
577
578/**
579 * Initiate a transfer with given device.
580 *
581 * @return Error code.
582 */
583int bus_issue_transfer(device_t *device, const transfer_request_t *request)
584{
585 assert(device);
586 assert(request);
587
588 check_request(request);
589 assert(device->address == request->target.address);
590
591 /* Temporary reference */
592 endpoint_t *ep = bus_find_endpoint(device, request->target.endpoint, request->dir);
593 if (ep == NULL) {
594 usb_log_error("Endpoint(%d:%d) not registered for %s.",
595 device->address, request->target.endpoint, request->name);
596 return ENOENT;
597 }
598
599 assert(ep->device == device);
600
601 const int err = endpoint_send_batch(ep, request);
602
603 /* Temporary reference */
604 endpoint_del_ref(ep);
605
606 return err;
607}
608
609/**
610 * A structure to pass data from the completion callback to the caller.
611 */
612typedef struct {
613 fibril_mutex_t done_mtx;
614 fibril_condvar_t done_cv;
615 bool done;
616
617 size_t transferred_size;
618 int error;
619} sync_data_t;
620
621/**
622 * Callback for finishing the transfer. Wake the issuing thread.
623 */
624static int sync_transfer_complete(void *arg, int error, size_t transferred_size)
625{
626 sync_data_t *d = arg;
627 assert(d);
628 d->transferred_size = transferred_size;
629 d->error = error;
630 fibril_mutex_lock(&d->done_mtx);
631 d->done = true;
632 fibril_condvar_broadcast(&d->done_cv);
633 fibril_mutex_unlock(&d->done_mtx);
634 return EOK;
635}
636
637/**
638 * Issue a transfer on the bus, wait for the result.
639 *
640 * @param device Device for which to send the batch
641 * @param target The target of the transfer.
642 * @param direction A direction of the transfer.
643 * @param data A pointer to the data buffer.
644 * @param size Size of the data buffer.
645 * @param setup_data Data to use in the setup stage (Control communication type)
646 * @param name Communication identifier (for nicer output).
647 */
648errno_t bus_device_send_batch_sync(device_t *device, usb_target_t target,
649 usb_direction_t direction, char *data, size_t size, uint64_t setup_data,
650 const char *name, size_t *transferred_size)
651{
652 int err;
653 sync_data_t sd = { .done = false };
654 fibril_mutex_initialize(&sd.done_mtx);
655 fibril_condvar_initialize(&sd.done_cv);
656
657 transfer_request_t request = {
658 .target = target,
659 .dir = direction,
660 .offset = ((uintptr_t) data) % PAGE_SIZE,
661 .size = size,
662 .setup = setup_data,
663 .on_complete = sync_transfer_complete,
664 .arg = &sd,
665 .name = name,
666 };
667
668 if (data &&
669 (err = dma_buffer_lock(&request.buffer, data - request.offset, size)))
670 return err;
671
672 if ((err = bus_issue_transfer(device, &request))) {
673 dma_buffer_unlock(&request.buffer, size);
674 return err;
675 }
676
677 /*
678 * Note: There are requests that are completed synchronously. It is not
679 * therefore possible to just lock the mutex before and wait.
680 */
681 fibril_mutex_lock(&sd.done_mtx);
682 while (!sd.done)
683 fibril_condvar_wait(&sd.done_cv, &sd.done_mtx);
684 fibril_mutex_unlock(&sd.done_mtx);
685
686 dma_buffer_unlock(&request.buffer, size);
687
688 if (transferred_size)
689 *transferred_size = sd.transferred_size;
690
691 return sd.error;
692}
693
694/**
695 * @}
696 */
Note: See TracBrowser for help on using the repository browser.