io: Track device in usbi_transfer

transfer->dev_handle currently has the behaviour that it will be unset
if the device is closed. The sync API uses this fact to catch an error

In other cases, transfer->dev_handle will keep its value, which means
that if the transfer lives longer than the device handle, the pointer
becomes invalid.

The transfer does however keep a reference to the device, which owns the
pointer to the context. As such, we can track this reference internal to
the transfer, and it is set while the transfer is in-flight.

With this, switch the logging infrastructure to use itransfer->dev->ctx
while checking that itransfer->dev is non-NULL.

Note that this was a regression caused by 6cae9c6 ("core: update
usbi_dbg to take the context as an argument"), specifically when
resolving the context while freeing a transfer after closing a device.

Note that the transfer will now keep a reference to the device until it
is free'ed. This allows it to use the correct context for logging even
in libusb_free_transfer.

The alternative to all this would be to just explicitly pass NULL to the
log handler in libusb_free_transfer.

Fixes #1038
Closes #1073
3 files changed