1 /*
   2  * Copyright (c) 2014, 2016, 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  * @test
  26  * @summary Stress test for malloc tracking
  27  * @key nmt jcmd stress
  28  * @library /test/lib
  29  * @modules java.base/jdk.internal.misc
  30  *          java.management
  31  * @build sun.hotspot.WhiteBox
  32  * @ignore - This test is disabled since it will stress NMT and timeout during normal testing
  33  * @run main ClassFileInstaller sun.hotspot.WhiteBox
  34  * @run main/othervm/timeout=600 -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -XX:NativeMemoryTracking=detail MallocStressTest
  35  */
  36 
  37 import java.util.concurrent.atomic.AtomicInteger;
  38 import java.util.ArrayList;
  39 import java.util.List;
  40 import java.util.Random;
  41 import jdk.test.lib.JDKToolFinder;
  42 import jdk.test.lib.Platform;
  43 import jdk.test.lib.process.ProcessTools;
  44 import jdk.test.lib.process.OutputAnalyzer;
  45 import sun.hotspot.WhiteBox;
  46 
  47 public class MallocStressTest {
  48     private static int K = 1024;
  49 
  50     // The stress test runs in three phases:
  51     // 1. alloc: A lot of malloc with fewer free, which simulates a burst memory allocation
  52     //    that is usually seen during startup or class loading.
  53     // 2. pause: Pause the test to check accuracy of native memory tracking
  54     // 3. release: Release all malloc'd memory and check native memory tracking result.
  55     public enum TestPhase {
  56         alloc,
  57         pause,
  58         release
  59     };
  60 
  61     static TestPhase phase = TestPhase.alloc;
  62 
  63     // malloc'd memory
  64     static ArrayList<MallocMemory>  mallocd_memory = new ArrayList<MallocMemory>();
  65     static long                     mallocd_total  = 0;
  66     static WhiteBox                 whiteBox;
  67     static AtomicInteger            pause_count = new AtomicInteger();
  68 
  69     static boolean                  is_64_bit_system;
  70 
  71     private static boolean is_64_bit_system() { return is_64_bit_system; }
  72 
  73     public static void main(String args[]) throws Exception {
  74         is_64_bit_system = (Platform.is64bit());
  75 
  76         OutputAnalyzer output;
  77         whiteBox = WhiteBox.getWhiteBox();
  78 
  79         // Grab my own PID
  80         String pid = Long.toString(ProcessTools.getProcessId());
  81         ProcessBuilder pb = new ProcessBuilder();
  82 
  83         AllocThread[]   alloc_threads = new AllocThread[256];
  84         ReleaseThread[] release_threads = new ReleaseThread[64];
  85 
  86         int index;
  87         // Create many allocation threads
  88         for (index = 0; index < alloc_threads.length; index ++) {
  89             alloc_threads[index] = new AllocThread();
  90         }
  91 
  92         // Fewer release threads
  93         for (index = 0; index < release_threads.length; index ++) {
  94             release_threads[index] = new ReleaseThread();
  95         }
  96 
  97         if (is_64_bit_system()) {
  98             sleep_wait(2*60*1000);
  99         } else {
 100             sleep_wait(60*1000);
 101         }
 102         // pause the stress test
 103         phase = TestPhase.pause;
 104         while (pause_count.intValue() <  alloc_threads.length + release_threads.length) {
 105             sleep_wait(10);
 106         }
 107 
 108         long mallocd_total_in_KB = (mallocd_total + K / 2) / K;
 109 
 110         // Now check if the result from NMT matches the total memory allocated.
 111         String expected_test_summary = "Test (reserved=" + mallocd_total_in_KB +"KB, committed=" + mallocd_total_in_KB + "KB)";
 112         // Run 'jcmd <pid> VM.native_memory summary'
 113         pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "summary"});
 114         output = new OutputAnalyzer(pb.start());
 115         output.shouldContain(expected_test_summary);
 116 
 117         // Release all allocated memory
 118         phase = TestPhase.release;
 119         synchronized(mallocd_memory) {
 120             mallocd_memory.notifyAll();
 121         }
 122 
 123         // Join all threads
 124         for (index = 0; index < alloc_threads.length; index ++) {
 125             try {
 126                 alloc_threads[index].join();
 127             } catch (InterruptedException e) {
 128             }
 129         }
 130 
 131         for (index = 0; index < release_threads.length; index ++) {
 132             try {
 133                 release_threads[index].join();
 134             } catch (InterruptedException e) {
 135             }
 136         }
 137 
 138         // All test memory allocated should be released
 139         output = new OutputAnalyzer(pb.start());
 140         output.shouldNotContain("Test (reserved=");
 141 
 142         // Verify that tracking level has not been downgraded
 143         pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "statistics"});
 144         output = new OutputAnalyzer(pb.start());
 145         output.shouldNotContain("Tracking level has been downgraded due to lack of resources");
 146     }
 147 
 148     private static void sleep_wait(int n) {
 149         try {
 150             Thread.sleep(n);
 151         } catch (InterruptedException e) {
 152         }
 153     }
 154 
 155 
 156     static class MallocMemory {
 157         private long  addr;
 158         private int   size;
 159 
 160         MallocMemory(long addr, int size) {
 161             this.addr = addr;
 162             this.size = size;
 163         }
 164 
 165         long addr()  { return this.addr; }
 166         int  size()  { return this.size; }
 167     }
 168 
 169     static class AllocThread extends Thread {
 170         AllocThread() {
 171             this.setName("MallocThread");
 172             this.start();
 173         }
 174 
 175         // AllocThread only runs "Alloc" phase
 176         public void run() {
 177             Random random = new Random();
 178             while (MallocStressTest.phase == TestPhase.alloc) {
 179                 int r = Math.abs(random.nextInt());
 180                 // Only malloc small amount to avoid OOM
 181                 int size = r % 32;
 182                 if (is_64_bit_system()) {
 183                     r = r % 32 * K;
 184                 } else {
 185                     r = r % 64;
 186                 }
 187                 if (size == 0) size = 1;
 188                 long addr = MallocStressTest.whiteBox.NMTMallocWithPseudoStack(size, r);
 189                 if (addr != 0) {
 190                     MallocMemory mem = new MallocMemory(addr, size);
 191                     synchronized(MallocStressTest.mallocd_memory) {
 192                         MallocStressTest.mallocd_memory.add(mem);
 193                         MallocStressTest.mallocd_total += size;
 194                     }
 195                 } else {
 196                     System.out.println("Out of malloc memory");
 197                     break;
 198                 }
 199             }
 200             MallocStressTest.pause_count.incrementAndGet();
 201         }
 202     }
 203 
 204     static class ReleaseThread extends Thread {
 205         private Random random = new Random();
 206         ReleaseThread() {
 207             this.setName("ReleaseThread");
 208             this.start();
 209         }
 210 
 211         public void run() {
 212             while(true) {
 213                 switch(MallocStressTest.phase) {
 214                 case alloc:
 215                     slow_release();
 216                     break;
 217                 case pause:
 218                     enter_pause();
 219                     break;
 220                 case release:
 221                     quick_release();
 222                     return;
 223                 }
 224             }
 225         }
 226 
 227         private void enter_pause() {
 228             MallocStressTest.pause_count.incrementAndGet();
 229             while (MallocStressTest.phase != MallocStressTest.TestPhase.release) {
 230                 try {
 231                     synchronized(MallocStressTest.mallocd_memory) {
 232                         MallocStressTest.mallocd_memory.wait(10);
 233                     }
 234                 } catch (InterruptedException e) {
 235                 }
 236             }
 237         }
 238 
 239         private void quick_release() {
 240             List<MallocMemory> free_list;
 241             while (true) {
 242                 synchronized(MallocStressTest.mallocd_memory) {
 243                     if (MallocStressTest.mallocd_memory.isEmpty()) return;
 244                     int size =  Math.min(MallocStressTest.mallocd_memory.size(), 5000);
 245                     List<MallocMemory> subList = MallocStressTest.mallocd_memory.subList(0, size);
 246                     free_list = new ArrayList<MallocMemory>(subList);
 247                     subList.clear();
 248                 }
 249                 for (int index = 0; index < free_list.size(); index ++) {
 250                     MallocMemory mem = free_list.get(index);
 251                     MallocStressTest.whiteBox.NMTFree(mem.addr());
 252                 }
 253             }
 254         }
 255 
 256         private void slow_release() {
 257             try {
 258                 Thread.sleep(10);
 259             } catch (InterruptedException e) {
 260             }
 261             synchronized(MallocStressTest.mallocd_memory) {
 262                 if (MallocStressTest.mallocd_memory.isEmpty()) return;
 263                 int n = Math.abs(random.nextInt()) % MallocStressTest.mallocd_memory.size();
 264                 MallocMemory mem = mallocd_memory.remove(n);
 265                 MallocStressTest.whiteBox.NMTFree(mem.addr());
 266                 MallocStressTest.mallocd_total -= mem.size();
 267             }
 268         }
 269     }
 270 }