1 /*
   2  * Copyright (c) 2018, 2019, 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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.jfr.event.gc.collection;
  27 
  28 import static java.lang.System.gc;
  29 import static java.lang.Thread.sleep;
  30 import static java.util.Set.of;
  31 import static java.util.stream.Collectors.joining;
  32 import static java.util.stream.Collectors.toList;
  33 import static java.util.stream.Collectors.toSet;
  34 import static java.util.stream.IntStream.range;
  35 import static jdk.jfr.event.gc.collection.Provoker.provokeMixedGC;
  36 import static jdk.test.lib.Asserts.assertEquals;
  37 import static jdk.test.lib.Asserts.assertTrue;
  38 import static jdk.test.lib.jfr.Events.fromRecording;
  39 import static sun.hotspot.WhiteBox.getWhiteBox;
  40 
  41 import java.io.IOException;
  42 import java.lang.ref.WeakReference;
  43 import java.math.BigDecimal;
  44 import java.util.ArrayList;
  45 import java.util.Collection;
  46 import java.util.List;
  47 import java.util.Set;
  48 
  49 import jdk.jfr.Recording;
  50 import jdk.test.lib.Asserts;
  51 import jdk.test.lib.jfr.EventNames;
  52 import sun.hotspot.WhiteBox;
  53 
  54 /**
  55  * @test
  56  * @key jfr
  57  * @requires vm.hasJFR
  58  * @requires vm.gc == "G1" | vm.gc == null
  59  * @library /test/lib /test/jdk
  60  * @build sun.hotspot.WhiteBox
  61  * @run main ClassFileInstaller sun.hotspot.WhiteBox
  62  * @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:+AlwaysTenure
  63  *      -Xms20M -Xmx20M -Xlog:gc=debug,gc+heap*=debug,gc+ergo*=debug,gc+start=debug
  64  *      -XX:G1MixedGCLiveThresholdPercent=100 -XX:G1HeapWastePercent=0 -XX:G1HeapRegionSize=1m
  65  *      -XX:+UseG1GC -XX:+UseStringDeduplication
  66  *      -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
  67  *      jdk.jfr.event.gc.collection.TestG1ParallelPhases
  68  */
  69 
  70 public class TestG1ParallelPhases {
  71     public static List<WeakReference<byte[]>> weakRefs;
  72 
  73     public static void main(String[] args) throws IOException {
  74         Recording recording = new Recording();
  75         recording.enable(EventNames.GCPhaseParallel);
  76         recording.start();
  77 
  78         // create more weak garbage than can fit in this heap (-Xmx20m), will force collection of weak references
  79         weakRefs = range(1, 30)
  80             .mapToObj(n -> new WeakReference<>(new byte[1_000_000]))
  81             .collect(toList()); // force evaluation of lazy stream (all weak refs must be created)
  82 
  83         final var MEG = 1024 * 1024;
  84         provokeMixedGC(1 * MEG);
  85         recording.stop();
  86 
  87         Set<String> usedPhases = fromRecording(recording).stream()
  88             .map(e -> e.getValue("name").toString())
  89             .collect(toSet());
  90 
  91         Set<String> allPhases = of(
  92             "ExtRootScan",
  93             "ThreadRoots",
  94             "UniverseRoots",
  95             "JNIRoots",
  96             "ObjectSynchronizerRoots",
  97             "ManagementRoots",
  98             "SystemDictionaryRoots",
  99             "CLDGRoots",
 100             "JVMTIRoots",
 101             "CMRefRoots",
 102             "MergeER",
 103             "MergeHCC",
 104             "MergeRS",
 105             "MergeLB",
 106             "ScanHR",
 107             "CodeRoots",
 108             "ObjCopy",
 109             "Termination",
 110             "StringDedupQueueFixup",
 111             "StringDedupTableFixup",
 112             "RedirtyCards",
 113             "NonYoungFreeCSet",
 114             "YoungFreeCSet"
 115         );
 116 
 117         // Some GC phases may or may not occur depending on environment. Filter them out
 118         // since we can not reliably guarantee that they occur (or not).
 119         Set<String> optPhases = of(
 120             "OptScanHR",
 121             "OptMergeRS",
 122             "OptCodeRoots",
 123             "OptObjCopy"
 124         );
 125         usedPhases.removeAll(optPhases);
 126 
 127         assertTrue(usedPhases.equals(allPhases), "Compare events expected and received"
 128             + ", Not found phases: " + allPhases.stream().filter(p -> !usedPhases.contains(p)).collect(joining(", "))
 129             + ", Not expected phases: " + usedPhases.stream().filter(p -> !allPhases.contains(p)).collect(joining(", ")));
 130     }
 131 }
 132 
 133 /**
 134  * Utility class to guarantee a mixed GC. The class allocates several arrays and
 135  * promotes them to the oldgen. After that it tries to provoke mixed GC by
 136  * allocating new objects.
 137  */
 138 class Provoker {
 139     private static void allocateOldObjects(
 140             List<byte[]> liveOldObjects,
 141             int g1HeapRegionSize,
 142             int arraySize) {
 143 
 144         var toUnreachable = new ArrayList<byte[]>();
 145 
 146         // Allocates buffer and promotes it to the old gen. Mix live and dead old objects.
 147         // allocate about two regions of old memory. At least one full old region will guarantee
 148         // mixed collection in the future
 149         range(0, g1HeapRegionSize/arraySize).forEach(n -> {
 150             liveOldObjects.add(new byte[arraySize]);
 151             toUnreachable.add(new byte[arraySize]);
 152         });
 153 
 154         // Do one young collection, AlwaysTenure will force promotion.
 155         getWhiteBox().youngGC();
 156 
 157         // Check it is promoted & keep alive
 158         Asserts.assertTrue(getWhiteBox().isObjectInOldGen(liveOldObjects), "List of the objects is suppose to be in OldGen");
 159         Asserts.assertTrue(getWhiteBox().isObjectInOldGen(toUnreachable), "List of the objects is suppose to be in OldGen");
 160     }
 161 
 162     private static void waitTillCMCFinished(int sleepTime) {
 163         while (getWhiteBox().g1InConcurrentMark()) {
 164               try {sleep(sleepTime);} catch (Exception e) {}
 165         }
 166     }
 167 
 168     /**
 169     * The necessary condition for guaranteed mixed GC is running in VM with the following flags:
 170     * -XX:+UnlockExperimentalVMOptions -XX:+AlwaysTenure -Xms{HEAP_SIZE}M
 171     * -Xmx{HEAP_SIZE}M -XX:G1MixedGCLiveThresholdPercent=100 -XX:G1HeapWastePercent=0
 172     * -XX:G1HeapRegionSize={REGION_SIZE}m
 173     *
 174     * @param g1HeapRegionSize The size of your regions in bytes
 175     */
 176     public static void provokeMixedGC(int g1HeapRegionSize) {
 177         final var arraySize = 20_000;
 178         var liveOldObjects = new ArrayList<byte[]>();
 179         allocateOldObjects(liveOldObjects, g1HeapRegionSize, arraySize);
 180         waitTillCMCFinished(10);
 181         getWhiteBox().g1StartConcMarkCycle();
 182         waitTillCMCFinished(10);
 183         getWhiteBox().youngGC();
 184         getWhiteBox().youngGC();
 185 
 186         // check that liveOldObjects still alive
 187         assertTrue(getWhiteBox().isObjectInOldGen(liveOldObjects), "List of the objects is suppose to be in OldGen");
 188     }
 189 }