tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

311 lignes · 11294 octetsBrut · Historique
1//! What a scheduler thread keeps to itself: its run queue ([`Local`]), its
2//! send cache, and the thread-locals they live in. On an actor's fiber,
3//! these are read only in the `#[inline(never)]` functions here, which
4//! never suspend (see `Fiber`'s `Send`).
5
6use std::cell::RefCell;
7use std::sync::Arc;
8
9use crossbeam_deque::{Steal, Worker};
10
11use crate::abi::{UNIT, Value};
12
13use super::Shared;
14use super::actor::Cell;
15use super::hibernate::Parked;
16
17/// What a scheduler thread keeps to itself.
18pub(super) struct Local {
19 /// Its scheduler's address.
20 pub(super) owner: usize,
21 /// Its index among the scheduler's threads.
22 pub(super) index: usize,
23 pub(super) queue: Worker<i64>,
24 /// The actor woken by the one running here, to run next (Tokio's LIFO
25 /// slot, Go's `runnext`): its caches are warm, and no other thread may
26 /// take it. Only with more than one thread (one keeps FIFO order).
27 pub(super) next: Option<i64>,
28 /// Actors run from `next` in a row: two actors waking each other would
29 /// otherwise starve the queue (Tokio 1.29, #5686).
30 pub(super) streak: u8,
31 /// For [`Local::random`].
32 pub(super) seed: u64,
33 /// The actors that parked here, oldest first, to hibernate.
34 pub(super) parked: Parked,
35}
36
37/// Actors run from a thread's next slot in a row, at most (Tokio's cap).
38const NEXT_STREAK: u8 = 3;
39
40/// Where [`place_here`] put an actor.
41pub(super) enum Placed {
42 /// In this thread's next slot: it runs after this slice.
43 Next,
44 /// At the back of this thread's queue; `true` if it is spare work
45 /// another thread should take: queued during a slice (this thread is
46 /// busy), or behind another actor.
47 Queued(bool),
48 /// In the inbound queue of its home, this other thread
49 /// (`Shared::queue`).
50 Inbound(usize),
51 /// Not on this thread: its home is another one, or this is not one of
52 /// the scheduler's threads (`Shared::queue` puts it in the shared
53 /// queue if it has no home).
54 Elsewhere,
55}
56
57/// Slots in a thread's [`SendCache`].
58const SEND_CACHE_SLOTS: usize = 64;
59
60/// The cells of the actors this thread sent to last, by pid (ADR 0028).
61/// Finding a receiver in the actor table takes its read lock and clones
62/// the cell's `Arc`: two atomic writes to lines every sender shares, 15% of
63/// `tests/bench/fanin.lse`'s user time on 22 threads. A hit writes nothing
64/// shared.
65///
66/// A pid is cached on its second miss in a row in its slot: a thread that
67/// sends to many actors in turn (a ring of 1,000) would otherwise evict an
68/// entry on every send, which made `tests/bench/messages.lse` 4% slower
69/// than with no cache.
70///
71/// A cached cell may outlive its actor: its inbox is closed then, so a
72/// send to it is refused, as one to a pid no longer in the table is. Pids
73/// are never reused. At most `SEND_CACHE_SLOTS` cells per thread stay
74/// alive this way, until evicted or the thread stops.
75pub(super) struct SendCache {
76 /// The scheduler the cells belong to (pids are its own).
77 owner: usize,
78 slots: [Slot; SEND_CACHE_SLOTS],
79}
80
81/// A cell found by [`SendCache::get`].
82pub(super) enum Lookup {
83 /// Kept alive by the cache until this thread's next lookup.
84 Cached(*const Cell),
85 /// Not cached (yet).
86 Found(Arc<Cell>),
87}
88
89struct Slot {
90 cell: Option<(i64, Arc<Cell>)>,
91 /// The last pid that missed here.
92 missed: i64,
93}
94
95const EMPTY_SLOT: Slot = Slot {
96 cell: None,
97 missed: 0,
98};
99
100impl SendCache {
101 /// `pid`'s cell; `None` if `pid` is not in the table.
102 pub(super) fn get(&mut self, sched: &Shared, pid: i64) -> Option<Lookup> {
103 let owner = sched as *const Shared as usize;
104 if self.owner != owner {
105 self.clear();
106 self.owner = owner;
107 }
108 let slot = &mut self.slots[pid as usize % SEND_CACHE_SLOTS];
109 if let Some((p, cell)) = &slot.cell
110 && *p == pid
111 {
112 return Some(Lookup::Cached(Arc::as_ptr(cell)));
113 }
114 let cell = sched.cell(pid)?;
115 if slot.missed != pid {
116 slot.missed = pid;
117 return Some(Lookup::Found(cell));
118 }
119 let ptr = Arc::as_ptr(&cell);
120 slot.cell = Some((pid, cell));
121 Some(Lookup::Cached(ptr))
122 }
123
124 pub(super) fn clear(&mut self) {
125 self.slots = [EMPTY_SLOT; SEND_CACHE_SLOTS];
126 }
127}
128
129thread_local! {
130 /// This scheduler thread's run queue and index. Only touched briefly
131 /// (never held across a fiber switch).
132 pub(super) static LOCAL: RefCell<Option<Local>> = const { RefCell::new(None) };
133 /// The call arguments after the sixth (`Ctx::xargs`) of the actors
134 /// this thread runs: written by a caller, copied by the callee before
135 /// it can suspend.
136 pub(super) static XARGS: std::cell::UnsafeCell<[Value; crate::abi::XARGS]> =
137 const { std::cell::UnsafeCell::new([UNIT; crate::abi::XARGS]) };
138 /// Read and written only within one send, which never suspends.
139 pub(super) static SEND_CACHE: RefCell<SendCache> = const {
140 RefCell::new(SendCache {
141 owner: 0,
142 slots: [EMPTY_SLOT; SEND_CACHE_SLOTS],
143 })
144 };
145 /// Times this thread found the shared queue holding actors
146 /// ([`shared_turn`]).
147 static SHARED_SEEN: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
148 /// Set while this thread runs an actor's slice (see [`place_here`]).
149 pub(super) static IN_SLICE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
150}
151
152/// Push to this thread's queue if it is one of `sched`'s threads.
153#[inline(never)]
154pub(super) fn push_local(sched: &Shared, pid: i64) -> bool {
155 LOCAL.with(|l| match &*l.borrow() {
156 Some(local) if local.owner == sched as *const Shared as usize => {
157 local.queue.push(pid);
158 true
159 }
160 _ => false,
161 })
162}
163
164/// Queue `pid`, whose home thread is `home`, here if this is that thread
165/// (or it has none yet): during a slice, in the next slot (an occupant
166/// moves to the back of the queue), else at the back of the queue. Not
167/// inlined (see `Fiber`).
168#[inline(never)]
169pub(super) fn place_here(sched: &Shared, pid: i64, home: usize) -> Placed {
170 LOCAL.with(|l| match &mut *l.borrow_mut() {
171 Some(local)
172 if local.owner == sched as *const Shared as usize
173 && (home == local.index || home == super::NO_HOME) =>
174 {
175 if IN_SLICE.get() && sched.threads() > 1 {
176 match local.next.replace(pid) {
177 None => Placed::Next,
178 Some(displaced) => {
179 local.queue.push(displaced);
180 Placed::Queued(true)
181 }
182 }
183 } else {
184 local.queue.push(pid);
185 Placed::Queued(IN_SLICE.get() || local.queue.len() > 1)
186 }
187 }
188 _ => Placed::Elsewhere,
189 })
190}
191
192/// One time in this many that a thread finds actors in the shared queue,
193/// it takes them before its own (`find_work`). Tokio's figure: rare enough
194/// to keep each thread's queue in order, often enough that an actor
195/// queued there waits for a few dozen slices at most.
196pub(super) const SHARED_TURN: u32 = 61;
197
198/// Whether it is the shared queue's turn ([`SHARED_TURN`]). Called on the
199/// scheduler thread's own stack only.
200pub(super) fn shared_turn() -> bool {
201 let seen = SHARED_SEEN.get().wrapping_add(1);
202 SHARED_SEEN.set(seen);
203 seen.is_multiple_of(SHARED_TURN)
204}
205
206/// The next actor for this thread from its own work: its next slot (at
207/// most [`NEXT_STREAK`] in a row), the actors other threads queued for it
208/// (moved behind its own), its queue, then the shared queue. But one time
209/// in [`SHARED_TURN`] that the shared queue holds actors, it comes first:
210/// actors queued from outside the scheduler with no home yet land there,
211/// and a thread whose own work never runs out would never run them.
212pub(super) fn local_work(sched: &Shared, index: usize) -> Option<i64> {
213 LOCAL.with(|l| {
214 let mut l = l.borrow_mut();
215 let local = l.as_mut()?;
216 if !sched.injector.is_empty()
217 && shared_turn()
218 && let Steal::Success(pid) = sched.injector.steal_batch_and_pop(&local.queue)
219 {
220 return Some(pid);
221 }
222 if let Some(pid) = local.next.take() {
223 if local.streak < NEXT_STREAK {
224 local.streak += 1;
225 super::stat!(Next);
226 return Some(pid);
227 }
228 local.queue.push(pid);
229 }
230 local.streak = 0;
231 let inbound = sched.inbound(index);
232 while !inbound.is_empty() {
233 if let Steal::Empty = inbound.steal_batch(&local.queue) {
234 break;
235 }
236 }
237 if let Some(pid) = local.queue.pop() {
238 return Some(pid);
239 }
240 loop {
241 match sched.injector.steal_batch_and_pop(&local.queue) {
242 Steal::Success(pid) => return Some(pid),
243 Steal::Retry => continue,
244 Steal::Empty => return None,
245 }
246 }
247 })
248}
249
250/// Steal from another thread's queues, starting at a random one (half of
251/// what it holds, `Shared::stealable`).
252pub(super) fn steal(sched: &Shared, index: usize) -> Option<i64> {
253 let threads = sched.threads();
254 LOCAL.with(|l| {
255 let mut l = l.borrow_mut();
256 let local = l.as_mut()?;
257 let start = local.random() % threads;
258 for k in 0..threads {
259 let victim = (start + k) % threads;
260 if victim == index || !sched.stealable(victim) {
261 continue;
262 }
263 loop {
264 let stolen = match sched.stealer(victim).len() {
265 0 => sched.inbound(victim).steal_batch_and_pop(&local.queue),
266 _ => sched.stealer(victim).steal_batch_and_pop(&local.queue),
267 };
268 match stolen {
269 Steal::Success(pid) => return Some(pid),
270 Steal::Retry => continue,
271 Steal::Empty => break,
272 }
273 }
274 }
275 None
276 })
277}
278
279impl Local {
280 /// A cheap random number (xorshift), to pick the first thread to steal
281 /// from: threads starting at the same victim would contend for it.
282 fn random(&mut self) -> usize {
283 let mut x = self.seed;
284 x ^= x << 13;
285 x ^= x >> 7;
286 x ^= x << 17;
287 self.seed = x;
288 x as usize
289 }
290}
291
292/// This thread's index among `sched`'s threads, as a new actor's home
293/// (none off the scheduler's threads). Not inlined (see `Fiber`).
294#[inline(never)]
295pub(super) fn spawner_home(sched: &Shared) -> usize {
296 LOCAL.with(|l| match &*l.borrow() {
297 Some(local) if local.owner == sched as *const Shared as usize => local.index,
298 _ => super::NO_HOME,
299 })
300}
301
302/// This thread's index among `sched`'s threads (0 for other threads).
303/// Not inlined, like every thread-local access on an actor's fiber (see
304/// `Fiber`).
305#[inline(never)]
306pub(super) fn local_index(sched: &Shared) -> usize {
307 LOCAL.with(|l| match &*l.borrow() {
308 Some(local) if local.owner == sched as *const Shared as usize => local.index,
309 _ => 0,
310 })
311}