Repository: google/OpenSK
File: third_party/libtock-drivers/src/usb_ctap_hid.rs (Rust)

Code before:
        #[cfg(feature = "verbose_usb")]
        writeln!(Console::new(), "Cancelling USB receive due to timeout").unwrap();
        let result_code =
            unsafe { syscalls::raw::command(DRIVER_NUMBER, command_nr::CANCEL, 0, 0) };
        match result_code {
            // - SUCCESS means that we successfully cancelled the transaction.
            // - EALREADY means that the transaction was already completed.
            SUCCESS | EALREADY => (),
            // - EBUSY means that the transaction is in progress.
            EBUSY => {
                // The app should wait for it, but it may never happen if the remote app crashes.
                // We just return to avoid a deadlock.
                #[cfg(feature = "debug_ctap")]
                writeln!(Console::new(), "Couldn't cancel the USB receive").unwrap();
            }
            _ => panic!(
                "Unexpected error when cancelling USB receive: {:?}",
                result_code
            ),
        }
    }

    core::mem::drop(result);
    core::mem::drop(subscription);
    core::mem::drop(result_code);
    status.get().transpose()
}

fn send_or_recv_with_timeout_detail(
    buf: &mut [u8; 64],
    timeout_delay: Duration<isize>,
    endpoint: UsbEndpoint,
) -> SendOrRecvResult {
    let result = syscalls::allow(DRIVER_NUMBER, allow_nr::TRANSMIT_OR_RECEIVE, buf)?;

    let status = Cell::new(None);
    let mut alarm = |direction, endpoint| {
        status.set(Some(match direction {
            subscribe_nr::callback_status::TRANSMITTED => Ok(SendOrRecvStatus::Sent),
            subscribe_nr::callback_status::RECEIVED => {
                UsbEndpoint::try_from(endpoint).map(|i| SendOrRecvStatus::Received(i))
            }
            // Unknown direction sent by the kernel.
            _ => Err(OutOfRangeError.into()),
        }));
    };

    let subscription = syscalls::subscribe::<callback::Identity2Consumer, _>(
        DRIVER_NUMBER,
        subscribe_nr::TRANSMIT_OR_RECEIVE,
        &mut alarm,

Review comment (suggestion):
We could actually only use `status: Cell<Option<SendOrRecvStatus>> = None` and set to `Some` on the first event (either recv/send or timeout). The second event shouldn't overwrite unless it's recv/send. We yield until `status.get().is_some()`. At the end we can `status.get().unwrap()`.

Code after:
    // Cancel USB transaction if necessary.
    if matches!(status, Ok(SendOrRecvStatus::Timeout)) {
        #[cfg(feature = "verbose_usb")]
        writeln!(Console::new(), "Cancelling USB receive due to timeout").unwrap();
        let result_code =
            unsafe { syscalls::raw::command(DRIVER_NUMBER, command_nr::CANCEL, 0, 0) };
        match result_code {
            // - SUCCESS means that we successfully cancelled the transaction.
            // - EALREADY means that the transaction was already completed.
            SUCCESS | EALREADY => (),
            // - EBUSY means that the transaction is in progress.
            EBUSY => {
                // The app should wait for it, but it may never happen if the remote app crashes.
                // We just return to avoid a deadlock.
                #[cfg(feature = "debug_ctap")]
                writeln!(Console::new(), "Couldn't cancel the USB receive").unwrap();
            }
            _ => panic!(
                "Unexpected error when cancelling USB receive: {:?}",
                result_code
            ),
        }
    }

    core::mem::drop(result);
    core::mem::drop(subscription);
    core::mem::drop(result_code);
    status
}

fn send_or_recv_with_timeout_detail(
    buf: &mut [u8; 64],
    timeout_delay: Duration<isize>,
    endpoint: UsbEndpoint,
) -> TockResult<SendOrRecvStatus> {
    let result = syscalls::allow(DRIVER_NUMBER, allow_nr::TRANSMIT_OR_RECEIVE, buf)?;

    let status = Cell::new(None);
    let mut alarm = |direction, endpoint| {
        status.set(Some(match direction {
            subscribe_nr::callback_status::TRANSMITTED => Ok(SendOrRecvStatus::Sent),
            subscribe_nr::callback_status::RECEIVED => {
                UsbEndpoint::try_from(endpoint).map(|i| SendOrRecvStatus::Received(i))
            }
            // Unknown direction sent by the kernel.
            _ => Err(OutOfRangeError.into()),
        }));
    };

    let subscription = syscalls::subscribe::<callback::Identity2Consumer, _>(
        DRIVER_NUMBER,