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

Last change on this file was e199ab3, checked in by Jakub Jermar <jakub@…>, 7 years ago

Fix endpoint reference counting

After commit 498ced1, an endpoint is created with an implicit reference.
Adding an extra reference for creation thus adds a reference that will
never be dropped and the endpoint will be leaked.

This commit removes the extra reference.

  • Property mode set to 100644
File size: 17.2 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 = EINVAL;
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 const size_t idx = bus_endpoint_index(ep->endpoint, ep->direction);
395 if (idx >= ARRAY_SIZE(device->endpoints)) {
396 usb_log_warning("Invalid endpoint description (ep no %u out of "
397 "bounds)", ep->endpoint);
398 goto drop;
399 }
400
401 if (ep->max_transfer_size == 0) {
402 usb_log_warning("Invalid endpoint description (mps %zu, "
403 "%u packets)", ep->max_packet_size, ep->packets_per_uframe);
404 goto drop;
405 }
406
407 usb_log_debug("Register endpoint %d:%d %s-%s %zuB.",
408 device->address, ep->endpoint,
409 usb_str_transfer_type(ep->transfer_type),
410 usb_str_direction(ep->direction),
411 ep->max_transfer_size);
412
413 fibril_mutex_lock(&device->guard);
414 if (!device->online && ep->endpoint != 0) {
415 err = EAGAIN;
416 } else if (device->endpoints[idx] != NULL) {
417 err = EEXIST;
418 } else {
419 err = bus->ops->endpoint_register(ep);
420 if (!err)
421 device->endpoints[idx] = ep;
422 }
423 fibril_mutex_unlock(&device->guard);
424 if (err)
425 goto drop;
426
427 if (out_ep) {
428 /* Exporting reference */
429 endpoint_add_ref(ep);
430 *out_ep = ep;
431 }
432
433 return EOK;
434drop:
435 endpoint_del_ref(ep);
436 return err;
437}
438
439/**
440 * Search for an endpoint. Returns a reference.
441 */
442endpoint_t *bus_find_endpoint(device_t *device, usb_endpoint_t endpoint,
443 usb_direction_t dir)
444{
445 assert(device);
446
447 const size_t idx = bus_endpoint_index(endpoint, dir);
448 const size_t ctrl_idx = bus_endpoint_index(endpoint, USB_DIRECTION_BOTH);
449
450 endpoint_t *ep = NULL;
451
452 fibril_mutex_lock(&device->guard);
453 if (idx < ARRAY_SIZE(device->endpoints))
454 ep = device->endpoints[idx];
455 /*
456 * If the endpoint was not found, it's still possible it is a control
457 * endpoint having direction BOTH.
458 */
459 if (!ep && ctrl_idx < ARRAY_SIZE(device->endpoints)) {
460 ep = device->endpoints[ctrl_idx];
461 if (ep && ep->transfer_type != USB_TRANSFER_CONTROL)
462 ep = NULL;
463 }
464 if (ep) {
465 /* Exporting reference */
466 endpoint_add_ref(ep);
467 }
468 fibril_mutex_unlock(&device->guard);
469 return ep;
470}
471
472/**
473 * Remove an endpoint from the device.
474 */
475int bus_endpoint_remove(endpoint_t *ep)
476{
477 assert(ep);
478 assert(ep->device);
479
480 device_t *device = ep->device;
481 if (!device)
482 return ENOENT;
483
484 bus_t *bus = device->bus;
485
486 if (!bus->ops->endpoint_unregister)
487 return ENOTSUP;
488
489 usb_log_debug("Unregister endpoint %d:%d %s-%s %zuB.",
490 device->address, ep->endpoint,
491 usb_str_transfer_type(ep->transfer_type),
492 usb_str_direction(ep->direction),
493 ep->max_transfer_size);
494
495 const size_t idx = bus_endpoint_index(ep->endpoint, ep->direction);
496
497 if (idx >= ARRAY_SIZE(device->endpoints))
498 return EINVAL;
499
500 fibril_mutex_lock(&device->guard);
501
502 /* Check whether the endpoint is registered */
503 if (device->endpoints[idx] != ep) {
504 fibril_mutex_unlock(&device->guard);
505 return EINVAL;
506 }
507
508 bus->ops->endpoint_unregister(ep);
509 device->endpoints[idx] = NULL;
510 fibril_mutex_unlock(&device->guard);
511
512 /* Bus reference */
513 endpoint_del_ref(ep);
514
515 return EOK;
516}
517
518/**
519 * Reserve the default address on the bus for the specified device (hub).
520 */
521int bus_reserve_default_address(bus_t *bus, device_t *dev)
522{
523 assert(bus);
524
525 int err;
526 fibril_mutex_lock(&bus->guard);
527 if (bus->default_address_owner != NULL) {
528 err = (bus->default_address_owner == dev) ? EINVAL : EAGAIN;
529 } else {
530 bus->default_address_owner = dev;
531 err = EOK;
532 }
533 fibril_mutex_unlock(&bus->guard);
534 return err;
535}
536
537/**
538 * Release the default address.
539 */
540void bus_release_default_address(bus_t *bus, device_t *dev)
541{
542 assert(bus);
543
544 fibril_mutex_lock(&bus->guard);
545 if (bus->default_address_owner != dev) {
546 usb_log_error("Device %d tried to release default address, "
547 "which is not reserved for it.", dev->address);
548 } else {
549 bus->default_address_owner = NULL;
550 }
551 fibril_mutex_unlock(&bus->guard);
552}
553
554/**
555 * Assert some conditions on transfer request. As the request is an entity of
556 * HC driver only, we can force these conditions harder. Invalid values from
557 * devices shall be caught on DDF interface already.
558 */
559static void check_request(const transfer_request_t *request)
560{
561 assert(usb_target_is_valid(&request->target));
562 assert(request->dir != USB_DIRECTION_BOTH);
563 /* Non-zero offset => size is non-zero */
564 assert(request->offset == 0 || request->size != 0);
565 /* Non-zero size => buffer is set */
566 assert(request->size == 0 || dma_buffer_is_set(&request->buffer));
567 /* Non-null arg => callback is set */
568 assert(request->arg == NULL || request->on_complete != NULL);
569 assert(request->name);
570}
571
572/**
573 * Initiate a transfer with given device.
574 *
575 * @return Error code.
576 */
577int bus_issue_transfer(device_t *device, const transfer_request_t *request)
578{
579 assert(device);
580 assert(request);
581
582 check_request(request);
583 assert(device->address == request->target.address);
584
585 /* Temporary reference */
586 endpoint_t *ep = bus_find_endpoint(device, request->target.endpoint, request->dir);
587 if (ep == NULL) {
588 usb_log_error("Endpoint(%d:%d) not registered for %s.",
589 device->address, request->target.endpoint, request->name);
590 return ENOENT;
591 }
592
593 assert(ep->device == device);
594
595 const int err = endpoint_send_batch(ep, request);
596
597 /* Temporary reference */
598 endpoint_del_ref(ep);
599
600 return err;
601}
602
603/**
604 * A structure to pass data from the completion callback to the caller.
605 */
606typedef struct {
607 fibril_mutex_t done_mtx;
608 fibril_condvar_t done_cv;
609 bool done;
610
611 size_t transferred_size;
612 int error;
613} sync_data_t;
614
615/**
616 * Callback for finishing the transfer. Wake the issuing thread.
617 */
618static int sync_transfer_complete(void *arg, int error, size_t transferred_size)
619{
620 sync_data_t *d = arg;
621 assert(d);
622 d->transferred_size = transferred_size;
623 d->error = error;
624 fibril_mutex_lock(&d->done_mtx);
625 d->done = true;
626 fibril_condvar_broadcast(&d->done_cv);
627 fibril_mutex_unlock(&d->done_mtx);
628 return EOK;
629}
630
631/**
632 * Issue a transfer on the bus, wait for the result.
633 *
634 * @param device Device for which to send the batch
635 * @param target The target of the transfer.
636 * @param direction A direction of the transfer.
637 * @param data A pointer to the data buffer.
638 * @param size Size of the data buffer.
639 * @param setup_data Data to use in the setup stage (Control communication type)
640 * @param name Communication identifier (for nicer output).
641 */
642errno_t bus_device_send_batch_sync(device_t *device, usb_target_t target,
643 usb_direction_t direction, char *data, size_t size, uint64_t setup_data,
644 const char *name, size_t *transferred_size)
645{
646 int err;
647 sync_data_t sd = { .done = false };
648 fibril_mutex_initialize(&sd.done_mtx);
649 fibril_condvar_initialize(&sd.done_cv);
650
651 transfer_request_t request = {
652 .target = target,
653 .dir = direction,
654 .offset = ((uintptr_t) data) % PAGE_SIZE,
655 .size = size,
656 .setup = setup_data,
657 .on_complete = sync_transfer_complete,
658 .arg = &sd,
659 .name = name,
660 };
661
662 if (data &&
663 (err = dma_buffer_lock(&request.buffer, data - request.offset, size)))
664 return err;
665
666 if ((err = bus_issue_transfer(device, &request))) {
667 dma_buffer_unlock(&request.buffer, size);
668 return err;
669 }
670
671 /*
672 * Note: There are requests that are completed synchronously. It is not
673 * therefore possible to just lock the mutex before and wait.
674 */
675 fibril_mutex_lock(&sd.done_mtx);
676 while (!sd.done)
677 fibril_condvar_wait(&sd.done_cv, &sd.done_mtx);
678 fibril_mutex_unlock(&sd.done_mtx);
679
680 dma_buffer_unlock(&request.buffer, size);
681
682 if (transferred_size)
683 *transferred_size = sd.transferred_size;
684
685 return sd.error;
686}
687
688/**
689 * @}
690 */
Note: See TracBrowser for help on using the repository browser.