1 /*
2  * Copyright (c) 2001, 2018, 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 #ifndef SHARE_VM_MEMORY_BINARYTREEDICTIONARY_INLINE_HPP
26 #define SHARE_VM_MEMORY_BINARYTREEDICTIONARY_INLINE_HPP
27 
28 #include "gc/shared/spaceDecorator.hpp"
29 #include "logging/log.hpp"
30 #include "logging/logStream.hpp"
31 #include "memory/binaryTreeDictionary.hpp"
32 #include "memory/freeList.inline.hpp"
33 #include "memory/resourceArea.hpp"
34 #include "runtime/mutex.hpp"
35 #include "runtime/globals.hpp"
36 #include "utilities/macros.hpp"
37 #include "utilities/ostream.hpp"
38 
39 ////////////////////////////////////////////////////////////////////////////////
40 // A binary tree based search structure for free blocks.
41 // This is currently used in the Concurrent Mark&Sweep implementation.
42 ////////////////////////////////////////////////////////////////////////////////
43 
44 template <class Chunk_t, class FreeList_t>
as_TreeChunk(Chunk_t * fc)45 TreeChunk<Chunk_t, FreeList_t>* TreeChunk<Chunk_t, FreeList_t>::as_TreeChunk(Chunk_t* fc) {
46   // Do some assertion checking here.
47   return (TreeChunk<Chunk_t, FreeList_t>*) fc;
48 }
49 
50 template <class Chunk_t, class FreeList_t>
verify_tree_chunk_list() const51 void TreeChunk<Chunk_t, FreeList_t>::verify_tree_chunk_list() const {
52   TreeChunk<Chunk_t, FreeList_t>* nextTC = (TreeChunk<Chunk_t, FreeList_t>*)next();
53   if (prev() != NULL) { // interior list node shouldn't have tree fields
54     guarantee(embedded_list()->parent() == NULL && embedded_list()->left() == NULL &&
55               embedded_list()->right()  == NULL, "should be clear");
56   }
57   if (nextTC != NULL) {
58     guarantee(as_TreeChunk(nextTC->prev()) == this, "broken chain");
59     guarantee(nextTC->size() == size(), "wrong size");
60     nextTC->verify_tree_chunk_list();
61   }
62 }
63 
64 template <class Chunk_t, class FreeList_t>
TreeList()65 TreeList<Chunk_t, FreeList_t>::TreeList() : _parent(NULL),
66   _left(NULL), _right(NULL) {}
67 
68 template <class Chunk_t, class FreeList_t>
69 TreeList<Chunk_t, FreeList_t>*
as_TreeList(TreeChunk<Chunk_t,FreeList_t> * tc)70 TreeList<Chunk_t, FreeList_t>::as_TreeList(TreeChunk<Chunk_t,FreeList_t>* tc) {
71   // This first free chunk in the list will be the tree list.
72   assert((tc->size() >= (TreeChunk<Chunk_t, FreeList_t>::min_size())),
73     "Chunk is too small for a TreeChunk");
74   TreeList<Chunk_t, FreeList_t>* tl = tc->embedded_list();
75   tl->initialize();
76   tc->set_list(tl);
77   tl->set_size(tc->size());
78   tl->link_head(tc);
79   tl->link_tail(tc);
80   tl->set_count(1);
81   assert(tl->parent() == NULL, "Should be clear");
82   return tl;
83 }
84 
85 template <class Chunk_t, class FreeList_t>
86 TreeList<Chunk_t, FreeList_t>*
as_TreeList(HeapWord * addr,size_t size)87 TreeList<Chunk_t, FreeList_t>::as_TreeList(HeapWord* addr, size_t size) {
88   TreeChunk<Chunk_t, FreeList_t>* tc = (TreeChunk<Chunk_t, FreeList_t>*) addr;
89   assert((size >= TreeChunk<Chunk_t, FreeList_t>::min_size()),
90     "Chunk is too small for a TreeChunk");
91   // The space will have been mangled initially but
92   // is not remangled when a Chunk_t is returned to the free list
93   // (since it is used to maintain the chunk on the free list).
94   tc->assert_is_mangled();
95   tc->set_size(size);
96   tc->link_prev(NULL);
97   tc->link_next(NULL);
98   TreeList<Chunk_t, FreeList_t>* tl = TreeList<Chunk_t, FreeList_t>::as_TreeList(tc);
99   return tl;
100 }
101 
102 
103 template <class Chunk_t, class FreeList_t>
104 TreeList<Chunk_t, FreeList_t>*
get_better_list(BinaryTreeDictionary<Chunk_t,FreeList_t> * dictionary)105 TreeList<Chunk_t, FreeList_t>::get_better_list(
106   BinaryTreeDictionary<Chunk_t, FreeList_t>* dictionary) {
107   return this;
108 }
109 
110 template <class Chunk_t, class FreeList_t>
remove_chunk_replace_if_needed(TreeChunk<Chunk_t,FreeList_t> * tc)111 TreeList<Chunk_t, FreeList_t>* TreeList<Chunk_t, FreeList_t>::remove_chunk_replace_if_needed(TreeChunk<Chunk_t, FreeList_t>* tc) {
112 
113   TreeList<Chunk_t, FreeList_t>* retTL = this;
114   Chunk_t* list = head();
115   assert(!list || list != list->next(), "Chunk on list twice");
116   assert(tc != NULL, "Chunk being removed is NULL");
117   assert(parent() == NULL || this == parent()->left() ||
118     this == parent()->right(), "list is inconsistent");
119   assert(tc->is_free(), "Header is not marked correctly");
120   assert(head() == NULL || head()->prev() == NULL, "list invariant");
121   assert(tail() == NULL || tail()->next() == NULL, "list invariant");
122 
123   Chunk_t* prevFC = tc->prev();
124   TreeChunk<Chunk_t, FreeList_t>* nextTC = TreeChunk<Chunk_t, FreeList_t>::as_TreeChunk(tc->next());
125   assert(list != NULL, "should have at least the target chunk");
126 
127   // Is this the first item on the list?
128   if (tc == list) {
129     // The "getChunk..." functions for a TreeList<Chunk_t, FreeList_t> will not return the
130     // first chunk in the list unless it is the last chunk in the list
131     // because the first chunk is also acting as the tree node.
132     // When coalescing happens, however, the first chunk in the a tree
133     // list can be the start of a free range.  Free ranges are removed
134     // from the free lists so that they are not available to be
135     // allocated when the sweeper yields (giving up the free list lock)
136     // to allow mutator activity.  If this chunk is the first in the
137     // list and is not the last in the list, do the work to copy the
138     // TreeList<Chunk_t, FreeList_t> from the first chunk to the next chunk and update all
139     // the TreeList<Chunk_t, FreeList_t> pointers in the chunks in the list.
140     if (nextTC == NULL) {
141       assert(prevFC == NULL, "Not last chunk in the list");
142       set_tail(NULL);
143       set_head(NULL);
144     } else {
145       // copy embedded list.
146       nextTC->set_embedded_list(tc->embedded_list());
147       retTL = nextTC->embedded_list();
148       // Fix the pointer to the list in each chunk in the list.
149       // This can be slow for a long list.  Consider having
150       // an option that does not allow the first chunk on the
151       // list to be coalesced.
152       for (TreeChunk<Chunk_t, FreeList_t>* curTC = nextTC; curTC != NULL;
153           curTC = TreeChunk<Chunk_t, FreeList_t>::as_TreeChunk(curTC->next())) {
154         curTC->set_list(retTL);
155       }
156       // Fix the parent to point to the new TreeList<Chunk_t, FreeList_t>.
157       if (retTL->parent() != NULL) {
158         if (this == retTL->parent()->left()) {
159           retTL->parent()->set_left(retTL);
160         } else {
161           assert(this == retTL->parent()->right(), "Parent is incorrect");
162           retTL->parent()->set_right(retTL);
163         }
164       }
165       // Fix the children's parent pointers to point to the
166       // new list.
167       assert(right() == retTL->right(), "Should have been copied");
168       if (retTL->right() != NULL) {
169         retTL->right()->set_parent(retTL);
170       }
171       assert(left() == retTL->left(), "Should have been copied");
172       if (retTL->left() != NULL) {
173         retTL->left()->set_parent(retTL);
174       }
175       retTL->link_head(nextTC);
176       assert(nextTC->is_free(), "Should be a free chunk");
177     }
178   } else {
179     if (nextTC == NULL) {
180       // Removing chunk at tail of list
181       this->link_tail(prevFC);
182     }
183     // Chunk is interior to the list
184     prevFC->link_after(nextTC);
185   }
186 
187   // Below this point the embedded TreeList<Chunk_t, FreeList_t> being used for the
188   // tree node may have changed. Don't use "this"
189   // TreeList<Chunk_t, FreeList_t>*.
190   // chunk should still be a free chunk (bit set in _prev)
191   assert(!retTL->head() || retTL->size() == retTL->head()->size(),
192     "Wrong sized chunk in list");
193   debug_only(
194     tc->link_prev(NULL);
195     tc->link_next(NULL);
196     tc->set_list(NULL);
197     bool prev_found = false;
198     bool next_found = false;
199     for (Chunk_t* curFC = retTL->head();
200          curFC != NULL; curFC = curFC->next()) {
201       assert(curFC != tc, "Chunk is still in list");
202       if (curFC == prevFC) {
203         prev_found = true;
204       }
205       if (curFC == nextTC) {
206         next_found = true;
207       }
208     }
209     assert(prevFC == NULL || prev_found, "Chunk was lost from list");
210     assert(nextTC == NULL || next_found, "Chunk was lost from list");
211     assert(retTL->parent() == NULL ||
212            retTL == retTL->parent()->left() ||
213            retTL == retTL->parent()->right(),
214            "list is inconsistent");
215   )
216   retTL->decrement_count();
217 
218   assert(tc->is_free(), "Should still be a free chunk");
219   assert(retTL->head() == NULL || retTL->head()->prev() == NULL,
220     "list invariant");
221   assert(retTL->tail() == NULL || retTL->tail()->next() == NULL,
222     "list invariant");
223   return retTL;
224 }
225 
226 template <class Chunk_t, class FreeList_t>
return_chunk_at_tail(TreeChunk<Chunk_t,FreeList_t> * chunk)227 void TreeList<Chunk_t, FreeList_t>::return_chunk_at_tail(TreeChunk<Chunk_t, FreeList_t>* chunk) {
228   assert(chunk != NULL, "returning NULL chunk");
229   assert(chunk->list() == this, "list should be set for chunk");
230   assert(tail() != NULL, "The tree list is embedded in the first chunk");
231   // which means that the list can never be empty.
232   // This is expensive for metaspace
233   assert(!FLSVerifyDictionary || !this->verify_chunk_in_free_list(chunk), "Double entry");
234   assert(head() == NULL || head()->prev() == NULL, "list invariant");
235   assert(tail() == NULL || tail()->next() == NULL, "list invariant");
236 
237   Chunk_t* fc = tail();
238   fc->link_after(chunk);
239   this->link_tail(chunk);
240 
241   assert(!tail() || size() == tail()->size(), "Wrong sized chunk in list");
242   FreeList_t::increment_count();
243   debug_only(this->increment_returned_bytes_by(chunk->size()*sizeof(HeapWord));)
244   assert(head() == NULL || head()->prev() == NULL, "list invariant");
245   assert(tail() == NULL || tail()->next() == NULL, "list invariant");
246 }
247 
248 // Add this chunk at the head of the list.  "At the head of the list"
249 // is defined to be after the chunk pointer to by head().  This is
250 // because the TreeList<Chunk_t, FreeList_t> is embedded in the first TreeChunk<Chunk_t, FreeList_t> in the
251 // list.  See the definition of TreeChunk<Chunk_t, FreeList_t>.
252 template <class Chunk_t, class FreeList_t>
return_chunk_at_head(TreeChunk<Chunk_t,FreeList_t> * chunk)253 void TreeList<Chunk_t, FreeList_t>::return_chunk_at_head(TreeChunk<Chunk_t, FreeList_t>* chunk) {
254   assert(chunk->list() == this, "list should be set for chunk");
255   assert(head() != NULL, "The tree list is embedded in the first chunk");
256   assert(chunk != NULL, "returning NULL chunk");
257   // This is expensive for metaspace
258   assert(!FLSVerifyDictionary || !this->verify_chunk_in_free_list(chunk), "Double entry");
259   assert(head() == NULL || head()->prev() == NULL, "list invariant");
260   assert(tail() == NULL || tail()->next() == NULL, "list invariant");
261 
262   Chunk_t* fc = head()->next();
263   if (fc != NULL) {
264     chunk->link_after(fc);
265   } else {
266     assert(tail() == NULL, "List is inconsistent");
267     this->link_tail(chunk);
268   }
269   head()->link_after(chunk);
270   assert(!head() || size() == head()->size(), "Wrong sized chunk in list");
271   FreeList_t::increment_count();
272   debug_only(this->increment_returned_bytes_by(chunk->size()*sizeof(HeapWord));)
273   assert(head() == NULL || head()->prev() == NULL, "list invariant");
274   assert(tail() == NULL || tail()->next() == NULL, "list invariant");
275 }
276 
277 template <class Chunk_t, class FreeList_t>
assert_is_mangled() const278 void TreeChunk<Chunk_t, FreeList_t>::assert_is_mangled() const {
279   assert((ZapUnusedHeapArea &&
280           SpaceMangler::is_mangled((HeapWord*) Chunk_t::size_addr()) &&
281           SpaceMangler::is_mangled((HeapWord*) Chunk_t::prev_addr()) &&
282           SpaceMangler::is_mangled((HeapWord*) Chunk_t::next_addr())) ||
283           (size() == 0 && prev() == NULL && next() == NULL),
284     "Space should be clear or mangled");
285 }
286 
287 template <class Chunk_t, class FreeList_t>
head_as_TreeChunk()288 TreeChunk<Chunk_t, FreeList_t>* TreeList<Chunk_t, FreeList_t>::head_as_TreeChunk() {
289   assert(head() == NULL || (TreeChunk<Chunk_t, FreeList_t>::as_TreeChunk(head())->list() == this),
290     "Wrong type of chunk?");
291   return TreeChunk<Chunk_t, FreeList_t>::as_TreeChunk(head());
292 }
293 
294 template <class Chunk_t, class FreeList_t>
first_available()295 TreeChunk<Chunk_t, FreeList_t>* TreeList<Chunk_t, FreeList_t>::first_available() {
296   assert(head() != NULL, "The head of the list cannot be NULL");
297   Chunk_t* fc = head()->next();
298   TreeChunk<Chunk_t, FreeList_t>* retTC;
299   if (fc == NULL) {
300     retTC = head_as_TreeChunk();
301   } else {
302     retTC = TreeChunk<Chunk_t, FreeList_t>::as_TreeChunk(fc);
303   }
304   assert(retTC->list() == this, "Wrong type of chunk.");
305   return retTC;
306 }
307 
308 // Returns the block with the largest heap address amongst
309 // those in the list for this size; potentially slow and expensive,
310 // use with caution!
311 template <class Chunk_t, class FreeList_t>
largest_address()312 TreeChunk<Chunk_t, FreeList_t>* TreeList<Chunk_t, FreeList_t>::largest_address() {
313   assert(head() != NULL, "The head of the list cannot be NULL");
314   Chunk_t* fc = head()->next();
315   TreeChunk<Chunk_t, FreeList_t>* retTC;
316   if (fc == NULL) {
317     retTC = head_as_TreeChunk();
318   } else {
319     // walk down the list and return the one with the highest
320     // heap address among chunks of this size.
321     Chunk_t* last = fc;
322     while (fc->next() != NULL) {
323       if ((HeapWord*)last < (HeapWord*)fc) {
324         last = fc;
325       }
326       fc = fc->next();
327     }
328     retTC = TreeChunk<Chunk_t, FreeList_t>::as_TreeChunk(last);
329   }
330   assert(retTC->list() == this, "Wrong type of chunk.");
331   return retTC;
332 }
333 
334 template <class Chunk_t, class FreeList_t>
BinaryTreeDictionary(MemRegion mr)335 BinaryTreeDictionary<Chunk_t, FreeList_t>::BinaryTreeDictionary(MemRegion mr) {
336   assert((mr.byte_size() > min_size()), "minimum chunk size");
337 
338   reset(mr);
339   assert(root()->left() == NULL, "reset check failed");
340   assert(root()->right() == NULL, "reset check failed");
341   assert(root()->head()->next() == NULL, "reset check failed");
342   assert(root()->head()->prev() == NULL, "reset check failed");
343   assert(total_size() == root()->size(), "reset check failed");
344   assert(total_free_blocks() == 1, "reset check failed");
345 }
346 
347 template <class Chunk_t, class FreeList_t>
inc_total_size(size_t inc)348 void BinaryTreeDictionary<Chunk_t, FreeList_t>::inc_total_size(size_t inc) {
349   _total_size = _total_size + inc;
350 }
351 
352 template <class Chunk_t, class FreeList_t>
dec_total_size(size_t dec)353 void BinaryTreeDictionary<Chunk_t, FreeList_t>::dec_total_size(size_t dec) {
354   _total_size = _total_size - dec;
355 }
356 
357 template <class Chunk_t, class FreeList_t>
reset(MemRegion mr)358 void BinaryTreeDictionary<Chunk_t, FreeList_t>::reset(MemRegion mr) {
359   assert((mr.byte_size() > min_size()), "minimum chunk size");
360   set_root(TreeList<Chunk_t, FreeList_t>::as_TreeList(mr.start(), mr.word_size()));
361   set_total_size(mr.word_size());
362   set_total_free_blocks(1);
363 }
364 
365 template <class Chunk_t, class FreeList_t>
reset(HeapWord * addr,size_t byte_size)366 void BinaryTreeDictionary<Chunk_t, FreeList_t>::reset(HeapWord* addr, size_t byte_size) {
367   MemRegion mr(addr, heap_word_size(byte_size));
368   reset(mr);
369 }
370 
371 template <class Chunk_t, class FreeList_t>
reset()372 void BinaryTreeDictionary<Chunk_t, FreeList_t>::reset() {
373   set_root(NULL);
374   set_total_size(0);
375   set_total_free_blocks(0);
376 }
377 
378 // Get a free block of size at least size from tree, or NULL.
379 template <class Chunk_t, class FreeList_t>
380 TreeChunk<Chunk_t, FreeList_t>*
get_chunk_from_tree(size_t size)381 BinaryTreeDictionary<Chunk_t, FreeList_t>::get_chunk_from_tree(size_t size)
382 {
383   TreeList<Chunk_t, FreeList_t> *curTL, *prevTL;
384   TreeChunk<Chunk_t, FreeList_t>* retTC = NULL;
385 
386   assert((size >= min_size()), "minimum chunk size");
387   if (FLSVerifyDictionary) {
388     verify_tree();
389   }
390   // starting at the root, work downwards trying to find match.
391   // Remember the last node of size too great or too small.
392   for (prevTL = curTL = root(); curTL != NULL;) {
393     if (curTL->size() == size) {        // exact match
394       break;
395     }
396     prevTL = curTL;
397     if (curTL->size() < size) {        // proceed to right sub-tree
398       curTL = curTL->right();
399     } else {                           // proceed to left sub-tree
400       assert(curTL->size() > size, "size inconsistency");
401       curTL = curTL->left();
402     }
403   }
404   if (curTL == NULL) { // couldn't find exact match
405 
406     // try and find the next larger size by walking back up the search path
407     for (curTL = prevTL; curTL != NULL;) {
408       if (curTL->size() >= size) break;
409       else curTL = curTL->parent();
410     }
411     assert(curTL == NULL || curTL->count() > 0,
412       "An empty list should not be in the tree");
413   }
414   if (curTL != NULL) {
415     assert(curTL->size() >= size, "size inconsistency");
416 
417     curTL = curTL->get_better_list(this);
418 
419     retTC = curTL->first_available();
420     assert((retTC != NULL) && (curTL->count() > 0),
421       "A list in the binary tree should not be NULL");
422     assert(retTC->size() >= size,
423       "A chunk of the wrong size was found");
424     remove_chunk_from_tree(retTC);
425     assert(retTC->is_free(), "Header is not marked correctly");
426   }
427 
428   if (FLSVerifyDictionary) {
429     verify();
430   }
431   return retTC;
432 }
433 
434 template <class Chunk_t, class FreeList_t>
find_list(size_t size) const435 TreeList<Chunk_t, FreeList_t>* BinaryTreeDictionary<Chunk_t, FreeList_t>::find_list(size_t size) const {
436   TreeList<Chunk_t, FreeList_t>* curTL;
437   for (curTL = root(); curTL != NULL;) {
438     if (curTL->size() == size) {        // exact match
439       break;
440     }
441 
442     if (curTL->size() < size) {        // proceed to right sub-tree
443       curTL = curTL->right();
444     } else {                           // proceed to left sub-tree
445       assert(curTL->size() > size, "size inconsistency");
446       curTL = curTL->left();
447     }
448   }
449   return curTL;
450 }
451 
452 
453 template <class Chunk_t, class FreeList_t>
verify_chunk_in_free_list(Chunk_t * tc) const454 bool BinaryTreeDictionary<Chunk_t, FreeList_t>::verify_chunk_in_free_list(Chunk_t* tc) const {
455   size_t size = tc->size();
456   TreeList<Chunk_t, FreeList_t>* tl = find_list(size);
457   if (tl == NULL) {
458     return false;
459   } else {
460     return tl->verify_chunk_in_free_list(tc);
461   }
462 }
463 
464 template <class Chunk_t, class FreeList_t>
465 Chunk_t* BinaryTreeDictionary<Chunk_t, FreeList_t>::find_largest_dict() const {
466   TreeList<Chunk_t, FreeList_t> *curTL = root();
467   if (curTL != NULL) {
468     while(curTL->right() != NULL) curTL = curTL->right();
469     return curTL->largest_address();
470   } else {
471     return NULL;
472   }
473 }
474 
475 // Remove the current chunk from the tree.  If it is not the last
476 // chunk in a list on a tree node, just unlink it.
477 // If it is the last chunk in the list (the next link is NULL),
478 // remove the node and repair the tree.
479 template <class Chunk_t, class FreeList_t>
480 TreeChunk<Chunk_t, FreeList_t>*
remove_chunk_from_tree(TreeChunk<Chunk_t,FreeList_t> * tc)481 BinaryTreeDictionary<Chunk_t, FreeList_t>::remove_chunk_from_tree(TreeChunk<Chunk_t, FreeList_t>* tc) {
482   assert(tc != NULL, "Should not call with a NULL chunk");
483   assert(tc->is_free(), "Header is not marked correctly");
484 
485   TreeList<Chunk_t, FreeList_t> *newTL, *parentTL;
486   TreeChunk<Chunk_t, FreeList_t>* retTC;
487   TreeList<Chunk_t, FreeList_t>* tl = tc->list();
488   debug_only(
489     bool removing_only_chunk = false;
490     if (tl == _root) {
491       if ((_root->left() == NULL) && (_root->right() == NULL)) {
492         if (_root->count() == 1) {
493           assert(_root->head() == tc, "Should only be this one chunk");
494           removing_only_chunk = true;
495         }
496       }
497     }
498   )
499   assert(tl != NULL, "List should be set");
500   assert(tl->parent() == NULL || tl == tl->parent()->left() ||
501          tl == tl->parent()->right(), "list is inconsistent");
502 
503   bool complicated_splice = false;
504 
505   retTC = tc;
506   // Removing this chunk can have the side effect of changing the node
507   // (TreeList<Chunk_t, FreeList_t>*) in the tree.  If the node is the root, update it.
508   TreeList<Chunk_t, FreeList_t>* replacementTL = tl->remove_chunk_replace_if_needed(tc);
509   assert(tc->is_free(), "Chunk should still be free");
510   assert(replacementTL->parent() == NULL ||
511          replacementTL == replacementTL->parent()->left() ||
512          replacementTL == replacementTL->parent()->right(),
513          "list is inconsistent");
514   if (tl == root()) {
515     assert(replacementTL->parent() == NULL, "Incorrectly replacing root");
516     set_root(replacementTL);
517   }
518 #ifdef ASSERT
519     if (tl != replacementTL) {
520       assert(replacementTL->head() != NULL,
521         "If the tree list was replaced, it should not be a NULL list");
522       TreeList<Chunk_t, FreeList_t>* rhl = replacementTL->head_as_TreeChunk()->list();
523       TreeList<Chunk_t, FreeList_t>* rtl =
524         TreeChunk<Chunk_t, FreeList_t>::as_TreeChunk(replacementTL->tail())->list();
525       assert(rhl == replacementTL, "Broken head");
526       assert(rtl == replacementTL, "Broken tail");
527       assert(replacementTL->size() == tc->size(),  "Broken size");
528     }
529 #endif
530 
531   // Does the tree need to be repaired?
532   if (replacementTL->count() == 0) {
533     assert(replacementTL->head() == NULL &&
534            replacementTL->tail() == NULL, "list count is incorrect");
535     // Find the replacement node for the (soon to be empty) node being removed.
536     // if we have a single (or no) child, splice child in our stead
537     if (replacementTL->left() == NULL) {
538       // left is NULL so pick right.  right may also be NULL.
539       newTL = replacementTL->right();
540       debug_only(replacementTL->clear_right();)
541     } else if (replacementTL->right() == NULL) {
542       // right is NULL
543       newTL = replacementTL->left();
544       debug_only(replacementTL->clear_left();)
545     } else {  // we have both children, so, by patriarchal convention,
546               // my replacement is least node in right sub-tree
547       complicated_splice = true;
548       newTL = remove_tree_minimum(replacementTL->right());
549       assert(newTL != NULL && newTL->left() == NULL &&
550              newTL->right() == NULL, "sub-tree minimum exists");
551     }
552     // newTL is the replacement for the (soon to be empty) node.
553     // newTL may be NULL.
554     // should verify; we just cleanly excised our replacement
555     if (FLSVerifyDictionary) {
556       verify_tree();
557     }
558     // first make newTL my parent's child
559     if ((parentTL = replacementTL->parent()) == NULL) {
560       // newTL should be root
561       assert(tl == root(), "Incorrectly replacing root");
562       set_root(newTL);
563       if (newTL != NULL) {
564         newTL->clear_parent();
565       }
566     } else if (parentTL->right() == replacementTL) {
567       // replacementTL is a right child
568       parentTL->set_right(newTL);
569     } else {                                // replacementTL is a left child
570       assert(parentTL->left() == replacementTL, "should be left child");
571       parentTL->set_left(newTL);
572     }
573     debug_only(replacementTL->clear_parent();)
574     if (complicated_splice) {  // we need newTL to get replacementTL's
575                               // two children
576       assert(newTL != NULL &&
577              newTL->left() == NULL && newTL->right() == NULL,
578             "newTL should not have encumbrances from the past");
579       // we'd like to assert as below:
580       // assert(replacementTL->left() != NULL && replacementTL->right() != NULL,
581       //       "else !complicated_splice");
582       // ... however, the above assertion is too strong because we aren't
583       // guaranteed that replacementTL->right() is still NULL.
584       // Recall that we removed
585       // the right sub-tree minimum from replacementTL.
586       // That may well have been its right
587       // child! So we'll just assert half of the above:
588       assert(replacementTL->left() != NULL, "else !complicated_splice");
589       newTL->set_left(replacementTL->left());
590       newTL->set_right(replacementTL->right());
591       debug_only(
592         replacementTL->clear_right();
593         replacementTL->clear_left();
594       )
595     }
596     assert(replacementTL->right() == NULL &&
597            replacementTL->left() == NULL &&
598            replacementTL->parent() == NULL,
599         "delete without encumbrances");
600   }
601 
602   assert(total_size() >= retTC->size(), "Incorrect total size");
603   dec_total_size(retTC->size());     // size book-keeping
604   assert(total_free_blocks() > 0, "Incorrect total count");
605   set_total_free_blocks(total_free_blocks() - 1);
606 
607   assert(retTC != NULL, "null chunk?");
608   assert(retTC->prev() == NULL && retTC->next() == NULL,
609          "should return without encumbrances");
610   if (FLSVerifyDictionary) {
611     verify_tree();
612   }
613   assert(!removing_only_chunk || _root == NULL, "root should be NULL");
614   return TreeChunk<Chunk_t, FreeList_t>::as_TreeChunk(retTC);
615 }
616 
617 // Remove the leftmost node (lm) in the tree and return it.
618 // If lm has a right child, link it to the left node of
619 // the parent of lm.
620 template <class Chunk_t, class FreeList_t>
remove_tree_minimum(TreeList<Chunk_t,FreeList_t> * tl)621 TreeList<Chunk_t, FreeList_t>* BinaryTreeDictionary<Chunk_t, FreeList_t>::remove_tree_minimum(TreeList<Chunk_t, FreeList_t>* tl) {
622   assert(tl != NULL && tl->parent() != NULL, "really need a proper sub-tree");
623   // locate the subtree minimum by walking down left branches
624   TreeList<Chunk_t, FreeList_t>* curTL = tl;
625   for (; curTL->left() != NULL; curTL = curTL->left());
626   // obviously curTL now has at most one child, a right child
627   if (curTL != root()) {  // Should this test just be removed?
628     TreeList<Chunk_t, FreeList_t>* parentTL = curTL->parent();
629     if (parentTL->left() == curTL) { // curTL is a left child
630       parentTL->set_left(curTL->right());
631     } else {
632       // If the list tl has no left child, then curTL may be
633       // the right child of parentTL.
634       assert(parentTL->right() == curTL, "should be a right child");
635       parentTL->set_right(curTL->right());
636     }
637   } else {
638     // The only use of this method would not pass the root of the
639     // tree (as indicated by the assertion above that the tree list
640     // has a parent) but the specification does not explicitly exclude the
641     // passing of the root so accommodate it.
642     set_root(NULL);
643   }
644   debug_only(
645     curTL->clear_parent();  // Test if this needs to be cleared
646     curTL->clear_right();    // recall, above, left child is already null
647   )
648   // we just excised a (non-root) node, we should still verify all tree invariants
649   if (FLSVerifyDictionary) {
650     verify_tree();
651   }
652   return curTL;
653 }
654 
655 template <class Chunk_t, class FreeList_t>
insert_chunk_in_tree(Chunk_t * fc)656 void BinaryTreeDictionary<Chunk_t, FreeList_t>::insert_chunk_in_tree(Chunk_t* fc) {
657   TreeList<Chunk_t, FreeList_t> *curTL, *prevTL;
658   size_t size = fc->size();
659 
660   assert((size >= min_size()),
661          SIZE_FORMAT " is too small to be a TreeChunk<Chunk_t, FreeList_t> " SIZE_FORMAT,
662          size, min_size());
663   if (FLSVerifyDictionary) {
664     verify_tree();
665   }
666 
667   fc->clear_next();
668   fc->link_prev(NULL);
669 
670   // work down from the _root, looking for insertion point
671   for (prevTL = curTL = root(); curTL != NULL;) {
672     if (curTL->size() == size)  // exact match
673       break;
674     prevTL = curTL;
675     if (curTL->size() > size) { // follow left branch
676       curTL = curTL->left();
677     } else {                    // follow right branch
678       assert(curTL->size() < size, "size inconsistency");
679       curTL = curTL->right();
680     }
681   }
682   TreeChunk<Chunk_t, FreeList_t>* tc = TreeChunk<Chunk_t, FreeList_t>::as_TreeChunk(fc);
683   // This chunk is being returned to the binary tree.  Its embedded
684   // TreeList<Chunk_t, FreeList_t> should be unused at this point.
685   tc->initialize();
686   if (curTL != NULL) {          // exact match
687     tc->set_list(curTL);
688     curTL->return_chunk_at_tail(tc);
689   } else {                     // need a new node in tree
690     tc->clear_next();
691     tc->link_prev(NULL);
692     TreeList<Chunk_t, FreeList_t>* newTL = TreeList<Chunk_t, FreeList_t>::as_TreeList(tc);
693     assert(((TreeChunk<Chunk_t, FreeList_t>*)tc)->list() == newTL,
694       "List was not initialized correctly");
695     if (prevTL == NULL) {      // we are the only tree node
696       assert(root() == NULL, "control point invariant");
697       set_root(newTL);
698     } else {                   // insert under prevTL ...
699       if (prevTL->size() < size) {   // am right child
700         assert(prevTL->right() == NULL, "control point invariant");
701         prevTL->set_right(newTL);
702       } else {                       // am left child
703         assert(prevTL->size() > size && prevTL->left() == NULL, "cpt pt inv");
704         prevTL->set_left(newTL);
705       }
706     }
707   }
708   assert(tc->list() != NULL, "Tree list should be set");
709 
710   inc_total_size(size);
711   // Method 'total_size_in_tree' walks through the every block in the
712   // tree, so it can cause significant performance loss if there are
713   // many blocks in the tree
714   assert(!FLSVerifyDictionary || total_size_in_tree(root()) == total_size(), "_total_size inconsistency");
715   set_total_free_blocks(total_free_blocks() + 1);
716   if (FLSVerifyDictionary) {
717     verify_tree();
718   }
719 }
720 
721 template <class Chunk_t, class FreeList_t>
max_chunk_size() const722 size_t BinaryTreeDictionary<Chunk_t, FreeList_t>::max_chunk_size() const {
723   verify_par_locked();
724   TreeList<Chunk_t, FreeList_t>* tc = root();
725   if (tc == NULL) return 0;
726   for (; tc->right() != NULL; tc = tc->right());
727   return tc->size();
728 }
729 
730 template <class Chunk_t, class FreeList_t>
total_list_length(TreeList<Chunk_t,FreeList_t> * tl) const731 size_t BinaryTreeDictionary<Chunk_t, FreeList_t>::total_list_length(TreeList<Chunk_t, FreeList_t>* tl) const {
732   size_t res;
733   res = tl->count();
734 #ifdef ASSERT
735   size_t cnt;
736   Chunk_t* tc = tl->head();
737   for (cnt = 0; tc != NULL; tc = tc->next(), cnt++);
738   assert(res == cnt, "The count is not being maintained correctly");
739 #endif
740   return res;
741 }
742 
743 template <class Chunk_t, class FreeList_t>
total_size_in_tree(TreeList<Chunk_t,FreeList_t> * tl) const744 size_t BinaryTreeDictionary<Chunk_t, FreeList_t>::total_size_in_tree(TreeList<Chunk_t, FreeList_t>* tl) const {
745   if (tl == NULL)
746     return 0;
747   return (tl->size() * total_list_length(tl)) +
748          total_size_in_tree(tl->left())    +
749          total_size_in_tree(tl->right());
750 }
751 
752 template <class Chunk_t, class FreeList_t>
sum_of_squared_block_sizes(TreeList<Chunk_t,FreeList_t> * const tl) const753 double BinaryTreeDictionary<Chunk_t, FreeList_t>::sum_of_squared_block_sizes(TreeList<Chunk_t, FreeList_t>* const tl) const {
754   if (tl == NULL) {
755     return 0.0;
756   }
757   double size = (double)(tl->size());
758   double curr = size * size * total_list_length(tl);
759   curr += sum_of_squared_block_sizes(tl->left());
760   curr += sum_of_squared_block_sizes(tl->right());
761   return curr;
762 }
763 
764 template <class Chunk_t, class FreeList_t>
total_free_blocks_in_tree(TreeList<Chunk_t,FreeList_t> * tl) const765 size_t BinaryTreeDictionary<Chunk_t, FreeList_t>::total_free_blocks_in_tree(TreeList<Chunk_t, FreeList_t>* tl) const {
766   if (tl == NULL)
767     return 0;
768   return total_list_length(tl) +
769          total_free_blocks_in_tree(tl->left()) +
770          total_free_blocks_in_tree(tl->right());
771 }
772 
773 template <class Chunk_t, class FreeList_t>
num_free_blocks() const774 size_t BinaryTreeDictionary<Chunk_t, FreeList_t>::num_free_blocks() const {
775   assert(total_free_blocks_in_tree(root()) == total_free_blocks(),
776          "_total_free_blocks inconsistency");
777   return total_free_blocks();
778 }
779 
780 template <class Chunk_t, class FreeList_t>
tree_height_helper(TreeList<Chunk_t,FreeList_t> * tl) const781 size_t BinaryTreeDictionary<Chunk_t, FreeList_t>::tree_height_helper(TreeList<Chunk_t, FreeList_t>* tl) const {
782   if (tl == NULL)
783     return 0;
784   return 1 + MAX2(tree_height_helper(tl->left()),
785                   tree_height_helper(tl->right()));
786 }
787 
788 template <class Chunk_t, class FreeList_t>
tree_height() const789 size_t BinaryTreeDictionary<Chunk_t, FreeList_t>::tree_height() const {
790   return tree_height_helper(root());
791 }
792 
793 template <class Chunk_t, class FreeList_t>
total_nodes_helper(TreeList<Chunk_t,FreeList_t> * tl) const794 size_t BinaryTreeDictionary<Chunk_t, FreeList_t>::total_nodes_helper(TreeList<Chunk_t, FreeList_t>* tl) const {
795   if (tl == NULL) {
796     return 0;
797   }
798   return 1 + total_nodes_helper(tl->left()) +
799     total_nodes_helper(tl->right());
800 }
801 
802 template <class Chunk_t, class FreeList_t>
total_nodes_in_tree(TreeList<Chunk_t,FreeList_t> * tl) const803 size_t BinaryTreeDictionary<Chunk_t, FreeList_t>::total_nodes_in_tree(TreeList<Chunk_t, FreeList_t>* tl) const {
804   return total_nodes_helper(root());
805 }
806 
807 // Searches the tree for a chunk that ends at the
808 // specified address.
809 template <class Chunk_t, class FreeList_t>
810 class EndTreeSearchClosure : public DescendTreeSearchClosure<Chunk_t, FreeList_t> {
811   HeapWord* _target;
812   Chunk_t* _found;
813 
814  public:
EndTreeSearchClosure(HeapWord * target)815   EndTreeSearchClosure(HeapWord* target) : _target(target), _found(NULL) {}
do_list(FreeList_t * fl)816   bool do_list(FreeList_t* fl) {
817     Chunk_t* item = fl->head();
818     while (item != NULL) {
819       if (item->end() == (uintptr_t*) _target) {
820         _found = item;
821         return true;
822       }
823       item = item->next();
824     }
825     return false;
826   }
found()827   Chunk_t* found() { return _found; }
828 };
829 
830 template <class Chunk_t, class FreeList_t>
831 Chunk_t* BinaryTreeDictionary<Chunk_t, FreeList_t>::find_chunk_ends_at(HeapWord* target) const {
832   EndTreeSearchClosure<Chunk_t, FreeList_t> etsc(target);
833   bool found_target = etsc.do_tree(root());
834   assert(found_target || etsc.found() == NULL, "Consistency check");
835   assert(!found_target || etsc.found() != NULL, "Consistency check");
836   return etsc.found();
837 }
838 
839 // Closures and methods for calculating total bytes returned to the
840 // free lists in the tree.
841 #ifndef PRODUCT
842 template <class Chunk_t, class FreeList_t>
843 class InitializeDictReturnedBytesClosure : public AscendTreeCensusClosure<Chunk_t, FreeList_t> {
844    public:
do_list(FreeList_t * fl)845   void do_list(FreeList_t* fl) {
846     fl->set_returned_bytes(0);
847   }
848 };
849 
850 template <class Chunk_t, class FreeList_t>
initialize_dict_returned_bytes()851 void BinaryTreeDictionary<Chunk_t, FreeList_t>::initialize_dict_returned_bytes() {
852   InitializeDictReturnedBytesClosure<Chunk_t, FreeList_t> idrb;
853   idrb.do_tree(root());
854 }
855 
856 template <class Chunk_t, class FreeList_t>
857 class ReturnedBytesClosure : public AscendTreeCensusClosure<Chunk_t, FreeList_t> {
858   size_t _dict_returned_bytes;
859  public:
ReturnedBytesClosure()860   ReturnedBytesClosure() { _dict_returned_bytes = 0; }
do_list(FreeList_t * fl)861   void do_list(FreeList_t* fl) {
862     _dict_returned_bytes += fl->returned_bytes();
863   }
dict_returned_bytes()864   size_t dict_returned_bytes() { return _dict_returned_bytes; }
865 };
866 
867 template <class Chunk_t, class FreeList_t>
sum_dict_returned_bytes()868 size_t BinaryTreeDictionary<Chunk_t, FreeList_t>::sum_dict_returned_bytes() {
869   ReturnedBytesClosure<Chunk_t, FreeList_t> rbc;
870   rbc.do_tree(root());
871 
872   return rbc.dict_returned_bytes();
873 }
874 
875 // Count the number of entries in the tree.
876 template <class Chunk_t, class FreeList_t>
877 class treeCountClosure : public DescendTreeCensusClosure<Chunk_t, FreeList_t> {
878  public:
879   uint count;
treeCountClosure(uint c)880   treeCountClosure(uint c) { count = c; }
do_list(FreeList_t * fl)881   void do_list(FreeList_t* fl) {
882     count++;
883   }
884 };
885 
886 template <class Chunk_t, class FreeList_t>
total_count()887 size_t BinaryTreeDictionary<Chunk_t, FreeList_t>::total_count() {
888   treeCountClosure<Chunk_t, FreeList_t> ctc(0);
889   ctc.do_tree(root());
890   return ctc.count;
891 }
892 
893 template <class Chunk_t, class FreeList_t>
par_lock() const894 Mutex* BinaryTreeDictionary<Chunk_t, FreeList_t>::par_lock() const {
895   return _lock;
896 }
897 
898 template <class Chunk_t, class FreeList_t>
set_par_lock(Mutex * lock)899 void BinaryTreeDictionary<Chunk_t, FreeList_t>::set_par_lock(Mutex* lock) {
900   _lock = lock;
901 }
902 
903 template <class Chunk_t, class FreeList_t>
verify_par_locked() const904 void BinaryTreeDictionary<Chunk_t, FreeList_t>::verify_par_locked() const {
905 #ifdef ASSERT
906   Thread* my_thread = Thread::current();
907   if (my_thread->is_GC_task_thread()) {
908     assert(par_lock() != NULL, "Should be using locking?");
909     assert_lock_strong(par_lock());
910   }
911 #endif // ASSERT
912 }
913 #endif // PRODUCT
914 
915 // Print summary statistics
916 template <class Chunk_t, class FreeList_t>
report_statistics(outputStream * st) const917 void BinaryTreeDictionary<Chunk_t, FreeList_t>::report_statistics(outputStream* st) const {
918   verify_par_locked();
919   st->print_cr("Statistics for BinaryTreeDictionary:");
920   st->print_cr("------------------------------------");
921   size_t total_size = total_chunk_size(debug_only(NULL));
922   size_t free_blocks = num_free_blocks();
923   st->print_cr("Total Free Space: " SIZE_FORMAT, total_size);
924   st->print_cr("Max   Chunk Size: " SIZE_FORMAT, max_chunk_size());
925   st->print_cr("Number of Blocks: " SIZE_FORMAT, free_blocks);
926   if (free_blocks > 0) {
927     st->print_cr("Av.  Block  Size: " SIZE_FORMAT, total_size/free_blocks);
928   }
929   st->print_cr("Tree      Height: " SIZE_FORMAT, tree_height());
930 }
931 
932 template <class Chunk_t, class FreeList_t>
933 class PrintFreeListsClosure : public AscendTreeCensusClosure<Chunk_t, FreeList_t> {
934   outputStream* _st;
935   int _print_line;
936 
937  public:
PrintFreeListsClosure(outputStream * st)938   PrintFreeListsClosure(outputStream* st) {
939     _st = st;
940     _print_line = 0;
941   }
do_list(FreeList_t * fl)942   void do_list(FreeList_t* fl) {
943     if (++_print_line >= 40) {
944       FreeList_t::print_labels_on(_st, "size");
945       _print_line = 0;
946     }
947     fl->print_on(_st);
948     size_t sz = fl->size();
949     for (Chunk_t* fc = fl->head(); fc != NULL;
950          fc = fc->next()) {
951       _st->print_cr("\t[" PTR_FORMAT "," PTR_FORMAT ")  %s",
952                     p2i(fc), p2i((HeapWord*)fc + sz),
953                     fc->cantCoalesce() ? "\t CC" : "");
954     }
955   }
956 };
957 
958 template <class Chunk_t, class FreeList_t>
print_free_lists(outputStream * st) const959 void BinaryTreeDictionary<Chunk_t, FreeList_t>::print_free_lists(outputStream* st) const {
960 
961   FreeList_t::print_labels_on(st, "size");
962   PrintFreeListsClosure<Chunk_t, FreeList_t> pflc(st);
963   pflc.do_tree(root());
964 }
965 
966 // Verify the following tree invariants:
967 // . _root has no parent
968 // . parent and child point to each other
969 // . each node's key correctly related to that of its child(ren)
970 template <class Chunk_t, class FreeList_t>
verify_tree() const971 void BinaryTreeDictionary<Chunk_t, FreeList_t>::verify_tree() const {
972   guarantee(root() == NULL || total_free_blocks() == 0 ||
973     total_size() != 0, "_total_size shouldn't be 0?");
974   guarantee(root() == NULL || root()->parent() == NULL, "_root shouldn't have parent");
975   verify_tree_helper(root());
976 }
977 
978 template <class Chunk_t, class FreeList_t>
verify_prev_free_ptrs(TreeList<Chunk_t,FreeList_t> * tl)979 size_t BinaryTreeDictionary<Chunk_t, FreeList_t>::verify_prev_free_ptrs(TreeList<Chunk_t, FreeList_t>* tl) {
980   size_t ct = 0;
981   for (Chunk_t* curFC = tl->head(); curFC != NULL; curFC = curFC->next()) {
982     ct++;
983     assert(curFC->prev() == NULL || curFC->prev()->is_free(),
984       "Chunk should be free");
985   }
986   return ct;
987 }
988 
989 // Note: this helper is recursive rather than iterative, so use with
990 // caution on very deep trees; and watch out for stack overflow errors;
991 // In general, to be used only for debugging.
992 template <class Chunk_t, class FreeList_t>
verify_tree_helper(TreeList<Chunk_t,FreeList_t> * tl) const993 void BinaryTreeDictionary<Chunk_t, FreeList_t>::verify_tree_helper(TreeList<Chunk_t, FreeList_t>* tl) const {
994   if (tl == NULL)
995     return;
996   guarantee(tl->size() != 0, "A list must has a size");
997   guarantee(tl->left()  == NULL || tl->left()->parent()  == tl,
998          "parent<-/->left");
999   guarantee(tl->right() == NULL || tl->right()->parent() == tl,
1000          "parent<-/->right");;
1001   guarantee(tl->left() == NULL  || tl->left()->size()    <  tl->size(),
1002          "parent !> left");
1003   guarantee(tl->right() == NULL || tl->right()->size()   >  tl->size(),
1004          "parent !< left");
1005   guarantee(tl->head() == NULL || tl->head()->is_free(), "!Free");
1006   guarantee(tl->head() == NULL || tl->head_as_TreeChunk()->list() == tl,
1007     "list inconsistency");
1008   guarantee(tl->count() > 0 || (tl->head() == NULL && tl->tail() == NULL),
1009     "list count is inconsistent");
1010   guarantee(tl->count() > 1 || tl->head() == tl->tail(),
1011     "list is incorrectly constructed");
1012   size_t count = verify_prev_free_ptrs(tl);
1013   guarantee(count == (size_t)tl->count(), "Node count is incorrect");
1014   if (tl->head() != NULL) {
1015     tl->head_as_TreeChunk()->verify_tree_chunk_list();
1016   }
1017   verify_tree_helper(tl->left());
1018   verify_tree_helper(tl->right());
1019 }
1020 
1021 template <class Chunk_t, class FreeList_t>
verify() const1022 void BinaryTreeDictionary<Chunk_t, FreeList_t>::verify() const {
1023   verify_tree();
1024   guarantee(total_size() == total_size_in_tree(root()), "Total Size inconsistency");
1025 }
1026 
1027 template <class Chunk_t, class FreeList_t>
total_chunk_size(debug_only (const Mutex * lock)) const1028 size_t BinaryTreeDictionary<Chunk_t, FreeList_t>::total_chunk_size(debug_only(const Mutex* lock)) const {
1029   debug_only(
1030     if (lock != NULL && lock->owned_by_self()) {
1031       assert(total_size_in_tree(root()) == total_size(),
1032              "_total_size inconsistency");
1033     }
1034   )
1035   return total_size();
1036 }
1037 
1038 #endif // SHARE_VM_MEMORY_BINARYTREEDICTIONARY_INLINE_HPP
1039