mmtk/scheduler/
scheduler.rs

1use self::worker::PollResult;
2
3use super::gc_work::ScheduleCollection;
4use super::stat::SchedulerStat;
5use super::work_bucket::*;
6use super::worker::{GCWorker, ThreadId, WorkerGroup};
7use super::worker_goals::{WorkerGoal, WorkerGoals};
8use super::worker_monitor::{LastParkedResult, WorkerMonitor};
9use super::*;
10use crate::mmtk::MMTK;
11use crate::plan::tracing::gc_work::weakref::{
12    VMForwardWeakRefs, VMPostForwarding, VMProcessWeakRefs,
13};
14use crate::plan::Pause;
15use crate::util::opaque_pointer::*;
16use crate::util::options::AffinityKind;
17use crate::util::options::PlanSelector;
18use crate::vm::Collection;
19use crate::vm::VMBinding;
20use crate::Plan;
21use crossbeam::deque::Steal;
22use enum_map::{Enum, EnumMap};
23use std::collections::HashMap;
24use std::sync::Arc;
25
26pub struct GCWorkScheduler<VM: VMBinding> {
27    /// Work buckets
28    pub work_buckets: EnumMap<WorkBucketStage, WorkBucket<VM>>,
29    /// Workers
30    pub(crate) worker_group: Arc<WorkerGroup<VM>>,
31    /// For synchronized communication between workers and with mutators.
32    pub(crate) worker_monitor: Arc<WorkerMonitor>,
33    /// How to assign the affinity of each GC thread. Specified by the user.
34    affinity: AffinityKind,
35}
36
37// FIXME: GCWorkScheduler should be naturally Sync, but we cannot remove this `impl` yet.
38// Some subtle interaction between ObjectRememberingBarrier, Mutator and some GCWork instances
39// makes the compiler think WorkBucket is not Sync.
40unsafe impl<VM: VMBinding> Sync for GCWorkScheduler<VM> {}
41
42impl<VM: VMBinding> GCWorkScheduler<VM> {
43    pub fn new(num_workers: usize, affinity: AffinityKind) -> Arc<Self> {
44        assert!(num_workers > 0);
45        let worker_monitor: Arc<WorkerMonitor> = Arc::new(WorkerMonitor::new(num_workers));
46        let worker_group = WorkerGroup::new(num_workers);
47
48        // Create work buckets for workers.
49        let mut work_buckets = EnumMap::from_fn(|stage: WorkBucketStage| {
50            WorkBucket::new(stage, worker_monitor.clone())
51        });
52
53        // Set the open condition of each bucket.
54        {
55            let mut open_stages: Vec<WorkBucketStage> = vec![WorkBucketStage::FIRST_STW_STAGE];
56            let stages = (0..WorkBucketStage::LENGTH).map(WorkBucketStage::from_usize);
57            for stage in stages {
58                if stage.is_sequentially_opened() {
59                    let cur_stages = open_stages.clone();
60                    // Other work packets will be opened after previous stages are done
61                    // (i.e their buckets are drained and all workers parked).
62                    work_buckets[stage].set_open_condition(
63                        move |scheduler: &GCWorkScheduler<VM>| {
64                            debug!(
65                                "Check if {:?} can be opened? These needs to be drained: {:?}",
66                                stage, cur_stages
67                            );
68                            scheduler.are_buckets_drained(&cur_stages)
69                        },
70                    );
71                    open_stages.push(stage);
72                }
73            }
74        }
75
76        Arc::new(Self {
77            work_buckets,
78            worker_group,
79            worker_monitor,
80            affinity,
81        })
82    }
83
84    pub fn process_concurrent_packets_in_pause(&self) {
85        let mut packets = vec![];
86        // Buggy
87        let bucket = &self.work_buckets[WorkBucketStage::Concurrent];
88        loop {
89            if bucket.is_empty() {
90                break;
91            }
92            match bucket.get_queue().steal() {
93                Steal::Success(w) => packets.push(w),
94                Steal::Empty => break,
95                Steal::Retry => {}
96            }
97        }
98        if !packets.is_empty() {
99            self.work_buckets[WorkBucketStage::STWRCDecsAndSweep].bulk_add(packets);
100        }
101    }
102
103    pub fn num_workers(&self) -> usize {
104        self.worker_group.as_ref().worker_count()
105    }
106
107    pub fn set_active_workers(&self, active_workers: usize) {
108        self.worker_monitor.set_active_workers(active_workers);
109    }
110
111    pub fn num_active_workers(&self) -> usize {
112        self.worker_monitor.active_workers()
113    }
114
115    pub(crate) fn is_worker_active(&self, ordinal: usize) -> bool {
116        self.worker_monitor.is_worker_active(ordinal)
117    }
118
119    /// Create GC threads for the first time.  It will also create the `GCWorker` instances.
120    ///
121    /// Currently GC threads only include worker threads, and we currently have only one worker
122    /// group.  We may add more worker groups in the future.
123    pub fn spawn_gc_threads(self: &Arc<Self>, mmtk: &'static MMTK<VM>, tls: VMThread) {
124        self.worker_group.initial_spawn(tls, mmtk);
125    }
126
127    /// Ask all GC workers to exit for forking.
128    pub fn stop_gc_threads_for_forking(self: &Arc<Self>) {
129        self.worker_group.prepare_surrender_buffer();
130
131        debug!("A mutator is requesting GC threads to stop for forking...");
132        self.worker_monitor.make_request(WorkerGoal::StopForFork);
133    }
134
135    /// Ask all GC workers to exit permanently.
136    pub fn shutdown_gc_threads(self: &Arc<Self>) {
137        self.worker_group.prepare_surrender_buffer();
138
139        info!("A mutator is requesting GC threads to shut down...");
140        self.worker_monitor.make_request(WorkerGoal::Shutdown);
141    }
142
143    /// Surrender the `GCWorker` struct of a GC worker when it exits.
144    pub fn surrender_gc_worker(&self, worker: Box<GCWorker<VM>>) {
145        let all_surrendered = self.worker_group.surrender_gc_worker(worker);
146
147        if all_surrendered {
148            debug!(
149                "All {} workers surrendered.",
150                self.worker_group.worker_count()
151            );
152            self.worker_monitor.on_all_workers_exited();
153        }
154    }
155
156    /// Respawn GC threads after forking.  This will reuse the `GCWorker` instances of stopped
157    /// workers.  `tls` is the VM thread that requests GC threads to be re-spawn, and will be
158    /// passed down to [`crate::vm::Collection::spawn_gc_thread`].
159    pub fn respawn_gc_threads_after_forking(self: &Arc<Self>, tls: VMThread) {
160        self.worker_group.respawn(tls)
161    }
162
163    /// Resolve the affinity of a thread.
164    pub fn resolve_affinity(&self, thread: ThreadId) {
165        self.affinity.resolve_affinity(thread);
166    }
167
168    /// Request a GC to be scheduled.  Called by mutator via `GCTrigger`.
169    pub(crate) fn request_schedule_collection(&self) {
170        debug!("A mutator is sending GC-scheduling request to workers...");
171        self.worker_monitor.make_request(WorkerGoal::Gc);
172    }
173
174    /// Add the `ScheduleCollection` packet.  Called by the last parked worker.
175    fn add_schedule_collection_packet(&self) {
176        // We are still holding the mutex `WorkerMonitor::sync`.  Do not notify now.
177        probe!(mmtk, add_schedule_collection_packet);
178        self.work_buckets[WorkBucketStage::Unconstrained].add_no_notify(ScheduleCollection);
179    }
180
181    /// Schedule all the common work packets
182    pub fn schedule_common_work<C: GCWorkContext<VM = VM>>(&self, plan: &'static C::PlanType) {
183        use crate::scheduler::gc_work::*;
184        // Stop & scan mutators (mutator scanning can happen before STW)
185        self.work_buckets[WorkBucketStage::Unconstrained].add(StopMutators::<C>::new());
186
187        // Prepare global/collectors/mutators
188        self.work_buckets[WorkBucketStage::Prepare].add(Prepare::<C>::new(plan));
189
190        // Release global/collectors/mutators
191        self.work_buckets[WorkBucketStage::Release].add(Release::<C>::new(plan));
192
193        // Analysis GC work
194        #[cfg(feature = "analysis")]
195        {
196            use crate::util::analysis::GcHookWork;
197            self.work_buckets[WorkBucketStage::Unconstrained].add(GcHookWork);
198        }
199
200        // Sanity
201        #[cfg(feature = "sanity")]
202        {
203            use crate::util::sanity::sanity_checker::ScheduleSanityGC;
204            self.work_buckets[WorkBucketStage::Final]
205                .add(ScheduleSanityGC::<C::PlanType>::new(plan));
206        }
207
208        // Reference processing
209        if !*plan.base().options.no_reference_types {
210            use crate::util::reference_processor::{
211                PhantomRefProcessing, SoftRefProcessing, WeakRefProcessing,
212            };
213            self.work_buckets[WorkBucketStage::SoftRefClosure]
214                .add(SoftRefProcessing::<C::DefaultTrace>::new());
215            self.work_buckets[WorkBucketStage::WeakRefClosure].add(WeakRefProcessing::<VM>::new());
216            self.work_buckets[WorkBucketStage::PhantomRefClosure]
217                .add(PhantomRefProcessing::<VM>::new());
218
219            use crate::util::reference_processor::RefForwarding;
220            if plan.constraints().needs_forward_after_liveness {
221                self.work_buckets[WorkBucketStage::RefForwarding]
222                    .add(RefForwarding::<C::DefaultTrace>::new());
223            }
224
225            use crate::util::reference_processor::RefEnqueue;
226            self.work_buckets[WorkBucketStage::Release].add(RefEnqueue::<VM>::new());
227        }
228
229        // Finalization
230        if !*plan.base().options.no_finalizer {
231            use crate::util::finalizable_processor::{Finalization, ForwardFinalization};
232            // finalization
233            self.work_buckets[WorkBucketStage::FinalRefClosure]
234                .add(Finalization::<C::DefaultTrace>::new());
235            // forward refs
236            if plan.constraints().needs_forward_after_liveness {
237                self.work_buckets[WorkBucketStage::FinalizableForwarding]
238                    .add(ForwardFinalization::<C::DefaultTrace>::new());
239            }
240        }
241
242        // We add the VM-specific weak ref processing work regardless of MMTK-side options,
243        // including Options::no_finalizer and Options::no_reference_types.
244        //
245        // VMs need weak reference handling to function properly.  The VM may treat weak references
246        // as strong references, but it is not appropriate to simply disable weak reference
247        // handling from MMTk's side.  The VM, however, may choose to do nothing in
248        // `Collection::process_weak_refs` if appropriate.
249        //
250        // It is also not sound for MMTk core to turn off weak
251        // reference processing or finalization alone, because (1) not all VMs have the notion of
252        // weak references or finalizers, so it may not make sence, and (2) the VM may
253        // processing them together.
254
255        // VM-specific weak ref processing
256        // The `VMProcessWeakRefs` work packet is set as the sentinel so that it is executed when
257        // the `VMRefClosure` bucket is drained.  The VM binding may spawn new work packets into
258        // the `VMRefClosure` bucket, and request another `VMProcessWeakRefs` work packet to be
259        // executed again after this bucket is drained again.  Strictly speaking, the first
260        // `VMProcessWeakRefs` packet can be an ordinary packet (doesn't have to be a sentinel)
261        // because there are no other packets in the bucket.  We set it as sentinel for
262        // consistency.
263        self.work_buckets[WorkBucketStage::VMRefClosure]
264            .set_sentinel(Box::new(VMProcessWeakRefs::<C::DefaultTrace>::new()));
265
266        if plan.constraints().needs_forward_after_liveness {
267            // VM-specific weak ref forwarding
268            self.work_buckets[WorkBucketStage::VMRefForwarding]
269                .add(VMForwardWeakRefs::<C::DefaultTrace>::new());
270        }
271
272        self.work_buckets[WorkBucketStage::Release].add(VMPostForwarding::<VM>::default());
273    }
274
275    fn are_buckets_drained(&self, buckets: &[WorkBucketStage]) -> bool {
276        buckets
277            .iter()
278            .all(|&b| !self.work_buckets[b].is_enabled() || self.work_buckets[b].is_drained())
279    }
280
281    pub fn debug_assert_all_stw_buckets_empty(&self) {
282        debug_assert!(self
283            .work_buckets
284            .values()
285            .filter(|bucket| bucket.get_stage().is_stw())
286            .all(|bucket| {
287                if !bucket.is_empty() {
288                    warn!(
289                        "Work bucket {:?} is not empty but it is expected to be empty!",
290                        bucket.get_stage()
291                    );
292                    warn!("Queue: {:?}", bucket.get_queue().debug_dump_packets());
293                    false
294                } else {
295                    true
296                }
297            }))
298    }
299
300    /// Schedule "sentinel" work packets for all open buckets.
301    ///
302    /// Returns the number of sentinel packets scheduled, so the caller can wake just that many
303    /// workers.
304    pub(crate) fn schedule_sentinels(&self) -> usize {
305        let mut new_packets = 0;
306        for (id, work_bucket) in self.work_buckets.iter() {
307            if work_bucket.is_open() && work_bucket.maybe_schedule_sentinel() {
308                trace!("Scheduled sentinel packet into {:?}", id);
309                new_packets += 1;
310            }
311        }
312        new_packets
313    }
314
315    /// Open buckets if their conditions are met.
316    ///
317    /// This function should only be called after all the workers are parked.
318    /// No workers will be waked up by this function. The caller is responsible for that.
319    ///
320    /// Returns the number of packets made available by the buckets that were opened, so the
321    /// caller can wake just that many workers.  Returns 0 if no bucket was opened, or if the
322    /// opened buckets were all empty.
323    pub(crate) fn update_buckets(&self) -> usize {
324        debug!("update_buckets");
325        let mut buckets_updated = false;
326        let mut new_packets = 0;
327        for i in 0..WorkBucketStage::LENGTH {
328            let id = WorkBucketStage::from_usize(i);
329            if id.is_always_open() {
330                continue;
331            }
332            let bucket = &self.work_buckets[id];
333            if !bucket.is_enabled() {
334                debug!("Work bucket {:?} is disabled. Skip.", id);
335                continue;
336            }
337            debug!("Checking if {:?} can be opened...", id);
338            let bucket_opened = bucket.update(self);
339            buckets_updated = buckets_updated || bucket_opened;
340            if bucket_opened {
341                probe!(mmtk, bucket_opened, id);
342                if !bucket.is_drained() {
343                    // Quit the loop. There are already new packets in the newly opened buckets.
344                    new_packets = bucket.len();
345                    trace!(
346                        "Found {} new packets at stage {:?}.  Break.",
347                        new_packets,
348                        id
349                    );
350                    break;
351                }
352                if bucket.maybe_schedule_sentinel() {
353                    // Quit the loop. A sentinel packet is added to the newly opened buckets.
354                    new_packets = 1;
355                    trace!("Sentinel is scheduled at stage {:?}.  Break.", id);
356                    break;
357                }
358            }
359        }
360        if buckets_updated {
361            new_packets
362        } else {
363            0
364        }
365    }
366
367    pub fn close_all_stw_buckets(&self) {
368        self.work_buckets.iter().for_each(|(id, bkt)| {
369            if id.is_stw() {
370                bkt.close();
371            }
372        });
373    }
374
375    pub fn reset_state(&self) {
376        self.work_buckets.iter().for_each(|(id, bkt)| {
377            if id.is_stw() && !id.is_first_stw_stage() {
378                bkt.close();
379            }
380        });
381    }
382
383    pub fn debug_assert_all_stw_buckets_closed(&self) {
384        if cfg!(debug_assertions) {
385            self.work_buckets.iter().for_each(|(id, bkt)| {
386                if id.is_stw() {
387                    assert!(!bkt.is_open());
388                }
389            });
390        }
391    }
392
393    /// Check if all the work buckets are empty
394    pub(crate) fn assert_all_open_buckets_are_empty(&self) {
395        let mut error_example = None;
396        for (id, bucket) in self.work_buckets.iter() {
397            if id == WorkBucketStage::ConcurrentResumable {
398                // Concurrent resumable bucket is a special case. It can be non-empty.
399                continue;
400            }
401            if bucket.is_enabled() && bucket.is_open() && !bucket.is_empty() {
402                error!("Work bucket {:?} is not drained!", id);
403                error!("Queue: {:?}", bucket.get_queue().debug_dump_packets());
404                // This error can be hard to reproduce.
405                // If an error happens in the release build where logs are turned off,
406                // we should show at least one abnormal bucket in the panic message
407                // so that we still have some information for debugging.
408                error_example = Some(id);
409            }
410        }
411        if let Some(id) = error_example {
412            panic!("Some open buckets (such as {:?}) are not empty.", id);
413        }
414    }
415
416    /// Get a schedulable work packet without retry.
417    fn poll_schedulable_work_once(&self, worker: &GCWorker<VM>) -> Steal<Box<dyn GCWork<VM>>> {
418        let mut should_retry = false;
419        // Try find a packet that can be processed only by this worker.
420        if let Some(w) = worker.shared.designated_work.pop() {
421            return Steal::Success(w);
422        }
423        // Try get a packet from a work bucket.
424        let plan = worker.mmtk.get_plan();
425        let in_concurrent_or_final_mark = plan
426            .concurrent()
427            .map(|c| c.current_pause().is_none() || c.current_pause() == Some(Pause::FinalMark))
428            .unwrap_or(false);
429        for (stage, work_bucket) in self.work_buckets.iter() {
430            if !in_concurrent_or_final_mark && stage == WorkBucketStage::ConcurrentResumable {
431                continue;
432            }
433            match work_bucket.poll(&worker.local_work_buffer) {
434                Steal::Success(w) => return Steal::Success(w),
435                Steal::Retry => should_retry = true,
436                _ => {}
437            }
438        }
439        // Try steal some packets from any worker
440        for (id, worker_shared) in self.worker_group.workers_shared.iter().enumerate() {
441            if id == worker.ordinal {
442                continue;
443            }
444            match worker_shared.stealer.as_ref().unwrap().steal() {
445                Steal::Success(w) => return Steal::Success(w),
446                Steal::Retry => should_retry = true,
447                _ => {}
448            }
449        }
450        if should_retry {
451            Steal::Retry
452        } else {
453            Steal::Empty
454        }
455    }
456
457    /// Get a schedulable work packet.
458    fn poll_schedulable_work(&self, worker: &GCWorker<VM>) -> Option<Box<dyn GCWork<VM>>> {
459        // Loop until we successfully get a packet.
460        loop {
461            match self.poll_schedulable_work_once(worker) {
462                Steal::Success(w) => {
463                    return Some(w);
464                }
465                Steal::Retry => {
466                    std::thread::yield_now();
467                    continue;
468                }
469                Steal::Empty => {
470                    return None;
471                }
472            }
473        }
474    }
475
476    /// Called by workers to get a schedulable work packet.
477    /// Park the worker if there're no available packets.
478    pub(crate) fn poll(&self, worker: &GCWorker<VM>) -> PollResult<VM> {
479        if let Some(work) = self.poll_schedulable_work(worker) {
480            return Ok(work);
481        }
482        self.poll_slow(worker)
483    }
484
485    fn poll_slow(&self, worker: &GCWorker<VM>) -> PollResult<VM> {
486        loop {
487            // Retry polling
488            if let Some(work) = self.poll_schedulable_work(worker) {
489                return Ok(work);
490            }
491
492            let ordinal = worker.ordinal;
493            self.worker_monitor
494                .park_and_wait(ordinal, |goals| self.on_last_parked(worker, goals))?;
495        }
496    }
497
498    /// Called when the last worker parked.  `goal` allows this function to inspect and change the
499    /// current goal.
500    fn on_last_parked(&self, worker: &GCWorker<VM>, goals: &mut WorkerGoals) -> LastParkedResult {
501        let Some(ref current_goal) = goals.current() else {
502            // There is no goal.  Find a request to respond to.
503            return self.respond_to_requests(worker, goals);
504        };
505
506        match current_goal {
507            WorkerGoal::Gc => {
508                // We are in the progress of GC.
509
510                // In stop-the-world GC, mutators cannot request for GC while GC is in progress.
511                // When we support concurrent GC, we should remove this assertion.
512                assert!(
513                    !goals.debug_is_requested(WorkerGoal::Gc),
514                    "GC request sent to WorkerMonitor while GC is still in progress."
515                );
516
517                // We are in the middle of GC, and the last GC worker parked.
518                trace!("The last worker parked during GC.  Try to find more work to do...");
519
520                // During GC, if all workers parked, all open buckets must have been drained.
521                self.assert_all_open_buckets_are_empty();
522
523                // Find more work for workers to do.
524                let found_more_work = self.find_more_work_for_workers();
525
526                if found_more_work != 0 {
527                    if found_more_work == usize::MAX {
528                        LastParkedResult::WakeAll
529                    } else {
530                        LastParkedResult::Wake(found_more_work)
531                    }
532                } else {
533                    // GC finished.
534                    let concurrent_work_scheduled = self.on_gc_finished(worker);
535
536                    // Clear the current goal
537                    goals.on_current_goal_completed();
538
539                    if concurrent_work_scheduled {
540                        // We just scheduled concurrent work. Wake up all GC workers to do concurrent work.
541                        LastParkedResult::WakeAll
542                    } else {
543                        // No scheduled concurrent work. Respond to another goal.
544                        self.respond_to_requests(worker, goals)
545                    }
546                }
547            }
548            WorkerGoal::StopForFork | WorkerGoal::Shutdown => {
549                panic!(
550                    "Worker {} parked again when it is asked to exit.",
551                    worker.ordinal
552                )
553            }
554        }
555    }
556
557    /// Respond to a worker reqeust.
558    fn respond_to_requests(
559        &self,
560        worker: &GCWorker<VM>,
561        goals: &mut WorkerGoals,
562    ) -> LastParkedResult {
563        assert!(goals.current().is_none());
564
565        let mut next_goal = goals.poll_next_goal();
566        if next_goal.is_none() {
567            // No work now. Check if we would like to do a GC poll from GC workers.
568            if worker.mmtk.gc_trigger.poll_from_last_parked_worker() {
569                goals.set_request(WorkerGoal::Gc);
570                next_goal = goals.poll_next_goal();
571            }
572        }
573
574        let Some(goal) = next_goal else {
575            // No requests, and the poll above did not ask for one either. If a concurrent phase
576            // was running, its work packets have now drained, tell the plan.
577            if worker.mmtk.state.gc_status.load() == crate::global_state::GcStatus::InConcurrentGC {
578                let plan = worker.mmtk.get_plan().concurrent().unwrap();
579                plan.on_concurrent_work_drained();
580            }
581            // Park this worker, too.
582            return LastParkedResult::ParkSelf;
583        };
584
585        match goal {
586            WorkerGoal::Gc => {
587                trace!("A mutator requested a GC to be scheduled.");
588
589                // We set the eBPF trace point here so that bpftrace scripts can start recording
590                // work packet events before the `ScheduleCollection` work packet starts.
591                probe!(mmtk, gc_start);
592
593                self.add_schedule_collection_packet();
594                LastParkedResult::WakeSelf
595            }
596            WorkerGoal::StopForFork | WorkerGoal::Shutdown => {
597                trace!("A mutator requested {:?}", goal);
598                LastParkedResult::WakeAll
599            }
600        }
601    }
602
603    /// Find more work for workers to do.
604    ///
605    /// Returns the number of workers worth waking: `0` if there is no more work (the GC is done),
606    /// or `usize::MAX` to mean "wake everyone".
607    fn find_more_work_for_workers(&self) -> usize {
608        if self.worker_group.has_designated_work() {
609            trace!("Some workers have designated work.");
610            // Designated work belongs to specific workers, and `notify_one` cannot choose which
611            // waiter it wakes, so everyone has to be given the chance to check.
612            return usize::MAX;
613        }
614
615        // See if any bucket has a sentinel.
616        let sentinels = self.schedule_sentinels();
617        if sentinels != 0 {
618            trace!("Some sentinels are scheduled.");
619            return sentinels;
620        }
621
622        // Try to open new buckets.
623        let opened = self.update_buckets();
624        if opened != 0 {
625            trace!("Some buckets are opened.");
626            return opened;
627        }
628
629        // If all of the above failed, it means GC has finished.
630        0
631    }
632
633    fn do_vm_release(&self, mmtk: &MMTK<VM>) {
634        if *mmtk.get_options().plan != PlanSelector::LXR {
635            <VM as VMBinding>::VMCollection::vm_release();
636        }
637    }
638
639    /// Called when GC has finished, i.e. when all work packets have been executed.
640    ///
641    /// Return `true` if any concurrent work packets have been scheduled.
642    fn on_gc_finished(&self, worker: &GCWorker<VM>) -> bool {
643        // All GC workers must have parked by now.
644        debug_assert!(!self.worker_group.has_designated_work());
645        self.debug_assert_all_stw_buckets_empty();
646
647        // Close all work buckets to prepare for the next GC.
648        self.close_all_stw_buckets();
649        self.debug_assert_all_stw_buckets_closed();
650
651        self.do_vm_release(worker.mmtk);
652
653        let mmtk = worker.mmtk;
654
655        // Tell GC trigger that GC ended - this happens before we resume mutators.
656        mmtk.gc_trigger.policy.on_pause_end(mmtk);
657
658        // All other workers are parked, so it is safe to access the Plan instance mutably.
659        probe!(mmtk, plan_end_of_gc_begin);
660        let plan_mut: &mut dyn Plan<VM = VM> = unsafe { mmtk.get_plan_mut() };
661        // This also tells the GC trigger whether the GC cycle has ended (see `Plan::on_pause_end`).
662        plan_mut.on_pause_end(mmtk, worker.tls);
663        probe!(mmtk, plan_end_of_gc_end);
664
665        // Compute the elapsed time of the pause so far. `pause_start_time` is taken (and the
666        // "pause-time" stat recorded) further down, once the pause is truly about to end.
667        let elapsed = mmtk
668            .state
669            .pause_start_time
670            .borrow()
671            .as_ref()
672            .expect("Pause start time was not recorded")
673            .elapsed();
674
675        let reserved_pages = mmtk.get_plan().get_reserved_pages();
676        let total_pages = mmtk.get_plan().get_total_pages();
677
678        info!(
679            "End of Pause ({}/{} pages, took {:.2} ms)",
680            reserved_pages,
681            total_pages,
682            elapsed.as_secs_f64() * 1000.0
683        );
684
685        probe!(mmtk, heap_stats, reserved_pages, total_pages);
686
687        // USDT tracepoint for the end of GC.
688        probe!(mmtk, gc_end);
689
690        if *mmtk.get_options().count_live_bytes_in_gc {
691            // Aggregate the live bytes
692            let live_bytes = mmtk
693                .scheduler
694                .worker_group
695                .get_and_clear_worker_live_bytes();
696            let mut live_bytes_in_last_gc = mmtk.state.live_bytes_in_last_gc.borrow_mut();
697            *live_bytes_in_last_gc = mmtk.aggregate_live_bytes_in_last_gc(live_bytes);
698            // Logging
699            for (space_name, &stats) in live_bytes_in_last_gc.iter() {
700                info!(
701                    "{} = {} pages ({:.1}% live)",
702                    space_name,
703                    stats.used_pages,
704                    stats.live_bytes as f64 * 100.0 / stats.used_bytes as f64,
705                );
706            }
707        }
708
709        mmtk.state
710            .set_used_pages_after_last_gc(mmtk.get_plan().get_used_pages());
711
712        #[cfg(feature = "extreme_assertions")]
713        if crate::util::slot_logger::should_check_duplicate_slots(mmtk.get_plan()) {
714            // reset the logging info at the end of each GC
715            mmtk.slot_logger.reset();
716        }
717
718        // Reset the triggering information.
719        mmtk.state.reset_collection_trigger();
720
721        let concurrent_work_scheduled = self.schedule_concurrent_packets(mmtk);
722        self.debug_assert_all_stw_buckets_closed();
723
724        // Set to NotInGC after everything, and right before resuming mutators.
725        if concurrent_work_scheduled {
726            mmtk.state.gc_status.set_in_concurrent_gc();
727            // Going to start concurrent GC. Set the number of active workers to the configured number of concurrent threads.
728            self.set_active_workers(*mmtk.options.concurrent_threads);
729            debug!(
730                "Concurrent work started. Active worker count set from concurrent_threads={}.",
731                *mmtk.options.concurrent_threads
732            );
733        } else {
734            mmtk.state.gc_status.set_not_in_gc();
735        }
736        // The pause is about to end (mutators are about to resume)
737        mmtk.stats.record_pause_time(mmtk.state.take_pause_time());
738        if mmtk.stats.get_gathering_stats() {
739            mmtk.stats.end_gc();
740        }
741        <VM as VMBinding>::VMCollection::resume_mutators(worker.tls);
742
743        concurrent_work_scheduled
744    }
745
746    pub fn enable_stat(&self) {
747        for worker in &self.worker_group.workers_shared {
748            let worker_stat = worker.borrow_stat();
749            worker_stat.enable();
750        }
751    }
752
753    pub fn statistics(&self) -> HashMap<String, String> {
754        let mut summary = SchedulerStat::default();
755        for worker in &self.worker_group.workers_shared {
756            let worker_stat = worker.borrow_stat();
757            summary.merge(&worker_stat);
758        }
759        summary.harness_stat()
760    }
761
762    pub fn notify_mutators_paused(&self, mmtk: &'static MMTK<VM>) {
763        mmtk.state.gc_status.set_in_pause();
764        // The number of active workers should be either the configured number of threads or the configured number of concurrent threads.
765        assert!(
766            mmtk.scheduler.num_active_workers() == *mmtk.options.threads
767                || mmtk.scheduler.num_active_workers() == *mmtk.options.concurrent_threads
768        );
769        // Pause started, use all GC threads.
770        mmtk.scheduler.set_active_workers(*mmtk.options.threads);
771
772        let first_stw_bucket = &self.work_buckets[WorkBucketStage::FIRST_STW_STAGE];
773        debug_assert!(!first_stw_bucket.is_open());
774        // Note: This is the only place where a bucket is opened without having all workers parked.
775        // We usually require all workers to park before opening new buckets because otherwise
776        // packets will be executed out of order.  However, since `Prepare` is the first STW
777        // bucket, and all subsequent buckets require all workers to park before opening, workers
778        // cannot execute work packets out of order.  This is not generally true if we are not
779        // opening the first STW bucket.  In the future, we should redesign the opening condition
780        // of work buckets to make the synchronization more robust,
781        first_stw_bucket.open();
782        self.worker_monitor.notify_work_available(true);
783    }
784
785    pub(super) fn schedule_concurrent_packets(&self, mmtk: &MMTK<VM>) -> bool {
786        // Only LXR defers work into the inactive queue (via `add_deferred`/`bulk_add_deferred`),
787        // so only LXR needs the `Concurrent` bucket's queue flipped here. For every other plan
788        // (e.g. the generic `ConcurrentImmix`), flipping would silently orphan any packets left
789        // in the currently-active queue when a STW pause interrupts an in-progress concurrent
790        // phase: `is_empty()` would check the other (empty) queue and the bucket would be closed
791        // as if drained, even though unprocessed concurrent-marking work is still sitting in the
792        // now-inactive queue. Keep this the same enable/disable-only mechanism as master unless
793        // the plan is LXR.
794        let is_lxr = *mmtk.get_options().plan == PlanSelector::LXR;
795        let enable_bucket = |stage: WorkBucketStage, flip: bool| {
796            let bucket = &self.work_buckets[stage];
797            if flip && is_lxr {
798                bucket.flip();
799            }
800            if !bucket.is_empty() {
801                bucket.set_enabled(true);
802                bucket.open();
803                true
804            } else {
805                bucket.set_enabled(false);
806                bucket.close();
807                false
808            }
809        };
810        let a = enable_bucket(WorkBucketStage::Concurrent, true);
811        let b = enable_bucket(WorkBucketStage::ConcurrentResumable, false);
812        a || b
813    }
814}