1 /* 2 * Copyright (c) 2000, 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. 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 sun.nio.ch; 27 28 import java.lang.reflect.*; 29 import java.io.FileDescriptor; 30 import java.nio.ByteBuffer; 31 import java.nio.MappedByteBuffer; 32 import java.security.AccessController; 33 import java.security.PrivilegedAction; 34 import java.util.*; 35 import jdk.internal.misc.Unsafe; 36 import sun.security.action.GetPropertyAction; 37 38 39 public class Util { 40 41 // -- Caches -- 42 43 // The number of temp buffers in our pool 44 private static final int TEMP_BUF_POOL_SIZE = IOUtil.IOV_MAX; 45 46 // The max size allowed for a cached temp buffer, in bytes 47 private static final long MAX_CACHED_BUFFER_SIZE = getMaxCachedBufferSize(); 48 49 // Per-thread cache of temporary direct buffers 50 private static ThreadLocal<BufferCache> bufferCache = 51 new ThreadLocal<BufferCache>() 52 { 53 @Override 54 protected BufferCache initialValue() { 55 return new BufferCache(); 56 } 57 }; 58 59 /** 60 * Returns the max size allowed for a cached temp buffers, in 61 * bytes. It defaults to Long.MAX_VALUE. It can be set with the 62 * jdk.nio.maxCachedBufferSize property. Even though 63 * ByteBuffer.capacity() returns an int, we're using a long here 64 * for potential future-proofing. 65 */ 66 private static long getMaxCachedBufferSize() { 67 String s = java.security.AccessController.doPrivileged( 68 new PrivilegedAction<String>() { 69 @Override 70 public String run() { 71 return System.getProperty("jdk.nio.maxCachedBufferSize"); 72 } 73 }); 74 if (s != null) { 75 try { 76 long m = Long.parseLong(s); 77 if (m >= 0) { 78 return m; 79 } else { 80 // if it's negative, ignore the system property 81 } 82 } catch (NumberFormatException e) { 83 // if the string is not well formed, ignore the system property 84 } 85 } 86 return Long.MAX_VALUE; 87 } 88 89 /** 90 * Returns true if a buffer of this size is too large to be 91 * added to the buffer cache, false otherwise. 92 */ 93 private static boolean isBufferTooLarge(int size) { 94 return size > MAX_CACHED_BUFFER_SIZE; 95 } 96 97 /** 98 * Returns true if the buffer is too large to be added to the 99 * buffer cache, false otherwise. 100 */ 101 private static boolean isBufferTooLarge(ByteBuffer buf) { 102 return isBufferTooLarge(buf.capacity()); 103 } 104 105 /** 106 * A simple cache of direct buffers. 107 */ 108 private static class BufferCache { 109 // the array of buffers 110 private ByteBuffer[] buffers; 111 112 // the number of buffers in the cache 113 private int count; 114 115 // the index of the first valid buffer (undefined if count == 0) 116 private int start; 117 118 private int next(int i) { 119 return (i + 1) % TEMP_BUF_POOL_SIZE; 120 } 121 122 BufferCache() { 123 buffers = new ByteBuffer[TEMP_BUF_POOL_SIZE]; 124 } 125 126 /** 127 * Removes and returns a buffer from the cache of at least the given 128 * size (or null if no suitable buffer is found). 129 */ 130 ByteBuffer get(int size) { 131 // Don't call this if the buffer would be too large. 132 assert !isBufferTooLarge(size); 133 134 if (count == 0) 135 return null; // cache is empty 136 137 ByteBuffer[] buffers = this.buffers; 138 139 // search for suitable buffer (often the first buffer will do) 140 ByteBuffer buf = buffers[start]; 141 if (buf.capacity() < size) { 142 buf = null; 143 int i = start; 144 while ((i = next(i)) != start) { 145 ByteBuffer bb = buffers[i]; 146 if (bb == null) 147 break; 148 if (bb.capacity() >= size) { 149 buf = bb; 150 break; 151 } 152 } 153 if (buf == null) 154 return null; 155 // move first element to here to avoid re-packing 156 buffers[i] = buffers[start]; 157 } 158 159 // remove first element 160 buffers[start] = null; 161 start = next(start); 162 count--; 163 164 // prepare the buffer and return it 165 buf.rewind(); 166 buf.limit(size); 167 return buf; 168 } 169 170 boolean offerFirst(ByteBuffer buf) { 171 // Don't call this if the buffer is too large. 172 assert !isBufferTooLarge(buf); 173 174 if (count >= TEMP_BUF_POOL_SIZE) { 175 return false; 176 } else { 177 start = (start + TEMP_BUF_POOL_SIZE - 1) % TEMP_BUF_POOL_SIZE; 178 buffers[start] = buf; 179 count++; 180 return true; 181 } 182 } 183 184 boolean offerLast(ByteBuffer buf) { 185 // Don't call this if the buffer is too large. 186 assert !isBufferTooLarge(buf); 187 188 if (count >= TEMP_BUF_POOL_SIZE) { 189 return false; 190 } else { 191 int next = (start + count) % TEMP_BUF_POOL_SIZE; 192 buffers[next] = buf; 193 count++; 194 return true; 195 } 196 } 197 198 boolean isEmpty() { 199 return count == 0; 200 } 201 202 ByteBuffer removeFirst() { 203 assert count > 0; 204 ByteBuffer buf = buffers[start]; 205 buffers[start] = null; 206 start = next(start); 207 count--; 208 return buf; 209 } 210 } 211 212 /** 213 * Returns a temporary buffer of at least the given size 214 */ 215 public static ByteBuffer getTemporaryDirectBuffer(int size) { 216 // If a buffer of this size is too large for the cache, there 217 // should not be a buffer in the cache that is at least as 218 // large. So we'll just create a new one. Also, we don't have 219 // to remove the buffer from the cache (as this method does 220 // below) given that we won't put the new buffer in the cache. 221 if (isBufferTooLarge(size)) { 222 return ByteBuffer.allocateDirect(size); 223 } 224 225 BufferCache cache = bufferCache.get(); 226 ByteBuffer buf = cache.get(size); 227 if (buf != null) { 228 return buf; 229 } else { 230 // No suitable buffer in the cache so we need to allocate a new 231 // one. To avoid the cache growing then we remove the first 232 // buffer from the cache and free it. 233 if (!cache.isEmpty()) { 234 buf = cache.removeFirst(); 235 free(buf); 236 } 237 return ByteBuffer.allocateDirect(size); 238 } 239 } 240 241 /** 242 * Releases a temporary buffer by returning to the cache or freeing it. 243 */ 244 public static void releaseTemporaryDirectBuffer(ByteBuffer buf) { 245 offerFirstTemporaryDirectBuffer(buf); 246 } 247 248 /** 249 * Releases a temporary buffer by returning to the cache or freeing it. If 250 * returning to the cache then insert it at the start so that it is 251 * likely to be returned by a subsequent call to getTemporaryDirectBuffer. 252 */ 253 static void offerFirstTemporaryDirectBuffer(ByteBuffer buf) { 254 // If the buffer is too large for the cache we don't have to 255 // check the cache. We'll just free it. 256 if (isBufferTooLarge(buf)) { 257 free(buf); 258 return; 259 } 260 261 assert buf != null; 262 BufferCache cache = bufferCache.get(); 263 if (!cache.offerFirst(buf)) { 264 // cache is full 265 free(buf); 266 } 267 } 268 269 /** 270 * Releases a temporary buffer by returning to the cache or freeing it. If 271 * returning to the cache then insert it at the end. This makes it 272 * suitable for scatter/gather operations where the buffers are returned to 273 * cache in same order that they were obtained. 274 */ 275 static void offerLastTemporaryDirectBuffer(ByteBuffer buf) { 276 // If the buffer is too large for the cache we don't have to 277 // check the cache. We'll just free it. 278 if (isBufferTooLarge(buf)) { 279 free(buf); 280 return; 281 } 282 283 assert buf != null; 284 BufferCache cache = bufferCache.get(); 285 if (!cache.offerLast(buf)) { 286 // cache is full 287 free(buf); 288 } 289 } 290 291 /** 292 * Frees the memory for the given direct buffer 293 */ 294 private static void free(ByteBuffer buf) { 295 ((DirectBuffer)buf).cleaner().clean(); 296 } 297 298 299 // -- Random stuff -- 300 301 static ByteBuffer[] subsequence(ByteBuffer[] bs, int offset, int length) { 302 if ((offset == 0) && (length == bs.length)) 303 return bs; 304 int n = length; 305 ByteBuffer[] bs2 = new ByteBuffer[n]; 306 for (int i = 0; i < n; i++) 307 bs2[i] = bs[offset + i]; 308 return bs2; 309 } 310 311 static <E> Set<E> ungrowableSet(final Set<E> s) { 312 return new Set<E>() { 313 314 public int size() { return s.size(); } 315 public boolean isEmpty() { return s.isEmpty(); } 316 public boolean contains(Object o) { return s.contains(o); } 317 public Object[] toArray() { return s.toArray(); } 318 public <T> T[] toArray(T[] a) { return s.toArray(a); } 319 public String toString() { return s.toString(); } 320 public Iterator<E> iterator() { return s.iterator(); } 321 public boolean equals(Object o) { return s.equals(o); } 322 public int hashCode() { return s.hashCode(); } 323 public void clear() { s.clear(); } 324 public boolean remove(Object o) { return s.remove(o); } 325 326 public boolean containsAll(Collection<?> coll) { 327 return s.containsAll(coll); 328 } 329 public boolean removeAll(Collection<?> coll) { 330 return s.removeAll(coll); 331 } 332 public boolean retainAll(Collection<?> coll) { 333 return s.retainAll(coll); 334 } 335 336 public boolean add(E o){ 337 throw new UnsupportedOperationException(); 338 } 339 public boolean addAll(Collection<? extends E> coll) { 340 throw new UnsupportedOperationException(); 341 } 342 343 }; 344 } 345 346 347 // -- Unsafe access -- 348 349 private static Unsafe unsafe = Unsafe.getUnsafe(); 350 351 private static byte _get(long a) { 352 return unsafe.getByte(a); 353 } 354 355 private static void _put(long a, byte b) { 356 unsafe.putByte(a, b); 357 } 358 359 static void erase(ByteBuffer bb) { 360 unsafe.setMemory(((DirectBuffer)bb).address(), bb.capacity(), (byte)0); 361 } 362 363 static Unsafe unsafe() { 364 return unsafe; 365 } 366 367 private static int pageSize = -1; 368 369 static int pageSize() { 370 if (pageSize == -1) 371 pageSize = unsafe().pageSize(); 372 return pageSize; 373 } 374 375 private static volatile Constructor<?> directByteBufferConstructor; 376 377 private static void initDBBConstructor() { 378 AccessController.doPrivileged(new PrivilegedAction<Void>() { 379 public Void run() { 380 try { 381 Class<?> cl = Class.forName("java.nio.DirectByteBuffer"); 382 Constructor<?> ctor = cl.getDeclaredConstructor( 383 new Class<?>[] { int.class, 384 long.class, 385 FileDescriptor.class, 386 Runnable.class }); 387 ctor.setAccessible(true); 388 directByteBufferConstructor = ctor; 389 } catch (ClassNotFoundException | 390 NoSuchMethodException | 391 IllegalArgumentException | 392 ClassCastException x) { 393 throw new InternalError(x); 394 } 395 return null; 396 }}); 397 } 398 399 static MappedByteBuffer newMappedByteBuffer(int size, long addr, 400 FileDescriptor fd, 401 Runnable unmapper) 402 { 403 MappedByteBuffer dbb; 404 if (directByteBufferConstructor == null) 405 initDBBConstructor(); 406 try { 407 dbb = (MappedByteBuffer)directByteBufferConstructor.newInstance( 408 new Object[] { size, 409 addr, 410 fd, 411 unmapper }); 412 } catch (InstantiationException | 413 IllegalAccessException | 414 InvocationTargetException e) { 415 throw new InternalError(e); 416 } 417 return dbb; 418 } 419 420 private static volatile Constructor<?> directByteBufferRConstructor; 421 422 private static void initDBBRConstructor() { 423 AccessController.doPrivileged(new PrivilegedAction<Void>() { 424 public Void run() { 425 try { 426 Class<?> cl = Class.forName("java.nio.DirectByteBufferR"); 427 Constructor<?> ctor = cl.getDeclaredConstructor( 428 new Class<?>[] { int.class, 429 long.class, 430 FileDescriptor.class, 431 Runnable.class }); 432 ctor.setAccessible(true); 433 directByteBufferRConstructor = ctor; 434 } catch (ClassNotFoundException | 435 NoSuchMethodException | 436 IllegalArgumentException | 437 ClassCastException x) { 438 throw new InternalError(x); 439 } 440 return null; 441 }}); 442 } 443 444 static MappedByteBuffer newMappedByteBufferR(int size, long addr, 445 FileDescriptor fd, 446 Runnable unmapper) 447 { 448 MappedByteBuffer dbb; 449 if (directByteBufferRConstructor == null) 450 initDBBRConstructor(); 451 try { 452 dbb = (MappedByteBuffer)directByteBufferRConstructor.newInstance( 453 new Object[] { size, 454 addr, 455 fd, 456 unmapper }); 457 } catch (InstantiationException | 458 IllegalAccessException | 459 InvocationTargetException e) { 460 throw new InternalError(e); 461 } 462 return dbb; 463 } 464 465 466 // -- Bug compatibility -- 467 468 private static volatile String bugLevel; 469 470 static boolean atBugLevel(String bl) { // package-private 471 if (bugLevel == null) { 472 if (!jdk.internal.misc.VM.isBooted()) 473 return false; 474 String value = AccessController.doPrivileged( 475 new GetPropertyAction("sun.nio.ch.bugLevel")); 476 bugLevel = (value != null) ? value : ""; 477 } 478 return bugLevel.equals(bl); 479 } 480 481 }