1 /*
  2  * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "cds/archiveBuilder.hpp"
 26 #include "cds/archiveHeapLoader.inline.hpp"
 27 #include "cds/archiveUtils.hpp"
 28 #include "cds/cdsConfig.hpp"
 29 #include "cds/classListParser.hpp"
 30 #include "cds/classListWriter.hpp"
 31 #include "cds/dynamicArchive.hpp"
 32 #include "cds/filemap.hpp"
 33 #include "cds/heapShared.hpp"
 34 #include "cds/lambdaProxyClassDictionary.hpp"
 35 #include "cds/metaspaceShared.hpp"
 36 #include "classfile/classLoader.hpp"
 37 #include "classfile/systemDictionaryShared.hpp"
 38 #include "classfile/vmClasses.hpp"
 39 #include "interpreter/bootstrapInfo.hpp"
 40 #include "memory/metaspaceUtils.hpp"
 41 #include "memory/resourceArea.hpp"
 42 #include "oops/compressedOops.inline.hpp"
 43 #include "oops/klass.inline.hpp"
 44 #include "runtime/arguments.hpp"
 45 #include "utilities/bitMap.inline.hpp"
 46 #include "utilities/debug.hpp"
 47 #include "utilities/formatBuffer.hpp"
 48 #include "utilities/globalDefinitions.hpp"
 49 #include "utilities/spinYield.hpp"
 50 
 51 CHeapBitMap* ArchivePtrMarker::_ptrmap = nullptr;
 52 CHeapBitMap* ArchivePtrMarker::_rw_ptrmap = nullptr;
 53 CHeapBitMap* ArchivePtrMarker::_ro_ptrmap = nullptr;
 54 CHeapBitMap* ArchivePtrMarker::_cc_ptrmap = nullptr;
 55 VirtualSpace* ArchivePtrMarker::_vs;
 56 
 57 bool ArchivePtrMarker::_compacted;
 58 
 59 void ArchivePtrMarker::initialize(CHeapBitMap* ptrmap, VirtualSpace* vs) {
 60   assert(_ptrmap == nullptr, "initialize only once");
 61   assert(_rw_ptrmap == nullptr, "initialize only once");
 62   assert(_ro_ptrmap == nullptr, "initialize only once");
 63   assert(_cc_ptrmap == nullptr, "initialize only once");
 64   _vs = vs;
 65   _compacted = false;
 66   _ptrmap = ptrmap;
 67 
 68   // Use this as initial guesstimate. We should need less space in the
 69   // archive, but if we're wrong the bitmap will be expanded automatically.
 70   size_t estimated_archive_size = MetaspaceGC::capacity_until_GC();
 71   // But set it smaller in debug builds so we always test the expansion code.
 72   // (Default archive is about 12MB).
 73   DEBUG_ONLY(estimated_archive_size = 6 * M);
 74 
 75   // We need one bit per pointer in the archive.
 76   _ptrmap->initialize(estimated_archive_size / sizeof(intptr_t));
 77 }
 78 
 79 void ArchivePtrMarker::initialize_rw_ro_cc_maps(CHeapBitMap* rw_ptrmap, CHeapBitMap* ro_ptrmap, CHeapBitMap* cc_ptrmap) {
 80   address* buff_bottom = (address*)ArchiveBuilder::current()->buffer_bottom();
 81   address* rw_bottom   = (address*)ArchiveBuilder::current()->rw_region()->base();
 82   address* ro_bottom   = (address*)ArchiveBuilder::current()->ro_region()->base();
 83   address* cc_bottom   = (address*)ArchiveBuilder::current()->cc_region()->base();
 84 
 85   // The bit in _ptrmap that cover the very first word in the rw/ro/cc regions.
 86   size_t rw_start = rw_bottom - buff_bottom;
 87   size_t ro_start = ro_bottom - buff_bottom;
 88   size_t cc_start = cc_bottom - buff_bottom;
 89 
 90   // The number of bits used by the rw/ro ptrmaps. We might have lots of zero
 91   // bits at the bottom and top of rw/ro ptrmaps, but these zeros will be
 92   // removed by FileMapInfo::write_bitmap_region().
 93   size_t rw_size = ArchiveBuilder::current()->rw_region()->used() / sizeof(address);
 94   size_t ro_size = ArchiveBuilder::current()->ro_region()->used() / sizeof(address);
 95   size_t cc_size = ArchiveBuilder::current()->cc_region()->used() / sizeof(address);
 96 
 97   // The last (exclusive) bit in _ptrmap that covers the rw/ro regions.
 98   // Note: _ptrmap is dynamically expanded only when an actual pointer is written, so
 99   // it may not be as large as we want.
100   size_t rw_end = MIN2<size_t>(rw_start + rw_size, _ptrmap->size());
101   size_t ro_end = MIN2<size_t>(ro_start + ro_size, _ptrmap->size());
102   size_t cc_end = MIN2<size_t>(cc_start + cc_size, _ptrmap->size());
103 
104   rw_ptrmap->initialize(rw_size);
105   ro_ptrmap->initialize(ro_size);
106   cc_ptrmap->initialize(cc_size);
107 
108   for (size_t rw_bit = rw_start; rw_bit < rw_end; rw_bit++) {
109     rw_ptrmap->at_put(rw_bit - rw_start, _ptrmap->at(rw_bit));
110   }
111 
112   for(size_t ro_bit = ro_start; ro_bit < ro_end; ro_bit++) {
113     ro_ptrmap->at_put(ro_bit - ro_start, _ptrmap->at(ro_bit));
114   }
115 
116   for (size_t cc_bit = cc_start; cc_bit < cc_end; cc_bit++) {
117     cc_ptrmap->at_put(cc_bit - cc_start, _ptrmap->at(cc_bit));
118   }
119 
120   _rw_ptrmap = rw_ptrmap;
121   _ro_ptrmap = ro_ptrmap;
122   _cc_ptrmap = cc_ptrmap;
123 }
124 
125 void ArchivePtrMarker::mark_pointer(address* ptr_loc) {
126   assert(_ptrmap != nullptr, "not initialized");
127   assert(!_compacted, "cannot mark anymore");
128 
129   if (ptr_base() <= ptr_loc && ptr_loc < ptr_end()) {
130     address value = *ptr_loc;
131     // We don't want any pointer that points to very bottom of the archive, otherwise when
132     // MetaspaceShared::default_base_address()==0, we can't distinguish between a pointer
133     // to nothing (null) vs a pointer to an objects that happens to be at the very bottom
134     // of the archive.
135     assert(value != (address)ptr_base(), "don't point to the bottom of the archive");
136 
137     if (value != nullptr) {
138       assert(uintx(ptr_loc) % sizeof(intptr_t) == 0, "pointers must be stored in aligned addresses");
139       size_t idx = ptr_loc - ptr_base();
140       if (_ptrmap->size() <= idx) {
141         _ptrmap->resize((idx + 1) * 2);
142       }
143       assert(idx < _ptrmap->size(), "must be");
144       _ptrmap->set_bit(idx);
145       //tty->print_cr("Marking pointer [" PTR_FORMAT "] -> " PTR_FORMAT " @ %5zu", p2i(ptr_loc), p2i(*ptr_loc), idx);
146     }
147   }
148 }
149 
150 void ArchivePtrMarker::clear_pointer(address* ptr_loc) {
151   assert(_ptrmap != nullptr, "not initialized");
152   assert(!_compacted, "cannot clear anymore");
153 
154   assert(ptr_base() <= ptr_loc && ptr_loc < ptr_end(), "must be");
155   assert(uintx(ptr_loc) % sizeof(intptr_t) == 0, "pointers must be stored in aligned addresses");
156   size_t idx = ptr_loc - ptr_base();
157   assert(idx < _ptrmap->size(), "cannot clear pointers that have not been marked");
158   _ptrmap->clear_bit(idx);
159   //tty->print_cr("Clearing pointer [" PTR_FORMAT "] -> " PTR_FORMAT " @ %5zu", p2i(ptr_loc), p2i(*ptr_loc), idx);
160 }
161 
162 class ArchivePtrBitmapCleaner: public BitMapClosure {
163   CHeapBitMap* _ptrmap;
164   address* _ptr_base;
165   address  _relocatable_base;
166   address  _relocatable_end;
167   size_t   _max_non_null_offset;
168 
169 public:
170   ArchivePtrBitmapCleaner(CHeapBitMap* ptrmap, address* ptr_base, address relocatable_base, address relocatable_end) :
171     _ptrmap(ptrmap), _ptr_base(ptr_base),
172     _relocatable_base(relocatable_base), _relocatable_end(relocatable_end), _max_non_null_offset(0) {}
173 
174   bool do_bit(size_t offset) {
175     address* ptr_loc = _ptr_base + offset;
176     address  ptr_value = *ptr_loc;
177     if (ptr_value != nullptr) {
178       assert(_relocatable_base <= ptr_value && ptr_value < _relocatable_end, "do not point to arbitrary locations!");
179       if (_max_non_null_offset < offset) {
180         _max_non_null_offset = offset;
181       }
182     } else {
183       _ptrmap->clear_bit(offset);
184       DEBUG_ONLY(log_trace(cds, reloc)("Clearing pointer [" PTR_FORMAT  "] -> null @ %9zu", p2i(ptr_loc), offset));
185     }
186 
187     return true;
188   }
189 
190   size_t max_non_null_offset() const { return _max_non_null_offset; }
191 };
192 
193 void ArchivePtrMarker::compact(address relocatable_base, address relocatable_end) {
194   assert(!_compacted, "cannot compact again");
195   ArchivePtrBitmapCleaner cleaner(_ptrmap, ptr_base(), relocatable_base, relocatable_end);
196   _ptrmap->iterate(&cleaner);
197   compact(cleaner.max_non_null_offset());
198 }
199 
200 void ArchivePtrMarker::compact(size_t max_non_null_offset) {
201   assert(!_compacted, "cannot compact again");
202   _ptrmap->resize(max_non_null_offset + 1);
203   _compacted = true;
204 }
205 
206 char* DumpRegion::expand_top_to(char* newtop) {
207   assert(is_allocatable(), "must be initialized and not packed");
208   assert(newtop >= _top, "must not grow backwards");
209   if (newtop > _end) {
210     ArchiveBuilder::current()->report_out_of_space(_name, newtop - _top);
211     ShouldNotReachHere();
212   }
213 
214   commit_to(newtop);
215   _top = newtop;
216 
217   if (_max_delta > 0) {
218     uintx delta = ArchiveBuilder::current()->buffer_to_offset((address)(newtop-1));
219     if (delta > _max_delta) {
220       // This is just a sanity check and should not appear in any real world usage. This
221       // happens only if you allocate more than 2GB of shared objects and would require
222       // millions of shared classes.
223       log_error(cds)("Out of memory in the CDS archive: Please reduce the number of shared classes.");
224       MetaspaceShared::unrecoverable_writing_error();
225     }
226   }
227 
228   return _top;
229 }
230 
231 void DumpRegion::commit_to(char* newtop) {
232   assert(CDSConfig::is_dumping_archive(), "sanity");
233   char* base = _rs->base();
234   size_t need_committed_size = newtop - base;
235   size_t has_committed_size = _vs->committed_size();
236   if (need_committed_size < has_committed_size) {
237     return;
238   }
239 
240   size_t min_bytes = need_committed_size - has_committed_size;
241   size_t preferred_bytes = 1 * M;
242   size_t uncommitted = _vs->reserved_size() - has_committed_size;
243 
244   size_t commit = MAX2(min_bytes, preferred_bytes);
245   commit = MIN2(commit, uncommitted);
246   assert(commit <= uncommitted, "sanity");
247 
248   if (!_vs->expand_by(commit, false)) {
249     log_error(cds)("Failed to expand shared space to %zu bytes",
250                     need_committed_size);
251     MetaspaceShared::unrecoverable_writing_error();
252   }
253 
254   const char* which;
255   if (_rs->base() == (char*)MetaspaceShared::symbol_rs_base()) {
256     which = "symbol";
257   } else {
258     which = "shared";
259   }
260   log_debug(cds)("Expanding %s spaces by %7zu bytes [total %9zu bytes ending at %p]",
261                  which, commit, _vs->actual_committed_size(), _vs->high());
262 }
263 
264 char* DumpRegion::allocate(size_t num_bytes, size_t alignment) {
265   // Always align to at least minimum alignment
266   alignment = MAX2(SharedSpaceObjectAlignment, alignment);
267   char* p = (char*)align_up(_top, alignment);
268   char* newtop = p + align_up(num_bytes, (size_t)SharedSpaceObjectAlignment);
269   expand_top_to(newtop);
270   memset(p, 0, newtop - p);
271   return p;
272 }
273 
274 void DumpRegion::append_intptr_t(intptr_t n, bool need_to_mark) {
275   assert(is_aligned(_top, sizeof(intptr_t)), "bad alignment");
276   intptr_t *p = (intptr_t*)_top;
277   char* newtop = _top + sizeof(intptr_t);
278   expand_top_to(newtop);
279   *p = n;
280   if (need_to_mark) {
281     ArchivePtrMarker::mark_pointer(p);
282   }
283 }
284 
285 void DumpRegion::print(size_t total_bytes) const {
286   char* base = used() > 0 ? ArchiveBuilder::current()->to_requested(_base) : nullptr;
287   log_debug(cds)("%s space: %9zu [ %4.1f%% of total] out of %9zu bytes [%5.1f%% used] at " INTPTR_FORMAT,
288                  _name, used(), percent_of(used(), total_bytes), reserved(), percent_of(used(), reserved()),
289                  p2i(base));
290 }
291 
292 void DumpRegion::print_out_of_space_msg(const char* failing_region, size_t needed_bytes) {
293   log_error(cds)("[%-8s] " PTR_FORMAT " - " PTR_FORMAT " capacity =%9d, allocated =%9d",
294                  _name, p2i(_base), p2i(_top), int(_end - _base), int(_top - _base));
295   if (strcmp(_name, failing_region) == 0) {
296     log_error(cds)(" required = %d", int(needed_bytes));
297   }
298 }
299 
300 void DumpRegion::init(ReservedSpace* rs, VirtualSpace* vs) {
301   _rs = rs;
302   _vs = vs;
303   // Start with 0 committed bytes. The memory will be committed as needed.
304   if (!_vs->initialize(*_rs, 0)) {
305     fatal("Unable to allocate memory for shared space");
306   }
307   _base = _top = _rs->base();
308   _end = _rs->end();
309 }
310 
311 void DumpRegion::pack(DumpRegion* next) {
312   if (!is_packed()) {
313     _end = (char*)align_up(_top, MetaspaceShared::core_region_alignment());
314     _is_packed = true;
315   }
316   if (next != nullptr) {
317     next->_rs = _rs;
318     next->_vs = _vs;
319     next->_base = next->_top = this->_end;
320     next->_end = _rs->end();
321   }
322 }
323 
324 void WriteClosure::do_ptr(void** p) {
325   // Write ptr into the archive; ptr can be:
326   //   (a) null                 -> written as 0
327   //   (b) a "buffered" address -> written as is
328   //   (c) a "source"   address -> convert to "buffered" and write
329   // The common case is (c). E.g., when writing the vmClasses into the archive.
330   // We have (b) only when we don't have a corresponding source object. E.g.,
331   // the archived c++ vtable entries.
332   address ptr = *(address*)p;
333   if (ptr != nullptr && !ArchiveBuilder::current()->is_in_buffer_space(ptr)) {
334     ptr = ArchiveBuilder::current()->get_buffered_addr(ptr);
335   }
336   // null pointers do not need to be converted to offsets
337   if (ptr != nullptr) {
338     ptr = (address)ArchiveBuilder::current()->buffer_to_offset(ptr);
339   }
340   _dump_region->append_intptr_t((intptr_t)ptr, false);
341 }
342 
343 void ReadClosure::do_ptr(void** p) {
344   assert(*p == nullptr, "initializing previous initialized pointer.");
345   intptr_t obj = nextPtr();
346   assert(obj >= 0, "sanity.");
347   *p = (obj != 0) ? (void*)(_base_address + obj) : (void*)obj;
348 }
349 
350 void ReadClosure::do_u4(u4* p) {
351   intptr_t obj = nextPtr();
352   *p = (u4)(uintx(obj));
353 }
354 
355 void ReadClosure::do_int(int* p) {
356   intptr_t obj = nextPtr();
357   *p = (int)(intx(obj));
358 }
359 
360 void ReadClosure::do_bool(bool* p) {
361   intptr_t obj = nextPtr();
362   *p = (bool)(uintx(obj));
363 }
364 
365 void ReadClosure::do_tag(int tag) {
366   int old_tag;
367   old_tag = (int)(intptr_t)nextPtr();
368   // do_int(&old_tag);
369   assert(tag == old_tag, "tag doesn't match (%d, expected %d)", old_tag, tag);
370   FileMapInfo::assert_mark(tag == old_tag);
371 }
372 
373 void ArchiveUtils::log_to_classlist(BootstrapInfo* bootstrap_specifier, TRAPS) {
374   if (ClassListWriter::is_enabled()) {
375     if (LambdaProxyClassDictionary::is_supported_invokedynamic(bootstrap_specifier)) {
376       const constantPoolHandle& pool = bootstrap_specifier->pool();
377       if (SystemDictionaryShared::is_builtin_loader(pool->pool_holder()->class_loader_data())) {
378         // Currently lambda proxy classes are supported only for the built-in loaders.
379         ResourceMark rm(THREAD);
380         int pool_index = bootstrap_specifier->bss_index();
381         ClassListWriter w;
382         w.stream()->print("%s %s", ClassListParser::lambda_proxy_tag(), pool->pool_holder()->name()->as_C_string());
383         CDSIndyInfo cii;
384         ClassListParser::populate_cds_indy_info(pool, pool_index, &cii, CHECK);
385         GrowableArray<const char*>* indy_items = cii.items();
386         for (int i = 0; i < indy_items->length(); i++) {
387           w.stream()->print(" %s", indy_items->at(i));
388         }
389         w.stream()->cr();
390       }
391     }
392   }
393 }
394 
395 
396 // "boot", "platform", "app" or nullptr
397 const char* ArchiveUtils::builtin_loader_name_or_null(oop loader) {
398   if (loader == nullptr) {
399     return "boot";
400   } else if (loader == SystemDictionary::java_platform_loader()) {
401     return "platform";
402   } else if (loader == SystemDictionary::java_system_loader()) {
403     return "app";
404   } else {
405     return nullptr;
406   }
407 }
408 
409 // "boot", "platform", "app". Asserts if not a built-in-loader
410 const char* ArchiveUtils::builtin_loader_name(oop loader) {
411   const char* name = builtin_loader_name_or_null(loader);
412   assert(name != nullptr, "must be a built-in loader");
413   return name;
414 }
415 
416 bool ArchiveUtils::builtin_loader_from_type(const char* loader_type, oop* value_ret) {
417   if (strcmp(loader_type, "boot") == 0) {
418     *value_ret = nullptr;
419     return true;
420   } else if (strcmp(loader_type, "platform") == 0) {
421     *value_ret = SystemDictionary::java_platform_loader();
422     return true;
423   } else if (strcmp(loader_type, "app") == 0) {
424     *value_ret = SystemDictionary::java_system_loader();
425     return true;
426   } else {
427     DEBUG_ONLY(*value_ret = cast_to_oop((void*)badOopVal));
428     return false;
429   }
430 }
431 
432 oop ArchiveUtils::builtin_loader_from_type(int loader_type) {
433   if (loader_type == ClassLoader::BOOT_LOADER) {
434     return nullptr;
435   } else if (loader_type == ClassLoader::PLATFORM_LOADER)  {
436     return SystemDictionary::java_platform_loader();
437   } else if (loader_type == ClassLoader::APP_LOADER) {
438     return SystemDictionary::java_system_loader();
439   } else {
440     ShouldNotReachHere();
441     return nullptr;
442   }
443 }
444 
445 bool ArchiveUtils::has_aot_initialized_mirror(InstanceKlass* src_ik) {
446   if (SystemDictionaryShared::is_excluded_class(src_ik)) {
447     assert(!ArchiveBuilder::current()->has_been_buffered(src_ik), "sanity");
448     return false;
449   }
450   return ArchiveBuilder::current()->get_buffered_addr(src_ik)->has_aot_initialized_mirror();
451 }
452 
453 size_t HeapRootSegments::size_in_bytes(size_t seg_idx) {
454   assert(seg_idx < _count, "In range");
455   return objArrayOopDesc::object_size(size_in_elems(seg_idx)) * HeapWordSize;
456 }
457 
458 int HeapRootSegments::size_in_elems(size_t seg_idx) {
459   assert(seg_idx < _count, "In range");
460   if (seg_idx != _count - 1) {
461     return _max_size_in_elems;
462   } else {
463     // Last slice, leftover
464     return _roots_count % _max_size_in_elems;
465   }
466 }
467 
468 size_t HeapRootSegments::segment_offset(size_t seg_idx) {
469   assert(seg_idx < _count, "In range");
470   return _base_offset + seg_idx * _max_size_in_bytes;
471 }
472 
473 ArchiveWorkers::ArchiveWorkers() :
474         _end_semaphore(0),
475         _num_workers(max_workers()),
476         _started_workers(0),
477         _finish_tokens(0),
478         _state(UNUSED),
479         _task(nullptr) {}
480 
481 ArchiveWorkers::~ArchiveWorkers() {
482   assert(Atomic::load(&_state) != WORKING, "Should not be working");
483 }
484 
485 int ArchiveWorkers::max_workers() {
486   // The pool is used for short-lived bursty tasks. We do not want to spend
487   // too much time creating and waking up threads unnecessarily. Plus, we do
488   // not want to overwhelm large machines. This is why we want to be very
489   // conservative about the number of workers actually needed.
490   return MAX2(0, log2i_graceful(os::active_processor_count()));
491 }
492 
493 bool ArchiveWorkers::is_parallel() {
494   return _num_workers > 0;
495 }
496 
497 void ArchiveWorkers::start_worker_if_needed() {
498   while (true) {
499     int cur = Atomic::load(&_started_workers);
500     if (cur >= _num_workers) {
501       return;
502     }
503     if (Atomic::cmpxchg(&_started_workers, cur, cur + 1, memory_order_relaxed) == cur) {
504       new ArchiveWorkerThread(this);
505       return;
506     }
507   }
508 }
509 
510 void ArchiveWorkers::run_task(ArchiveWorkerTask* task) {
511   assert(Atomic::load(&_state) == UNUSED, "Should be unused yet");
512   assert(Atomic::load(&_task) == nullptr, "Should not have running tasks");
513   Atomic::store(&_state, WORKING);
514 
515   if (is_parallel()) {
516     run_task_multi(task);
517   } else {
518     run_task_single(task);
519   }
520 
521   assert(Atomic::load(&_state) == WORKING, "Should be working");
522   Atomic::store(&_state, SHUTDOWN);
523 }
524 
525 void ArchiveWorkers::run_task_single(ArchiveWorkerTask* task) {
526   // Single thread needs no chunking.
527   task->configure_max_chunks(1);
528 
529   // Execute the task ourselves, as there are no workers.
530   task->work(0, 1);
531 }
532 
533 void ArchiveWorkers::run_task_multi(ArchiveWorkerTask* task) {
534   // Multiple threads can work with multiple chunks.
535   task->configure_max_chunks(_num_workers * CHUNKS_PER_WORKER);
536 
537   // Set up the run and publish the task. Issue one additional finish token
538   // to cover the semaphore shutdown path, see below.
539   Atomic::store(&_finish_tokens, _num_workers + 1);
540   Atomic::release_store(&_task, task);
541 
542   // Kick off pool startup by starting a single worker, and proceed
543   // immediately to executing the task locally.
544   start_worker_if_needed();
545 
546   // Execute the task ourselves, while workers are catching up.
547   // This allows us to hide parts of task handoff latency.
548   task->run();
549 
550   // Done executing task locally, wait for any remaining workers to complete.
551   // Once all workers report, we can proceed to termination. To do this safely,
552   // we need to make sure every worker has left. A spin-wait alone would suffice,
553   // but we do not want to burn cycles on it. A semaphore alone would not be safe,
554   // since workers can still be inside it as we proceed from wait here. So we block
555   // on semaphore first, and then spin-wait for all workers to terminate.
556   _end_semaphore.wait();
557   SpinYield spin;
558   while (Atomic::load(&_finish_tokens) != 0) {
559     spin.wait();
560   }
561 
562   OrderAccess::fence();
563 
564   assert(Atomic::load(&_finish_tokens) == 0, "All tokens are consumed");
565 }
566 
567 void ArchiveWorkers::run_as_worker() {
568   assert(is_parallel(), "Should be in parallel mode");
569 
570   ArchiveWorkerTask* task = Atomic::load_acquire(&_task);
571   task->run();
572 
573   // All work done in threads should be visible to caller.
574   OrderAccess::fence();
575 
576   // Signal the pool the work is complete, and we are exiting.
577   // Worker cannot do anything else with the pool after this.
578   if (Atomic::sub(&_finish_tokens, 1, memory_order_relaxed) == 1) {
579     // Last worker leaving. Notify the pool it can unblock to spin-wait.
580     // Then consume the last token and leave.
581     _end_semaphore.signal();
582     int last = Atomic::sub(&_finish_tokens, 1, memory_order_relaxed);
583     assert(last == 0, "Should be");
584   }
585 }
586 
587 void ArchiveWorkerTask::run() {
588   while (true) {
589     int chunk = Atomic::load(&_chunk);
590     if (chunk >= _max_chunks) {
591       return;
592     }
593     if (Atomic::cmpxchg(&_chunk, chunk, chunk + 1, memory_order_relaxed) == chunk) {
594       assert(0 <= chunk && chunk < _max_chunks, "Sanity");
595       work(chunk, _max_chunks);
596     }
597   }
598 }
599 
600 void ArchiveWorkerTask::configure_max_chunks(int max_chunks) {
601   if (_max_chunks == 0) {
602     _max_chunks = max_chunks;
603   }
604 }
605 
606 ArchiveWorkerThread::ArchiveWorkerThread(ArchiveWorkers* pool) : NamedThread(), _pool(pool) {
607   set_name("ArchiveWorkerThread");
608   if (os::create_thread(this, os::os_thread)) {
609     os::start_thread(this);
610   } else {
611     vm_exit_during_initialization("Unable to create archive worker",
612                                   os::native_thread_creation_failed_msg());
613   }
614 }
615 
616 void ArchiveWorkerThread::run() {
617   // Avalanche startup: each worker starts two others.
618   _pool->start_worker_if_needed();
619   _pool->start_worker_if_needed();
620 
621   // Set ourselves up.
622   os::set_priority(this, NearMaxPriority);
623 
624   // Work.
625   _pool->run_as_worker();
626 }
627 
628 void ArchiveWorkerThread::post_run() {
629   this->NamedThread::post_run();
630   delete this;
631 }