1 /*
   2  * Copyright (c) 2000, 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.  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 java.nio;
  27 
  28 import java.io.FileDescriptor;
  29 import java.lang.ref.Reference;
  30 import jdk.internal.misc.Unsafe;
  31 
  32 
  33 /**
  34  * A direct byte buffer whose content is a memory-mapped region of a file.
  35  *
  36  * <p> Mapped byte buffers are created via the {@link
  37  * java.nio.channels.FileChannel#map FileChannel.map} method.  This class
  38  * extends the {@link ByteBuffer} class with operations that are specific to
  39  * memory-mapped file regions.
  40  *
  41  * <p> A mapped byte buffer and the file mapping that it represents remain
  42  * valid until the buffer itself is garbage-collected.
  43  *
  44  * <p> The content of a mapped byte buffer can change at any time, for example
  45  * if the content of the corresponding region of the mapped file is changed by
  46  * this program or another.  Whether or not such changes occur, and when they
  47  * occur, is operating-system dependent and therefore unspecified.
  48  *
  49  * <a id="inaccess"></a><p> All or part of a mapped byte buffer may become
  50  * inaccessible at any time, for example if the mapped file is truncated.  An
  51  * attempt to access an inaccessible region of a mapped byte buffer will not
  52  * change the buffer's content and will cause an unspecified exception to be
  53  * thrown either at the time of the access or at some later time.  It is
  54  * therefore strongly recommended that appropriate precautions be taken to
  55  * avoid the manipulation of a mapped file by this program, or by a
  56  * concurrently running program, except to read or write the file's content.
  57  *
  58  * <p> Mapped byte buffers otherwise behave no differently than ordinary direct
  59  * byte buffers. </p>
  60  *
  61  *
  62  * @author Mark Reinhold
  63  * @author JSR-51 Expert Group
  64  * @since 1.4
  65  */
  66 
  67 public abstract class MappedByteBuffer
  68     extends ByteBuffer
  69 {
  70 
  71     // This is a little bit backwards: By rights MappedByteBuffer should be a
  72     // subclass of DirectByteBuffer, but to keep the spec clear and simple, and
  73     // for optimization purposes, it's easier to do it the other way around.
  74     // This works because DirectByteBuffer is a package-private class.
  75 
  76     // For mapped buffers, a FileDescriptor that may be used for mapping
  77     // operations if valid; null if the buffer is not mapped.
  78     private final FileDescriptor fd;
  79 
  80     // A flag true if this buffer is mapped against persistent memory
  81     // via a call to FileChannel.map_persistent and false if it is
  82     // some other sort of file mapped via a call to FileChannel.map.
  83     // this flag only determines the behaviour of force operations.
  84     private final boolean isPersistent;
  85     
  86     // This should only be invoked by the DirectByteBuffer constructors
  87     //
  88     MappedByteBuffer(int mark, int pos, int lim, int cap, // package-private
  89                      FileDescriptor fd, boolean isPersistent) {
  90         super(mark, pos, lim, cap);
  91         this.fd = fd;
  92         this.isPersistent = isPersistent;
  93     }
  94 
  95     MappedByteBuffer(int mark, int pos, int lim, int cap, // package-private
  96                      boolean isPersistent) {
  97         super(mark, pos, lim, cap);
  98         this.fd = null;
  99         this.isPersistent = isPersistent;
 100     }
 101 
 102     MappedByteBuffer(int mark, int pos, int lim, int cap) { // package-private
 103         super(mark, pos, lim, cap);
 104         this.fd = null;
 105         this.isPersistent = false;
 106     }
 107 
 108     // Returns the distance (in bytes) of the buffer from the page aligned address
 109     // of the mapping. Computed each time to avoid storing in every direct buffer.
 110     private long mappingOffset() {
 111         int ps = Bits.pageSize();
 112         long offset = address % ps;
 113         return (offset >= 0) ? offset : (ps + offset);
 114     }
 115 
 116     private long mappingAddress(long mappingOffset) {
 117         return address - mappingOffset;
 118     }
 119 
 120     private long mappingLength(long mappingOffset) {
 121         return (long)capacity() + mappingOffset;
 122     }
 123 
 124     /**
 125      * Tells whether this buffer was mapped against persistent memory
 126      * by calling {@link java.nio.channels.FileChannel#map_persistent
 127      * FileChannel.map_persistent} or mapped against some other form
 128      * of device file using {@link java.nio.channels.FileChannel#map
 129      * FileChannel.map}.
 130      *
 131      * @return true if the file was mapped using {@link
 132      * java.nio.channels.FileChannel#map_persistent
 133      * FileChannel.map_persistent} otherwise false.
 134      */
 135     public boolean isPersistent() {
 136         return isPersistent;
 137     }
 138     
 139     /**
 140      * Tells whether or not this buffer's content is resident in physical
 141      * memory.
 142      *
 143      * <p> A return value of {@code true} implies that it is highly likely
 144      * that all of the data in this buffer is resident in physical memory and
 145      * may therefore be accessed without incurring any virtual-memory page
 146      * faults or I/O operations.  A return value of {@code false} does not
 147      * necessarily imply that the buffer's content is not resident in physical
 148      * memory.
 149      *
 150      * <p> The returned value is a hint, rather than a guarantee, because the
 151      * underlying operating system may have paged out some of the buffer's data
 152      * by the time that an invocation of this method returns.  </p>
 153      *
 154      * @return  {@code true} if it is likely that this buffer's content
 155      *          is resident in physical memory
 156      */
 157     public final boolean isLoaded() {
 158         if (fd == null) {
 159             return true;
 160         }
 161         // a persistent mapped buffer is always loaded
 162         if (isPersistent()) {
 163             return true;
 164         }
 165         if ((address == 0) || (capacity() == 0))
 166             return true;
 167         long offset = mappingOffset();
 168         long length = mappingLength(offset);
 169         return isLoaded0(mappingAddress(offset), length, Bits.pageCount(length));
 170     }
 171 
 172     // not used, but a potential target for a store, see load() for details.
 173     private static byte unused;
 174 
 175     /**
 176      * Loads this buffer's content into physical memory.
 177      *
 178      * <p> This method makes a best effort to ensure that, when it returns,
 179      * this buffer's content is resident in physical memory.  Invoking this
 180      * method may cause some number of page faults and I/O operations to
 181      * occur. </p>
 182      *
 183      * @return  This buffer
 184      */
 185     public final MappedByteBuffer load() {
 186         if (fd == null) {
 187             return this;
 188         }
 189         // no need to load a persistent mapped buffer
 190         if (isPersistent()) {
 191             return this;
 192         }
 193         if ((address == 0) || (capacity() == 0))
 194             return this;
 195         long offset = mappingOffset();
 196         long length = mappingLength(offset);
 197         load0(mappingAddress(offset), length);
 198 
 199         // Read a byte from each page to bring it into memory. A checksum
 200         // is computed as we go along to prevent the compiler from otherwise
 201         // considering the loop as dead code.
 202         Unsafe unsafe = Unsafe.getUnsafe();
 203         int ps = Bits.pageSize();
 204         int count = Bits.pageCount(length);
 205         long a = mappingAddress(offset);
 206         byte x = 0;
 207         try {
 208             for (int i=0; i<count; i++) {
 209                 // TODO consider changing to getByteOpaque thus avoiding
 210                 // dead code elimination and the need to calculate a checksum
 211                 x ^= unsafe.getByte(a);
 212                 a += ps;
 213             }
 214         } finally {
 215             Reference.reachabilityFence(this);
 216         }
 217         if (unused != 0)
 218             unused = x;
 219 
 220         return this;
 221     }
 222 
 223     /**
 224      * Forces any changes made to this buffer's content to be written to the
 225      * storage device containing the mapped file.
 226      *
 227      * <p> If the file mapped into this buffer resides on a local storage
 228      * device then when this method returns it is guaranteed that all changes
 229      * made to the buffer since it was created, or since this method was last
 230      * invoked, will have been written to that device.
 231      *
 232      * <p> If the file does not reside on a local device then no such guarantee
 233      * is made.
 234      *
 235      * <p> If this buffer was not mapped in read/write mode ({@link
 236      * java.nio.channels.FileChannel.MapMode#READ_WRITE}) then invoking this
 237      * method has no effect. </p>
 238      *
 239      * @return  This buffer
 240      */
 241     public final MappedByteBuffer force() {
 242         return force(0, capacity());
 243     }
 244 
 245     /**
 246      * Forces any changes made to some subregion of this buffer's
 247      * content to be written to the storage device containing the
 248      * mapped file.
 249      *
 250      * <p> If the file mapped into this buffer resides on a local storage
 251      * device then when this method returns it is guaranteed that all changes
 252      * made to the buffer since it was created, or since this method was last
 253      * invoked, will have been written to that device.
 254      *
 255      * <p> If the file does not reside on a local device then no such guarantee
 256      * is made.
 257      *
 258      * <p> If this buffer was not mapped in read/write mode ({@link
 259      * java.nio.channels.FileChannel.MapMode#READ_WRITE}) then invoking this
 260      * method has no effect. </p>
 261      *
 262      * @param from
 263      *        The offset to the first byte in the buffer subregion
 264      *        that is to be written back to storage
 265      *
 266      * @param to
 267      *        The offset to the first byte beyond the buffer subregion
 268      *        that is to be written back to storage
 269      *
 270      * @return  This buffer
 271      */
 272     public final MappedByteBuffer force(long from, long to) {
 273         if (fd == null) {
 274             return this;
 275         }
 276         if ((address != 0) && (capacity() != 0)) {
 277             // check inputs
 278             if (from < 0 || from >= capacity()) {
 279                 throw new IllegalArgumentException();
 280             }
 281             if (to < from || to > capacity()) {
 282                 throw new IllegalArgumentException();
 283             }
 284             
 285             long offset = mappingOffset();
 286             long a = mappingAddress(offset) + from;
 287             long length = offset + to;
 288             if (isPersistent) {
 289                 // simply force writeback of associated cache lines
 290                 Unsafe unsafe = Unsafe.getUnsafe();
 291                 unsafe.writebackMemory(a, length);
 292             } else {
 293                 // writeback using device associated with fd
 294                 force0(fd, a, length);
 295             }
 296         }
 297         return this;
 298     }
 299 
 300     private native boolean isLoaded0(long address, long length, int pageCount);
 301     private native void load0(long address, long length);
 302     private native void force0(FileDescriptor fd, long address, long length);
 303 
 304     // -- Covariant return type overrides
 305 
 306     /**
 307      * {@inheritDoc}
 308      */
 309     @Override
 310     public final MappedByteBuffer position(int newPosition) {
 311         super.position(newPosition);
 312         return this;
 313     }
 314 
 315     /**
 316      * {@inheritDoc}
 317      */
 318     @Override
 319     public final MappedByteBuffer limit(int newLimit) {
 320         super.limit(newLimit);
 321         return this;
 322     }
 323 
 324     /**
 325      * {@inheritDoc}
 326      */
 327     @Override
 328     public final MappedByteBuffer mark() {
 329         super.mark();
 330         return this;
 331     }
 332 
 333     /**
 334      * {@inheritDoc}
 335      */
 336     @Override
 337     public final MappedByteBuffer reset() {
 338         super.reset();
 339         return this;
 340     }
 341 
 342     /**
 343      * {@inheritDoc}
 344      */
 345     @Override
 346     public final MappedByteBuffer clear() {
 347         super.clear();
 348         return this;
 349     }
 350 
 351     /**
 352      * {@inheritDoc}
 353      */
 354     @Override
 355     public final MappedByteBuffer flip() {
 356         super.flip();
 357         return this;
 358     }
 359 
 360     /**
 361      * {@inheritDoc}
 362      */
 363     @Override
 364     public final MappedByteBuffer rewind() {
 365         super.rewind();
 366         return this;
 367     }
 368 }