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