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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since fdc2253b was 1bab1c8, checked in by Ondřej Hlavatý <aearsis@…>, 8 years ago

libusbhost: bus_remove_endpoint no longer consumes a reference

  • Property mode set to 100644
File size: 17.1 KB
Line 
1/*
2 * Copyright (c) 2017 Ondrej Hlavaty <aearsis@eideo.cz>
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
49#include "endpoint.h"
50#include "bus.h"
51
52/**
53 * Initializes the base bus structure.
54 */
55void bus_init(bus_t *bus, size_t device_size)
56{
57 assert(bus);
58 assert(device_size >= sizeof(device_t));
59 memset(bus, 0, sizeof(bus_t));
60
61 fibril_mutex_initialize(&bus->guard);
62 bus->device_size = device_size;
63}
64
65/**
66 * Initialize the device_t structure belonging to a bus.
67 */
68int bus_device_init(device_t *dev, bus_t *bus)
69{
70 assert(bus);
71
72 memset(dev, 0, sizeof(*dev));
73
74 dev->bus = bus;
75
76 link_initialize(&dev->link);
77 list_initialize(&dev->devices);
78 fibril_mutex_initialize(&dev->guard);
79
80 return EOK;
81}
82
83/**
84 * Create a name of the ddf function node.
85 */
86int bus_device_set_default_name(device_t *dev)
87{
88 assert(dev);
89 assert(dev->fun);
90
91 char buf[10] = { 0 }; /* usbxyz-ss */
92 snprintf(buf, sizeof(buf), "usb%u-%cs",
93 dev->address, usb_str_speed(dev->speed)[0]);
94
95 return ddf_fun_set_name(dev->fun, buf);
96}
97
98/**
99 * Setup devices Transaction Translation.
100 *
101 * This applies for Low/Full speed devices under High speed hub only. Other
102 * devices just inherit TT from the hub.
103 *
104 * Roothub must be handled specially.
105 */
106static void device_setup_tt(device_t *dev)
107{
108 if (!dev->hub)
109 return;
110
111 if (dev->hub->speed == USB_SPEED_HIGH && usb_speed_is_11(dev->speed)) {
112 /* For LS devices under HS hub */
113 dev->tt.dev = dev->hub;
114 dev->tt.port = dev->port;
115 }
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 /* Bus reference */
393 endpoint_add_ref(ep);
394
395 const size_t idx = bus_endpoint_index(ep->endpoint, ep->direction);
396 if (idx >= ARRAY_SIZE(device->endpoints)) {
397 usb_log_warning("Invalid endpoint description (ep no %u out of "
398 "bounds)", ep->endpoint);
399 goto drop;
400 }
401
402 if (ep->max_transfer_size == 0) {
403 usb_log_warning("Invalid endpoint description (mps %zu, "
404 "%u packets)", ep->max_packet_size, ep->packets_per_uframe);
405 goto drop;
406 }
407
408 usb_log_debug("Register endpoint %d:%d %s-%s %zuB.",
409 device->address, ep->endpoint,
410 usb_str_transfer_type(ep->transfer_type),
411 usb_str_direction(ep->direction),
412 ep->max_transfer_size);
413
414 fibril_mutex_lock(&device->guard);
415 if (!device->online && ep->endpoint != 0) {
416 err = EAGAIN;
417 } else if (device->endpoints[idx] != NULL) {
418 err = EEXIST;
419 } else {
420 err = bus->ops->endpoint_register(ep);
421 if (!err)
422 device->endpoints[idx] = ep;
423 }
424 fibril_mutex_unlock(&device->guard);
425 if (err) {
426 endpoint_del_ref(ep);
427 return err;
428 }
429
430 if (out_ep) {
431 /* Exporting reference */
432 endpoint_add_ref(ep);
433 *out_ep = ep;
434 }
435
436 return EOK;
437drop:
438 /* Bus reference */
439 endpoint_del_ref(ep);
440 return EINVAL;
441}
442
443/**
444 * Search for an endpoint. Returns a reference.
445 */
446endpoint_t *bus_find_endpoint(device_t *device, usb_endpoint_t endpoint,
447 usb_direction_t dir)
448{
449 assert(device);
450
451 const size_t idx = bus_endpoint_index(endpoint, dir);
452 const size_t ctrl_idx = bus_endpoint_index(endpoint, USB_DIRECTION_BOTH);
453
454 endpoint_t *ep = NULL;
455
456 fibril_mutex_lock(&device->guard);
457 if (idx < ARRAY_SIZE(device->endpoints))
458 ep = device->endpoints[idx];
459 /*
460 * If the endpoint was not found, it's still possible it is a control
461 * endpoint having direction BOTH.
462 */
463 if (!ep && ctrl_idx < ARRAY_SIZE(device->endpoints)) {
464 ep = device->endpoints[ctrl_idx];
465 if (ep && ep->transfer_type != USB_TRANSFER_CONTROL)
466 ep = NULL;
467 }
468 if (ep) {
469 /* Exporting reference */
470 endpoint_add_ref(ep);
471 }
472 fibril_mutex_unlock(&device->guard);
473 return ep;
474}
475
476/**
477 * Remove an endpoint from the device.
478 */
479int bus_endpoint_remove(endpoint_t *ep)
480{
481 assert(ep);
482 assert(ep->device);
483
484 device_t *device = ep->device;
485 if (!device)
486 return ENOENT;
487
488 bus_t *bus = device->bus;
489
490 if (!bus->ops->endpoint_unregister)
491 return ENOTSUP;
492
493 usb_log_debug("Unregister endpoint %d:%d %s-%s %zuB.",
494 device->address, ep->endpoint,
495 usb_str_transfer_type(ep->transfer_type),
496 usb_str_direction(ep->direction),
497 ep->max_transfer_size);
498
499 const size_t idx = bus_endpoint_index(ep->endpoint, ep->direction);
500
501 if (idx >= ARRAY_SIZE(device->endpoints))
502 return EINVAL;
503
504 fibril_mutex_lock(&device->guard);
505
506 /* Check whether the endpoint is registered */
507 if (device->endpoints[idx] != ep) {
508 fibril_mutex_unlock(&device->guard);
509 return EINVAL;
510 }
511
512 bus->ops->endpoint_unregister(ep);
513 device->endpoints[idx] = NULL;
514 fibril_mutex_unlock(&device->guard);
515
516 /* Bus reference */
517 endpoint_del_ref(ep);
518
519 return EOK;
520}
521
522/**
523 * Reserve the default address on the bus for the specified device (hub).
524 */
525int bus_reserve_default_address(bus_t *bus, device_t *dev)
526{
527 assert(bus);
528
529 int err;
530 fibril_mutex_lock(&bus->guard);
531 if (bus->default_address_owner != NULL) {
532 err = (bus->default_address_owner == dev) ? EINVAL : EAGAIN;
533 } else {
534 bus->default_address_owner = dev;
535 err = EOK;
536 }
537 fibril_mutex_unlock(&bus->guard);
538 return err;
539}
540
541/**
542 * Release the default address.
543 */
544void bus_release_default_address(bus_t *bus, device_t *dev)
545{
546 assert(bus);
547
548 fibril_mutex_lock(&bus->guard);
549 if (bus->default_address_owner != dev) {
550 usb_log_error("Device %d tried to release default address, "
551 "which is not reserved for it.", dev->address);
552 } else {
553 bus->default_address_owner = NULL;
554 }
555 fibril_mutex_unlock(&bus->guard);
556}
557
558/**
559 * Initiate a transfer on the bus. Finds the target endpoint, creates
560 * a transfer batch and schedules it.
561 *
562 * @param device Device for which to send the batch
563 * @param target The target of the transfer.
564 * @param direction A direction of the transfer.
565 * @param data A pointer to the data buffer.
566 * @param size Size of the data buffer.
567 * @param setup_data Data to use in the setup stage (Control communication type)
568 * @param on_complete Callback which is called after the batch is complete
569 * @param arg Callback parameter.
570 * @param name Communication identifier (for nicer output).
571 * @return Error code.
572 */
573int bus_device_send_batch(device_t *device, usb_target_t target,
574 usb_direction_t direction, char *data, size_t size, uint64_t setup_data,
575 usbhc_iface_transfer_callback_t on_complete, void *arg, const char *name)
576{
577 assert(device->address == target.address);
578
579 /* Temporary reference */
580 endpoint_t *ep = bus_find_endpoint(device, target.endpoint, direction);
581 if (ep == NULL) {
582 usb_log_error("Endpoint(%d:%d) not registered for %s.",
583 device->address, target.endpoint, name);
584 return ENOENT;
585 }
586
587 assert(ep->device == device);
588
589 /*
590 * This method is already callable from HC only, so we can force these
591 * conditions harder.
592 * Invalid values from devices shall be caught on DDF interface already.
593 */
594 assert(usb_target_is_valid(&target));
595 assert(direction != USB_DIRECTION_BOTH);
596 assert(size == 0 || data != NULL);
597 assert(arg == NULL || on_complete != NULL);
598 assert(name);
599
600 const int err = endpoint_send_batch(ep, target, direction,
601 data, size, setup_data, on_complete, arg, name);
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 */
648ssize_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)
651{
652 sync_data_t sd = { .done = false };
653 fibril_mutex_initialize(&sd.done_mtx);
654 fibril_condvar_initialize(&sd.done_cv);
655
656 const int ret = bus_device_send_batch(device, target, direction,
657 data, size, setup_data, sync_transfer_complete, &sd, name);
658 if (ret != EOK)
659 return ret;
660
661 /*
662 * Note: There are requests that are completed synchronously. It is not
663 * therefore possible to just lock the mutex before and wait.
664 */
665 fibril_mutex_lock(&sd.done_mtx);
666 while (!sd.done)
667 fibril_condvar_wait(&sd.done_cv, &sd.done_mtx);
668 fibril_mutex_unlock(&sd.done_mtx);
669
670 return (sd.error == EOK)
671 ? (ssize_t) sd.transferred_size
672 : (ssize_t) sd.error;
673}
674
675/**
676 * @}
677 */
Note: See TracBrowser for help on using the repository browser.