tokio/runtime/task/state.rs
1use crate::loom::sync::atomic::AtomicUsize;
2
3use std::fmt;
4use std::sync::atomic::Ordering::{AcqRel, Acquire, Release};
5
6pub(super) struct State {
7 val: AtomicUsize,
8}
9
10/// Current state value.
11#[derive(Copy, Clone)]
12pub(super) struct Snapshot(usize);
13
14type UpdateResult = Result<Snapshot, Snapshot>;
15
16/// The task is currently being run.
17const RUNNING: usize = 0b0001;
18
19/// The task is complete.
20///
21/// Once this bit is set, it is never unset.
22const COMPLETE: usize = 0b0010;
23
24/// Extracts the task's lifecycle value from the state.
25const LIFECYCLE_MASK: usize = 0b11;
26
27/// Flag tracking if the task has been pushed into a run queue.
28const NOTIFIED: usize = 0b100;
29
30/// The join handle is still around.
31const JOIN_INTEREST: usize = 0b1_000;
32
33/// A join handle waker has been set.
34const JOIN_WAKER: usize = 0b10_000;
35
36/// The task has been forcibly cancelled.
37const CANCELLED: usize = 0b100_000;
38
39/// All bits.
40const STATE_MASK: usize = LIFECYCLE_MASK | NOTIFIED | JOIN_INTEREST | JOIN_WAKER | CANCELLED;
41
42/// Bits used by the ref count portion of the state.
43const REF_COUNT_MASK: usize = !STATE_MASK;
44
45/// Number of positions to shift the ref count.
46const REF_COUNT_SHIFT: usize = REF_COUNT_MASK.count_zeros() as usize;
47
48/// One ref count.
49const REF_ONE: usize = 1 << REF_COUNT_SHIFT;
50
51/// State a task is initialized with.
52///
53/// A task is initialized with three references:
54///
55/// * A reference that will be stored in an `OwnedTasks` or `LocalOwnedTasks`.
56/// * A reference that will be sent to the scheduler as an ordinary notification.
57/// * A reference for the `JoinHandle`.
58///
59/// As the task starts with a `JoinHandle`, `JOIN_INTEREST` is set.
60/// As the task starts with a `Notified`, `NOTIFIED` is set.
61const INITIAL_STATE: usize = (REF_ONE * 3) | JOIN_INTEREST | NOTIFIED;
62
63#[must_use]
64pub(super) enum TransitionToRunning {
65 Success,
66 Cancelled,
67 Failed,
68 Dealloc,
69}
70
71#[must_use]
72pub(super) enum TransitionToIdle {
73 Ok,
74 OkNotified,
75 OkDealloc,
76 Cancelled,
77}
78
79#[must_use]
80pub(super) enum TransitionToNotifiedByVal {
81 DoNothing,
82 Submit,
83 Dealloc,
84}
85
86#[must_use]
87pub(crate) enum TransitionToNotifiedByRef {
88 DoNothing,
89 Submit,
90}
91
92#[must_use]
93pub(super) struct TransitionToJoinHandleDrop {
94 pub(super) drop_waker: bool,
95 pub(super) drop_output: bool,
96}
97
98/// All transitions are performed via RMW operations. This establishes an
99/// unambiguous modification order.
100impl State {
101 /// Returns a task's initial state.
102 pub(super) fn new() -> State {
103 // The raw task returned by this method has a ref-count of three. See
104 // the comment on INITIAL_STATE for more.
105 State {
106 val: AtomicUsize::new(INITIAL_STATE),
107 }
108 }
109
110 /// Loads the current state, establishes `Acquire` ordering.
111 pub(super) fn load(&self) -> Snapshot {
112 Snapshot(self.val.load(Acquire))
113 }
114
115 /// Attempts to transition the lifecycle to `Running`. This sets the
116 /// notified bit to false so notifications during the poll can be detected.
117 pub(super) fn transition_to_running(&self) -> TransitionToRunning {
118 self.fetch_update_action(|mut next| {
119 let action;
120 assert!(next.is_notified());
121
122 if !next.is_idle() {
123 // This happens if the task is either currently running or if it
124 // has already completed, e.g. if it was cancelled during
125 // shutdown. Consume the ref-count and return.
126 next.ref_dec();
127 if next.ref_count() == 0 {
128 action = TransitionToRunning::Dealloc;
129 } else {
130 action = TransitionToRunning::Failed;
131 }
132 } else {
133 // We are able to lock the RUNNING bit.
134 next.set_running();
135 next.unset_notified();
136
137 if next.is_cancelled() {
138 action = TransitionToRunning::Cancelled;
139 } else {
140 action = TransitionToRunning::Success;
141 }
142 }
143 (action, Some(next))
144 })
145 }
146
147 /// Transitions the task from `Running` -> `Idle`.
148 ///
149 /// The transition to `Idle` fails if the task has been flagged to be
150 /// cancelled.
151 pub(super) fn transition_to_idle(&self) -> TransitionToIdle {
152 self.fetch_update_action(|curr| {
153 assert!(curr.is_running());
154
155 if curr.is_cancelled() {
156 return (TransitionToIdle::Cancelled, None);
157 }
158
159 let mut next = curr;
160 let action;
161 next.unset_running();
162
163 if !next.is_notified() {
164 // Polling the future consumes the ref-count of the Notified.
165 next.ref_dec();
166 if next.ref_count() == 0 {
167 action = TransitionToIdle::OkDealloc;
168 } else {
169 action = TransitionToIdle::Ok;
170 }
171 } else {
172 // The caller will schedule a new notification, so we create a
173 // new ref-count for the notification. Our own ref-count is kept
174 // for now, and the caller will drop it shortly.
175 next.ref_inc();
176 action = TransitionToIdle::OkNotified;
177 }
178
179 (action, Some(next))
180 })
181 }
182
183 /// Transitions the task from `Running` -> `Complete`.
184 pub(super) fn transition_to_complete(&self) -> Snapshot {
185 const DELTA: usize = RUNNING | COMPLETE;
186
187 let prev = Snapshot(self.val.fetch_xor(DELTA, AcqRel));
188 assert!(prev.is_running());
189 assert!(!prev.is_complete());
190
191 Snapshot(prev.0 ^ DELTA)
192 }
193
194 /// Transitions from `Complete` -> `Terminal`, decrementing the reference
195 /// count the specified number of times.
196 ///
197 /// Returns true if the task should be deallocated.
198 pub(super) fn transition_to_terminal(&self, count: usize) -> bool {
199 let prev = Snapshot(self.val.fetch_sub(count * REF_ONE, AcqRel));
200 assert!(
201 prev.ref_count() >= count,
202 "current: {}, sub: {}",
203 prev.ref_count(),
204 count
205 );
206 prev.ref_count() == count
207 }
208
209 /// Transitions the state to `NOTIFIED`.
210 ///
211 /// If no task needs to be submitted, a ref-count is consumed.
212 ///
213 /// If a task needs to be submitted, the ref-count is incremented for the
214 /// new Notified.
215 pub(super) fn transition_to_notified_by_val(&self) -> TransitionToNotifiedByVal {
216 self.fetch_update_action(|mut snapshot| {
217 let action;
218
219 if snapshot.is_running() {
220 // If the task is running, we mark it as notified, but we should
221 // not submit anything as the thread currently running the
222 // future is responsible for that.
223 snapshot.set_notified();
224 snapshot.ref_dec();
225
226 // The thread that set the running bit also holds a ref-count.
227 assert!(snapshot.ref_count() > 0);
228
229 action = TransitionToNotifiedByVal::DoNothing;
230 } else if snapshot.is_complete() || snapshot.is_notified() {
231 // We do not need to submit any notifications, but we have to
232 // decrement the ref-count.
233 snapshot.ref_dec();
234
235 if snapshot.ref_count() == 0 {
236 action = TransitionToNotifiedByVal::Dealloc;
237 } else {
238 action = TransitionToNotifiedByVal::DoNothing;
239 }
240 } else {
241 // We create a new notified that we can submit. The caller
242 // retains ownership of the ref-count they passed in.
243 snapshot.set_notified();
244 snapshot.ref_inc();
245 action = TransitionToNotifiedByVal::Submit;
246 }
247
248 (action, Some(snapshot))
249 })
250 }
251
252 /// Transitions the state to `NOTIFIED`.
253 pub(super) fn transition_to_notified_by_ref(&self) -> TransitionToNotifiedByRef {
254 self.fetch_update_action(|mut snapshot| {
255 if snapshot.is_complete() {
256 // The complete state is final
257 (TransitionToNotifiedByRef::DoNothing, None)
258 } else if snapshot.is_notified() {
259 // Even hough we have nothing to do in this branch,
260 // wake_by_ref() should synchronize-with the task starting execution,
261 // therefore we must use an Release store (with the same value),
262 // to pair with the Acquire in transition_to_running.
263 (TransitionToNotifiedByRef::DoNothing, Some(snapshot))
264 } else if snapshot.is_running() {
265 // If the task is running, we mark it as notified, but we should
266 // not submit as the thread currently running the future is
267 // responsible for that.
268 snapshot.set_notified();
269 (TransitionToNotifiedByRef::DoNothing, Some(snapshot))
270 } else {
271 // The task is idle and not notified. We should submit a
272 // notification.
273 snapshot.set_notified();
274 snapshot.ref_inc();
275 (TransitionToNotifiedByRef::Submit, Some(snapshot))
276 }
277 })
278 }
279
280 cfg_taskdump! {
281 /// Transitions the state to `NOTIFIED`, unconditionally increasing the ref
282 /// count.
283 ///
284 /// Returns `true` if the notified bit was transitioned from `0` to `1`;
285 /// otherwise `false.`
286 pub(super) fn transition_to_notified_for_tracing(&self) -> bool {
287 self.fetch_update_action(|mut snapshot| {
288 if snapshot.is_notified() {
289 (false, None)
290 } else {
291 snapshot.set_notified();
292 snapshot.ref_inc();
293 (true, Some(snapshot))
294 }
295 })
296 }
297 }
298
299 /// Sets the cancelled bit and transitions the state to `NOTIFIED` if idle.
300 ///
301 /// Returns `true` if the task needs to be submitted to the pool for
302 /// execution.
303 pub(super) fn transition_to_notified_and_cancel(&self) -> bool {
304 self.fetch_update_action(|mut snapshot| {
305 if snapshot.is_cancelled() || snapshot.is_complete() {
306 // Aborts to completed or cancelled tasks are no-ops.
307 (false, None)
308 } else if snapshot.is_running() {
309 // If the task is running, we mark it as cancelled. The thread
310 // running the task will notice the cancelled bit when it
311 // stops polling and it will kill the task.
312 //
313 // The set_notified() call is not strictly necessary but it will
314 // in some cases let a wake_by_ref call return without having
315 // to perform a compare_exchange.
316 snapshot.set_notified();
317 snapshot.set_cancelled();
318 (false, Some(snapshot))
319 } else {
320 // The task is idle. We set the cancelled and notified bits and
321 // submit a notification if the notified bit was not already
322 // set.
323 snapshot.set_cancelled();
324 if !snapshot.is_notified() {
325 snapshot.set_notified();
326 snapshot.ref_inc();
327 (true, Some(snapshot))
328 } else {
329 (false, Some(snapshot))
330 }
331 }
332 })
333 }
334
335 /// Sets the `CANCELLED` bit and attempts to transition to `Running`.
336 ///
337 /// Returns `true` if the transition to `Running` succeeded.
338 pub(super) fn transition_to_shutdown(&self) -> bool {
339 let mut prev = Snapshot(0);
340
341 let _ = self.fetch_update(|mut snapshot| {
342 prev = snapshot;
343
344 if snapshot.is_idle() {
345 snapshot.set_running();
346 }
347
348 // If the task was not idle, the thread currently running the task
349 // will notice the cancelled bit and cancel it once the poll
350 // completes.
351 snapshot.set_cancelled();
352 Some(snapshot)
353 });
354
355 prev.is_idle()
356 }
357
358 /// Optimistically tries to swap the state assuming the join handle is
359 /// __immediately__ dropped on spawn.
360 pub(super) fn drop_join_handle_fast(&self) -> Result<(), ()> {
361 use std::sync::atomic::Ordering::Relaxed;
362
363 // Relaxed is acceptable as if this function is called and succeeds,
364 // then nothing has been done w/ the join handle.
365 //
366 // The moment the join handle is used (polled), the `JOIN_WAKER` flag is
367 // set, at which point the CAS will fail.
368 //
369 // Given this, there is no risk if this operation is reordered.
370 self.val
371 .compare_exchange_weak(
372 INITIAL_STATE,
373 (INITIAL_STATE - REF_ONE) & !JOIN_INTEREST,
374 Release,
375 Relaxed,
376 )
377 .map(|_| ())
378 .map_err(|_| ())
379 }
380
381 /// Unsets the `JOIN_INTEREST` flag. If `COMPLETE` is not set, the `JOIN_WAKER`
382 /// flag is also unset.
383 /// The returned `TransitionToJoinHandleDrop` indicates whether the `JoinHandle` should drop
384 /// the output of the future or the join waker after the transition.
385 pub(super) fn transition_to_join_handle_dropped(&self) -> TransitionToJoinHandleDrop {
386 self.fetch_update_action(|mut snapshot| {
387 assert!(snapshot.is_join_interested());
388
389 let mut transition = TransitionToJoinHandleDrop {
390 drop_waker: false,
391 drop_output: false,
392 };
393
394 snapshot.unset_join_interested();
395
396 if !snapshot.is_complete() {
397 // If `COMPLETE` is unset we also unset `JOIN_WAKER` to give the
398 // `JoinHandle` exclusive access to the waker following rule 6 in task/mod.rs.
399 // The `JoinHandle` will drop the waker if it has exclusive access
400 // to drop it.
401 snapshot.unset_join_waker();
402 } else {
403 // If `COMPLETE` is set the task is completed so the `JoinHandle` is responsible
404 // for dropping the output.
405 transition.drop_output = true;
406 }
407
408 if !snapshot.is_join_waker_set() {
409 // If the `JOIN_WAKER` bit is unset and the `JOIN_HANDLE` has exclusive access to
410 // the join waker and should drop it following this transition.
411 // This might happen in two situations:
412 // 1. The task is not completed and we just unset the `JOIN_WAKer` above in this
413 // function.
414 // 2. The task is completed. In that case the `JOIN_WAKER` bit was already unset
415 // by the runtime during completion.
416 transition.drop_waker = true;
417 }
418
419 (transition, Some(snapshot))
420 })
421 }
422
423 /// Sets the `JOIN_WAKER` bit.
424 ///
425 /// Returns `Ok` if the bit is set, `Err` otherwise. This operation fails if
426 /// the task has completed.
427 pub(super) fn set_join_waker(&self) -> UpdateResult {
428 self.fetch_update(|curr| {
429 assert!(curr.is_join_interested());
430 assert!(!curr.is_join_waker_set());
431
432 if curr.is_complete() {
433 return None;
434 }
435
436 let mut next = curr;
437 next.set_join_waker();
438
439 Some(next)
440 })
441 }
442
443 /// Unsets the `JOIN_WAKER` bit.
444 ///
445 /// Returns `Ok` has been unset, `Err` otherwise. This operation fails if
446 /// the task has completed.
447 pub(super) fn unset_waker(&self) -> UpdateResult {
448 self.fetch_update(|curr| {
449 assert!(curr.is_join_interested());
450
451 if curr.is_complete() {
452 return None;
453 }
454
455 // If the task is completed, this bit may have been unset by
456 // `unset_waker_after_complete`.
457 assert!(curr.is_join_waker_set());
458
459 let mut next = curr;
460 next.unset_join_waker();
461
462 Some(next)
463 })
464 }
465
466 /// Unsets the `JOIN_WAKER` bit unconditionally after task completion.
467 ///
468 /// This operation requires the task to be completed.
469 pub(super) fn unset_waker_after_complete(&self) -> Snapshot {
470 let prev = Snapshot(self.val.fetch_and(!JOIN_WAKER, AcqRel));
471 assert!(prev.is_complete());
472 assert!(prev.is_join_waker_set());
473 Snapshot(prev.0 & !JOIN_WAKER)
474 }
475
476 pub(super) fn ref_inc(&self) {
477 use std::process;
478 use std::sync::atomic::Ordering::Relaxed;
479
480 // Using a relaxed ordering is alright here, as knowledge of the
481 // original reference prevents other threads from erroneously deleting
482 // the object.
483 //
484 // As explained in the [Boost documentation][1], Increasing the
485 // reference counter can always be done with memory_order_relaxed: New
486 // references to an object can only be formed from an existing
487 // reference, and passing an existing reference from one thread to
488 // another must already provide any required synchronization.
489 //
490 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
491 let prev = self.val.fetch_add(REF_ONE, Relaxed);
492
493 // If the reference count overflowed, abort.
494 if prev > isize::MAX as usize {
495 process::abort();
496 }
497 }
498
499 /// Returns `true` if the task should be released.
500 pub(super) fn ref_dec(&self) -> bool {
501 let prev = Snapshot(self.val.fetch_sub(REF_ONE, AcqRel));
502 assert!(prev.ref_count() >= 1);
503 prev.ref_count() == 1
504 }
505
506 /// Returns `true` if the task should be released.
507 pub(super) fn ref_dec_twice(&self) -> bool {
508 let prev = Snapshot(self.val.fetch_sub(2 * REF_ONE, AcqRel));
509 assert!(prev.ref_count() >= 2);
510 prev.ref_count() == 2
511 }
512
513 fn fetch_update_action<F, T>(&self, mut f: F) -> T
514 where
515 F: FnMut(Snapshot) -> (T, Option<Snapshot>),
516 {
517 let mut curr = self.load();
518
519 loop {
520 let (output, next) = f(curr);
521 let next = match next {
522 Some(next) => next,
523 None => return output,
524 };
525
526 let res = self.val.compare_exchange(curr.0, next.0, AcqRel, Acquire);
527
528 match res {
529 Ok(_) => return output,
530 Err(actual) => curr = Snapshot(actual),
531 }
532 }
533 }
534
535 fn fetch_update<F>(&self, mut f: F) -> Result<Snapshot, Snapshot>
536 where
537 F: FnMut(Snapshot) -> Option<Snapshot>,
538 {
539 let mut curr = self.load();
540
541 loop {
542 let next = match f(curr) {
543 Some(next) => next,
544 None => return Err(curr),
545 };
546
547 let res = self.val.compare_exchange(curr.0, next.0, AcqRel, Acquire);
548
549 match res {
550 Ok(_) => return Ok(next),
551 Err(actual) => curr = Snapshot(actual),
552 }
553 }
554 }
555}
556
557// ===== impl Snapshot =====
558
559impl Snapshot {
560 /// Returns `true` if the task is in an idle state.
561 pub(super) fn is_idle(self) -> bool {
562 self.0 & (RUNNING | COMPLETE) == 0
563 }
564
565 /// Returns `true` if the task has been flagged as notified.
566 pub(super) fn is_notified(self) -> bool {
567 self.0 & NOTIFIED == NOTIFIED
568 }
569
570 fn unset_notified(&mut self) {
571 self.0 &= !NOTIFIED;
572 }
573
574 fn set_notified(&mut self) {
575 self.0 |= NOTIFIED;
576 }
577
578 pub(super) fn is_running(self) -> bool {
579 self.0 & RUNNING == RUNNING
580 }
581
582 fn set_running(&mut self) {
583 self.0 |= RUNNING;
584 }
585
586 fn unset_running(&mut self) {
587 self.0 &= !RUNNING;
588 }
589
590 pub(super) fn is_cancelled(self) -> bool {
591 self.0 & CANCELLED == CANCELLED
592 }
593
594 fn set_cancelled(&mut self) {
595 self.0 |= CANCELLED;
596 }
597
598 /// Returns `true` if the task's future has completed execution.
599 pub(super) fn is_complete(self) -> bool {
600 self.0 & COMPLETE == COMPLETE
601 }
602
603 pub(super) fn is_join_interested(self) -> bool {
604 self.0 & JOIN_INTEREST == JOIN_INTEREST
605 }
606
607 fn unset_join_interested(&mut self) {
608 self.0 &= !JOIN_INTEREST;
609 }
610
611 pub(super) fn is_join_waker_set(self) -> bool {
612 self.0 & JOIN_WAKER == JOIN_WAKER
613 }
614
615 fn set_join_waker(&mut self) {
616 self.0 |= JOIN_WAKER;
617 }
618
619 fn unset_join_waker(&mut self) {
620 self.0 &= !JOIN_WAKER;
621 }
622
623 pub(super) fn ref_count(self) -> usize {
624 (self.0 & REF_COUNT_MASK) >> REF_COUNT_SHIFT
625 }
626
627 fn ref_inc(&mut self) {
628 assert!(self.0 <= isize::MAX as usize);
629 self.0 += REF_ONE;
630 }
631
632 pub(super) fn ref_dec(&mut self) {
633 assert!(self.ref_count() > 0);
634 self.0 -= REF_ONE;
635 }
636}
637
638impl fmt::Debug for State {
639 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
640 let snapshot = self.load();
641 snapshot.fmt(fmt)
642 }
643}
644
645impl fmt::Debug for Snapshot {
646 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
647 fmt.debug_struct("Snapshot")
648 .field("is_running", &self.is_running())
649 .field("is_complete", &self.is_complete())
650 .field("is_notified", &self.is_notified())
651 .field("is_cancelled", &self.is_cancelled())
652 .field("is_join_interested", &self.is_join_interested())
653 .field("is_join_waker_set", &self.is_join_waker_set())
654 .field("ref_count", &self.ref_count())
655 .finish()
656 }
657}