Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement cooperative multitasking for UnixDatagram #5967

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions tokio/src/runtime/coop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,17 @@ cfg_coop! {
}).unwrap_or(Poll::Ready(RestoreOnPending(Cell::new(Budget::unconstrained()))))
}

#[inline]
pub(crate) fn try_decrement() {
let _ = context::budget(|cell| {
let mut budget = cell.get();

budget.decrement();

cell.set(budget);
});
}

cfg_rt! {
cfg_metrics! {
#[inline(always)]
Expand Down
6 changes: 5 additions & 1 deletion tokio/src/runtime/io/registration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,11 @@ impl Registration {
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
self.clear_readiness(event);
}
x => return x,
x => {
crate::runtime::coop::try_decrement();

return x;
}
}
}
}
Expand Down
65 changes: 54 additions & 11 deletions tokio/src/runtime/io/scheduled_io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,8 @@ struct Readiness<'a> {

/// Entry in the waiter `LinkedList`.
waiter: UnsafeCell<Waiter>,

is_waiter_registered: bool,
}

enum State {
Expand Down Expand Up @@ -429,6 +431,7 @@ impl ScheduledIo {
interest,
_p: PhantomPinned,
}),
is_waiter_registered: false,
}
}
}
Expand Down Expand Up @@ -458,11 +461,46 @@ impl Future for Readiness<'_> {
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
use std::sync::atomic::Ordering::SeqCst;

let (scheduled_io, state, waiter) = unsafe {
let (scheduled_io, state, waiter, is_waiter_registered) = unsafe {
let me = self.get_unchecked_mut();
(&me.scheduled_io, &mut me.state, &me.waiter)
(
&me.scheduled_io,
&mut me.state,
&me.waiter,
&mut me.is_waiter_registered,
)
};

if !crate::runtime::coop::has_budget_remaining() {
// Wasn't ready, take the lock (and check again while locked).
let mut waiters = scheduled_io.waiters.lock();

let w = unsafe { &mut *waiter.get() };

if *is_waiter_registered {
Comment on lines +474 to +480
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I already mentioned this on our Discord chat, but I'll put it here too. This code isn't correct because when the coop budget is empty, you're registering the waker with the IO driver. But in this case, we need to be woken up by the coop system, and not by the IO waker. So you should register for readiness with the coop system instead.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. Thank you for pointing it out. I'm swamped right now with my job and university. I'll get to it as soon as I find some free time.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No worries. That's perfectly fine.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@maminrayej I can take this over from you if you're busy, I'd like to get this change over the finish line relatively quickly.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Noah-Kennedy Absolutely, feel free to take it over. Thanks for stepping in.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no problem!

// Update the waker, if necessary.
if !w.waker.as_ref().unwrap().will_wake(cx.waker()) {
w.waker = Some(cx.waker().clone());
}
} else {
// Safety: called while locked
w.waker = Some(cx.waker().clone());

// Insert the waiter into the linked list
//
// safety: pointers from `UnsafeCell` are never null.
waiters
.list
.push_front(unsafe { NonNull::new_unchecked(waiter.get()) });

*is_waiter_registered = true;
}

drop(waiters);

return Poll::Pending;
}

loop {
match *state {
State::Init => {
Expand Down Expand Up @@ -512,17 +550,22 @@ impl Future for Readiness<'_> {

// Not ready even after locked, insert into list...

// Safety: called while locked
unsafe {
(*waiter.get()).waker = Some(cx.waker().clone());
if !*is_waiter_registered {
// Safety: called while locked
unsafe {
(*waiter.get()).waker = Some(cx.waker().clone());
}

// Insert the waiter into the linked list
//
// safety: pointers from `UnsafeCell` are never null.
waiters
.list
.push_front(unsafe { NonNull::new_unchecked(waiter.get()) });

*is_waiter_registered = true;
}

// Insert the waiter into the linked list
//
// safety: pointers from `UnsafeCell` are never null.
waiters
.list
.push_front(unsafe { NonNull::new_unchecked(waiter.get()) });
*state = State::Waiting;
}
State::Waiting => {
Expand Down
44 changes: 44 additions & 0 deletions tokio/tests/uds_datagram.rs
Original file line number Diff line number Diff line change
Expand Up @@ -411,3 +411,47 @@ async fn poll_ready() -> io::Result<()> {

Ok(())
}

#[tokio::test(flavor = "current_thread")]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the test macro will actually default to this

async fn coop_uds() -> io::Result<()> {
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::{Duration, Instant};

const HELLO: &[u8] = b"hello world";
const DURATION: Duration = Duration::from_secs(1);

let dir = tempfile::tempdir().unwrap();
let server_path = dir.path().join("server.sock");

let client = std::os::unix::net::UnixDatagram::unbound().unwrap();
let server = UnixDatagram::bind(&server_path).unwrap();

let counter = Arc::new(AtomicU32::new(0));

let counter_jh = tokio::spawn({
let counter = counter.clone();

async move {
loop {
tokio::time::sleep(Duration::from_millis(250)).await;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i would recommend avoiding time in tests like this, and instead using yield_now to ensure that tasks wait a certain number of ticks rather than an amount of time. timing makes things brittle

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure how would I do that. Are there any existing tests in the code base that I could reference as a template?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What I'd recommend doing here is rewriting this test such that you have the main task use a pair of UDS sockets to message itself and read the datagram message in a for loop which runs just often enough that it should deplete its budget once, with a second task spawned before the loop which sets a boolean flag and exits to indicate that it run.

You'd then assert after the loop in the main task that the flag was flipped and the second task ran.

counter.fetch_add(1, Ordering::Relaxed);
}
}
});

let mut buf = [0; HELLO.len()];
let start = Instant::now();
while Instant::now().duration_since(start) < DURATION {
let _ = client.send_to(HELLO, &server_path);
let _ = server.recv(&mut buf[..]).await.unwrap();
}

counter_jh.abort();
let _ = counter_jh.await;

let expected = ((DURATION.as_secs() * 4) as f64 * 0.5) as u32;
let counter = counter.load(Ordering::Relaxed);
assert!(counter >= expected);

Ok(())
}
Loading