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

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

usbhub: revert the runtime binding of bus methods

It was just a dead end.

  • Property mode set to 100644
File size: 16.7 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 bus_endpoint_remove(ep);
178 fibril_mutex_lock(&dev->guard);
179
180 assert(dev->endpoints[i] == NULL);
181 }
182
183 /* Remove also orphaned children. */
184 while (!list_empty(&dev->devices)) {
185 device_t * const child = list_get_instance(list_first(&dev->devices), device_t, link);
186
187 usb_log_warning("USB device '%s' driver left device '%s' behind after %s.",
188 ddf_fun_get_name(dev->fun), ddf_fun_get_name(child->fun), op);
189 /*
190 * The child node won't disappear, because its parent's driver
191 * is already dead. And the child will need the guard to remove
192 * itself from the list.
193 */
194 fibril_mutex_unlock(&dev->guard);
195 bus_device_gone(child);
196 fibril_mutex_lock(&dev->guard);
197 }
198 assert(list_empty(&dev->devices));
199}
200
201/**
202 * Resolve a USB device that is gone.
203 */
204void bus_device_gone(device_t *dev)
205{
206 assert(dev);
207 assert(dev->fun != NULL);
208
209 const bus_ops_t *ops = dev->bus->ops;
210
211 /* First, block new transfers and operations. */
212 fibril_mutex_lock(&dev->guard);
213 dev->online = false;
214
215 /* Unbinding will need guard unlocked. */
216 fibril_mutex_unlock(&dev->guard);
217
218 /* Remove our device from our hub's children. */
219 if (dev->hub) {
220 fibril_mutex_lock(&dev->hub->guard);
221 list_remove(&dev->link);
222 fibril_mutex_unlock(&dev->hub->guard);
223 }
224
225 /*
226 * Unbind the DDF function. That will result in dev_gone called in
227 * driver, which shall destroy its pipes and remove its children.
228 */
229 const int err = ddf_fun_unbind(dev->fun);
230 if (err) {
231 usb_log_error("Failed to unbind USB device '%s': %s",
232 ddf_fun_get_name(dev->fun), str_error(err));
233 return;
234 }
235
236 /* Remove what driver left behind */
237 fibril_mutex_lock(&dev->guard);
238 device_clean_ep_children(dev, "removing");
239
240 /* Tell the HC to release its resources. */
241 if (ops->device_gone)
242 ops->device_gone(dev);
243
244 /* Check whether the driver didn't forgot EP0 */
245 if (dev->endpoints[0]) {
246 if (ops->endpoint_unregister)
247 ops->endpoint_unregister(dev->endpoints[0]);
248 /* Release the EP0 bus reference */
249 endpoint_del_ref(dev->endpoints[0]);
250 }
251
252 /* Destroy the function, freeing also the device, unlocking mutex. */
253 ddf_fun_destroy(dev->fun);
254}
255
256/**
257 * The user wants this device back online.
258 */
259int bus_device_online(device_t *dev)
260{
261 int rc;
262 assert(dev);
263
264 fibril_mutex_lock(&dev->guard);
265 if (dev->online) {
266 rc = EINVAL;
267 goto err_lock;
268 }
269
270 /* First, tell the HC driver. */
271 const bus_ops_t *ops = dev->bus->ops;
272 if (ops->device_online && (rc = ops->device_online(dev))) {
273 usb_log_warning("Host controller failed to make device '%s' online: %s",
274 ddf_fun_get_name(dev->fun), str_error(rc));
275 goto err_lock;
276 }
277
278 /* Allow creation of new endpoints and communication with the device. */
279 dev->online = true;
280
281 /* Onlining will need the guard */
282 fibril_mutex_unlock(&dev->guard);
283
284 if ((rc = ddf_fun_online(dev->fun))) {
285 usb_log_warning("Failed to take device '%s' online: %s",
286 ddf_fun_get_name(dev->fun), str_error(rc));
287 goto err;
288 }
289
290 usb_log_info("USB Device '%s' is now online.", ddf_fun_get_name(dev->fun));
291 return EOK;
292
293err_lock:
294 fibril_mutex_unlock(&dev->guard);
295err:
296 return rc;
297}
298
299/**
300 * The user requested to take this device offline.
301 */
302int bus_device_offline(device_t *dev)
303{
304 int rc;
305 assert(dev);
306
307 /* Make sure we're the one who offlines this device */
308 if (!dev->online) {
309 rc = ENOENT;
310 goto err;
311 }
312
313 /*
314 * XXX: If the device is removed/offlined just now, this can fail on
315 * assertion. We most probably need some kind of enum status field to
316 * make the synchronization work.
317 */
318
319 /* Tear down all drivers working with the device. */
320 if ((rc = ddf_fun_offline(dev->fun))) {
321 goto err;
322 }
323
324 fibril_mutex_lock(&dev->guard);
325 dev->online = false;
326 device_clean_ep_children(dev, "offlining");
327
328 /* Tell also the HC driver. */
329 const bus_ops_t *ops = dev->bus->ops;
330 if (ops->device_offline)
331 ops->device_offline(dev);
332
333 fibril_mutex_unlock(&dev->guard);
334 usb_log_info("USB Device '%s' is now offline.", ddf_fun_get_name(dev->fun));
335 return EOK;
336
337err:
338 return rc;
339}
340
341/**
342 * Calculate an index to the endpoint array.
343 * For the default control endpoint 0, it must return 0.
344 * For different arguments, the result is stable but not defined.
345 */
346static size_t bus_endpoint_index(usb_endpoint_t ep, usb_direction_t dir)
347{
348 return 2 * ep + (dir == USB_DIRECTION_OUT);
349}
350
351/**
352 * Create and register new endpoint to the bus.
353 *
354 * @param[in] device The device of which the endpoint shall be created
355 * @param[in] desc Endpoint descriptors as reported by the device
356 * @param[out] out_ep The resulting new endpoint reference, if any. Can be NULL.
357 */
358int bus_endpoint_add(device_t *device, const usb_endpoint_descriptors_t *desc, endpoint_t **out_ep)
359{
360 int err;
361 assert(device);
362
363 bus_t *bus = device->bus;
364
365 if (!bus->ops->endpoint_register)
366 return ENOTSUP;
367
368 endpoint_t *ep;
369 if (bus->ops->endpoint_create) {
370 ep = bus->ops->endpoint_create(device, desc);
371 if (!ep)
372 return ENOMEM;
373 } else {
374 ep = calloc(1, sizeof(endpoint_t));
375 if (!ep)
376 return ENOMEM;
377 endpoint_init(ep, device, desc);
378 }
379
380 /* Bus reference */
381 endpoint_add_ref(ep);
382
383 const size_t idx = bus_endpoint_index(ep->endpoint, ep->direction);
384 if (idx >= ARRAY_SIZE(device->endpoints)) {
385 usb_log_warning("Invalid endpoint description (ep no %u out of "
386 "bounds)", ep->endpoint);
387 goto drop;
388 }
389
390 if (ep->max_transfer_size == 0) {
391 usb_log_warning("Invalid endpoint description (mps %zu, "
392 "%u packets)", ep->max_packet_size, ep->packets_per_uframe);
393 goto drop;
394 }
395
396 usb_log_debug("Register endpoint %d:%d %s-%s %zuB.",
397 device->address, ep->endpoint,
398 usb_str_transfer_type(ep->transfer_type),
399 usb_str_direction(ep->direction),
400 ep->max_transfer_size);
401
402 fibril_mutex_lock(&device->guard);
403 if (!device->online && ep->endpoint != 0) {
404 err = EAGAIN;
405 } else if (device->endpoints[idx] != NULL) {
406 err = EEXIST;
407 } else {
408 err = bus->ops->endpoint_register(ep);
409 if (!err)
410 device->endpoints[idx] = ep;
411 }
412 fibril_mutex_unlock(&device->guard);
413 if (err) {
414 endpoint_del_ref(ep);
415 return err;
416 }
417
418 if (out_ep) {
419 /* Exporting reference */
420 endpoint_add_ref(ep);
421 *out_ep = ep;
422 }
423
424 return EOK;
425drop:
426 /* Bus reference */
427 endpoint_del_ref(ep);
428 return EINVAL;
429}
430
431/**
432 * Search for an endpoint. Returns a reference.
433 */
434endpoint_t *bus_find_endpoint(device_t *device, usb_endpoint_t endpoint,
435 usb_direction_t dir)
436{
437 assert(device);
438
439 const size_t idx = bus_endpoint_index(endpoint, dir);
440 const size_t ctrl_idx = bus_endpoint_index(endpoint, USB_DIRECTION_BOTH);
441
442 endpoint_t *ep = NULL;
443
444 fibril_mutex_lock(&device->guard);
445 if (idx < ARRAY_SIZE(device->endpoints))
446 ep = device->endpoints[idx];
447 /*
448 * If the endpoint was not found, it's still possible it is a control
449 * endpoint having direction BOTH.
450 */
451 if (!ep && ctrl_idx < ARRAY_SIZE(device->endpoints)) {
452 ep = device->endpoints[ctrl_idx];
453 if (ep && ep->transfer_type != USB_TRANSFER_CONTROL)
454 ep = NULL;
455 }
456 if (ep) {
457 /* Exporting reference */
458 endpoint_add_ref(ep);
459 }
460 fibril_mutex_unlock(&device->guard);
461 return ep;
462}
463
464/**
465 * Remove an endpoint from the device. Consumes a reference.
466 */
467int bus_endpoint_remove(endpoint_t *ep)
468{
469 assert(ep);
470 assert(ep->device);
471
472 device_t *device = ep->device;
473 if (!device)
474 return ENOENT;
475
476 bus_t *bus = device->bus;
477
478 if (!bus->ops->endpoint_unregister)
479 return ENOTSUP;
480
481 usb_log_debug("Unregister endpoint %d:%d %s-%s %zuB.",
482 device->address, ep->endpoint,
483 usb_str_transfer_type(ep->transfer_type),
484 usb_str_direction(ep->direction),
485 ep->max_transfer_size);
486
487 const size_t idx = bus_endpoint_index(ep->endpoint, ep->direction);
488
489 if (idx >= ARRAY_SIZE(device->endpoints))
490 return EINVAL;
491
492 fibril_mutex_lock(&device->guard);
493 bus->ops->endpoint_unregister(ep);
494 device->endpoints[idx] = NULL;
495 fibril_mutex_unlock(&device->guard);
496
497 /* Bus reference */
498 endpoint_del_ref(ep);
499
500 /* Given reference */
501 endpoint_del_ref(ep);
502
503 return EOK;
504}
505
506/**
507 * Reserve the default address on the bus for the specified device (hub).
508 */
509int bus_reserve_default_address(bus_t *bus, device_t *dev)
510{
511 assert(bus);
512
513 int err;
514 fibril_mutex_lock(&bus->guard);
515 if (bus->default_address_owner != NULL) {
516 err = (bus->default_address_owner == dev) ? EINVAL : EAGAIN;
517 } else {
518 bus->default_address_owner = dev;
519 err = EOK;
520 }
521 fibril_mutex_unlock(&bus->guard);
522 return err;
523}
524
525/**
526 * Release the default address.
527 */
528void bus_release_default_address(bus_t *bus, device_t *dev)
529{
530 assert(bus);
531
532 fibril_mutex_lock(&bus->guard);
533 if (bus->default_address_owner != dev) {
534 usb_log_error("Device %d tried to release default address, "
535 "which is not reserved for it.", dev->address);
536 } else {
537 bus->default_address_owner = NULL;
538 }
539 fibril_mutex_unlock(&bus->guard);
540}
541
542/**
543 * Initiate a transfer on the bus. Finds the target endpoint, creates
544 * a transfer batch and schedules it.
545 *
546 * @param device Device for which to send the batch
547 * @param target The target of the transfer.
548 * @param direction A direction of the transfer.
549 * @param data A pointer to the data buffer.
550 * @param size Size of the data buffer.
551 * @param setup_data Data to use in the setup stage (Control communication type)
552 * @param on_complete Callback which is called after the batch is complete
553 * @param arg Callback parameter.
554 * @param name Communication identifier (for nicer output).
555 * @return Error code.
556 */
557int bus_device_send_batch(device_t *device, usb_target_t target,
558 usb_direction_t direction, char *data, size_t size, uint64_t setup_data,
559 usbhc_iface_transfer_callback_t on_complete, void *arg, const char *name)
560{
561 assert(device->address == target.address);
562
563 /* Temporary reference */
564 endpoint_t *ep = bus_find_endpoint(device, target.endpoint, direction);
565 if (ep == NULL) {
566 usb_log_error("Endpoint(%d:%d) not registered for %s.",
567 device->address, target.endpoint, name);
568 return ENOENT;
569 }
570
571 assert(ep->device == device);
572
573 /*
574 * This method is already callable from HC only, so we can force these
575 * conditions harder.
576 * Invalid values from devices shall be caught on DDF interface already.
577 */
578 assert(usb_target_is_valid(&target));
579 assert(direction != USB_DIRECTION_BOTH);
580 assert(size == 0 || data != NULL);
581 assert(arg == NULL || on_complete != NULL);
582 assert(name);
583
584 const int err = endpoint_send_batch(ep, target, direction,
585 data, size, setup_data, on_complete, arg, name);
586
587 /* Temporary reference */
588 endpoint_del_ref(ep);
589
590 return err;
591}
592
593/**
594 * A structure to pass data from the completion callback to the caller.
595 */
596typedef struct {
597 fibril_mutex_t done_mtx;
598 fibril_condvar_t done_cv;
599 bool done;
600
601 size_t transferred_size;
602 int error;
603} sync_data_t;
604
605/**
606 * Callback for finishing the transfer. Wake the issuing thread.
607 */
608static int sync_transfer_complete(void *arg, int error, size_t transferred_size)
609{
610 sync_data_t *d = arg;
611 assert(d);
612 d->transferred_size = transferred_size;
613 d->error = error;
614 fibril_mutex_lock(&d->done_mtx);
615 d->done = true;
616 fibril_condvar_broadcast(&d->done_cv);
617 fibril_mutex_unlock(&d->done_mtx);
618 return EOK;
619}
620
621/**
622 * Issue a transfer on the bus, wait for the result.
623 *
624 * @param device Device for which to send the batch
625 * @param target The target of the transfer.
626 * @param direction A direction of the transfer.
627 * @param data A pointer to the data buffer.
628 * @param size Size of the data buffer.
629 * @param setup_data Data to use in the setup stage (Control communication type)
630 * @param name Communication identifier (for nicer output).
631 */
632ssize_t bus_device_send_batch_sync(device_t *device, usb_target_t target,
633 usb_direction_t direction, char *data, size_t size, uint64_t setup_data,
634 const char *name)
635{
636 sync_data_t sd = { .done = false };
637 fibril_mutex_initialize(&sd.done_mtx);
638 fibril_condvar_initialize(&sd.done_cv);
639
640 const int ret = bus_device_send_batch(device, target, direction,
641 data, size, setup_data, sync_transfer_complete, &sd, name);
642 if (ret != EOK)
643 return ret;
644
645 /*
646 * Note: There are requests that are completed synchronously. It is not
647 * therefore possible to just lock the mutex before and wait.
648 */
649 fibril_mutex_lock(&sd.done_mtx);
650 while (!sd.done)
651 fibril_condvar_wait(&sd.done_cv, &sd.done_mtx);
652 fibril_mutex_unlock(&sd.done_mtx);
653
654 return (sd.error == EOK)
655 ? (ssize_t) sd.transferred_size
656 : (ssize_t) sd.error;
657}
658
659/**
660 * @}
661 */
Note: See TracBrowser for help on using the repository browser.