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     // using one of the persistent FileChannel.MapMode modes,
  82     // MapMode.READ_ONLY_PERSISTENT or MapMode.READ_WRITE_PERSISTENT
  83     // and false if it is mapped using any of other modes. this flag
  84     // only determines the behaviour of force operations.
  85     private final boolean isPersistent;
  86     
  87     // This should only be invoked by the DirectByteBuffer constructors
  88     //
  89     MappedByteBuffer(int mark, int pos, int lim, int cap, // package-private
  90                      FileDescriptor fd, boolean isPersistent) {
  91         super(mark, pos, lim, cap);
  92         this.fd = fd;
  93         this.isPersistent = isPersistent;
  94     }
  95 
  96     MappedByteBuffer(int mark, int pos, int lim, int cap, // package-private
  97                      boolean isPersistent) {
  98         super(mark, pos, lim, cap);
  99         this.fd = null;
 100         this.isPersistent = isPersistent;
 101     }
 102 
 103     MappedByteBuffer(int mark, int pos, int lim, int cap) { // package-private
 104         super(mark, pos, lim, cap);
 105         this.fd = null;
 106         this.isPersistent = false;
 107     }
 108 
 109     // Returns the distance (in bytes) of the buffer from the page aligned address
 110     // of the mapping. Computed each time to avoid storing in every direct buffer.
 111     private long mappingOffset() {
 112         int ps = Bits.pageSize();
 113         long offset = address % ps;
 114         return (offset >= 0) ? offset : (ps + offset);
 115     }
 116 
 117     private long mappingAddress(long mappingOffset) {
 118         return address - mappingOffset;
 119     }
 120 
 121     private long mappingLength(long mappingOffset) {
 122         return (long)capacity() + mappingOffset;
 123     }
 124 
 125     /**
 126      * Tells whether this buffer was mapped against a non-volatile
 127      * memory device by passing one of the persistent map modes {@link
 128      * java.nio.channels.FileChannel.MapMode#READ_ONLY_PERSISTENT
 129      * MapMode#READ_ONLY_PERSISTENT} or {@link
 130      * java.nio.channels.FileChannel.MapMode#READ_ONLY_PERSISTENT
 131      * MapMode#READ_WRITE_PERSISTENT} in the call to {@link
 132      * java.nio.channels.FileChannel#map FileChannel.map} or mapped
 133      * against some other form of device file by pasing one of the
 134      * other map modes.
 135      *
 136      * @return true if the file was mapped using against a
 137      * non-volatile memory device by passing one of the persistent map
 138      * modes {@link
 139      * java.nio.channels.FileChannel.MapMode#READ_ONLY_PERSISTENT
 140      * MapMode#READ_ONLY_PERSISTENT} or {@link
 141      * java.nio.channels.FileChannel.MapMode#READ_ONLY_PERSISTENT
 142      * MapMode#READ_WRITE_PERSISTENT} in the call to {@link
 143      * java.nio.channels.FileChannel#map FileChannel.map} otherwise
 144      * false.
 145      */
 146     public boolean isPersistent() {
 147         return isPersistent;
 148     }
 149     
 150     /**
 151      * Tells whether or not this buffer's content is resident in physical
 152      * memory.
 153      *
 154      * <p> A return value of {@code true} implies that it is highly likely
 155      * that all of the data in this buffer is resident in physical memory and
 156      * may therefore be accessed without incurring any virtual-memory page
 157      * faults or I/O operations.  A return value of {@code false} does not
 158      * necessarily imply that the buffer's content is not resident in physical
 159      * memory.
 160      *
 161      * <p> The returned value is a hint, rather than a guarantee, because the
 162      * underlying operating system may have paged out some of the buffer's data
 163      * by the time that an invocation of this method returns.  </p>
 164      *
 165      * @return  {@code true} if it is likely that this buffer's content
 166      *          is resident in physical memory
 167      */
 168     public final boolean isLoaded() {
 169         if (fd == null) {
 170             return true;
 171         }
 172         // a persistent mapped buffer is always loaded
 173         if (isPersistent()) {
 174             return true;
 175         }
 176         if ((address == 0) || (capacity() == 0))
 177             return true;
 178         long offset = mappingOffset();
 179         long length = mappingLength(offset);
 180         return isLoaded0(mappingAddress(offset), length, Bits.pageCount(length));
 181     }
 182 
 183     // not used, but a potential target for a store, see load() for details.
 184     private static byte unused;
 185 
 186     /**
 187      * Loads this buffer's content into physical memory.
 188      *
 189      * <p> This method makes a best effort to ensure that, when it returns,
 190      * this buffer's content is resident in physical memory.  Invoking this
 191      * method may cause some number of page faults and I/O operations to
 192      * occur. </p>
 193      *
 194      * @return  This buffer
 195      */
 196     public final MappedByteBuffer load() {
 197         if (fd == null) {
 198             return this;
 199         }
 200         // no need to load a persistent mapped buffer
 201         if (isPersistent()) {
 202             return this;
 203         }
 204         if ((address == 0) || (capacity() == 0))
 205             return this;
 206         long offset = mappingOffset();
 207         long length = mappingLength(offset);
 208         load0(mappingAddress(offset), length);
 209 
 210         // Read a byte from each page to bring it into memory. A checksum
 211         // is computed as we go along to prevent the compiler from otherwise
 212         // considering the loop as dead code.
 213         Unsafe unsafe = Unsafe.getUnsafe();
 214         int ps = Bits.pageSize();
 215         int count = Bits.pageCount(length);
 216         long a = mappingAddress(offset);
 217         byte x = 0;
 218         try {
 219             for (int i=0; i<count; i++) {
 220                 // TODO consider changing to getByteOpaque thus avoiding
 221                 // dead code elimination and the need to calculate a checksum
 222                 x ^= unsafe.getByte(a);
 223                 a += ps;
 224             }
 225         } finally {
 226             Reference.reachabilityFence(this);
 227         }
 228         if (unused != 0)
 229             unused = x;
 230 
 231         return this;
 232     }
 233 
 234     /**
 235      * Forces any changes made to this buffer's content to be written to the
 236      * storage device containing the mapped file.
 237      *
 238      * <p> If the file mapped into this buffer resides on a local storage
 239      * device then when this method returns it is guaranteed that all changes
 240      * made to the buffer since it was created, or since this method was last
 241      * invoked, will have been written to that device.
 242      *
 243      * <p> If the file does not reside on a local device then no such guarantee
 244      * is made.
 245      *
 246      * <p> If this buffer was not mapped in read/write mode ({@link
 247      * java.nio.channels.FileChannel.MapMode#READ_WRITE}) then invoking this
 248      * method has no effect. </p>
 249      *
 250      * @return  This buffer
 251      */
 252     public final MappedByteBuffer force() {
 253         return force(0, capacity());
 254     }
 255 
 256     /**
 257      * Forces any changes made to some region of this buffer's content
 258      * to be written to the storage device containing the mapped file.
 259      *
 260      * <p> If the file mapped into this buffer resides on a local storage
 261      * device then when this method returns it is guaranteed that all changes
 262      * made to the buffer since it was created, or since this method was last
 263      * invoked, will have been written to that device.
 264      *
 265      * <p> If the file does not reside on a local device then no such guarantee
 266      * is made.
 267      *
 268      * <p> If this buffer was not mapped in read/write mode ({@link
 269      * java.nio.channels.FileChannel.MapMode#READ_WRITE}) then invoking this
 270      * method has no effect. </p>
 271      *
 272      * @param from
 273      *        The offset to the first byte in the buffer region that
 274      *        is to be written back to storage
 275      *
 276      * @param to
 277      *        The offset to the first byte beyond the buffer region
 278      *        that is to be written back to storage
 279      *
 280      * @return  This buffer
 281      *
 282      * @since 12
 283      */
 284     public final MappedByteBuffer force(long from, long to) {
 285         if (fd == null) {
 286             return this;
 287         }
 288         if ((address != 0) && (capacity() != 0)) {
 289             // check inputs
 290             if (from < 0 || from >= capacity()) {
 291                 throw new IllegalArgumentException();
 292             }
 293             if (to < from || to > capacity()) {
 294                 throw new IllegalArgumentException();
 295             }
 296             
 297             long offset = mappingOffset();
 298             long a = mappingAddress(offset) + from;
 299             long length = to - from;
 300             if (isPersistent) {
 301                 // simply force writeback of associated cache lines
 302                 Unsafe unsafe = Unsafe.getUnsafe();
 303                 unsafe.writebackMemory(a, length);
 304             } else {
 305                 // writeback using device associated with fd
 306                 force0(fd, a, length);
 307             }
 308         }
 309         return this;
 310     }
 311 
 312     private native boolean isLoaded0(long address, long length, int pageCount);
 313     private native void load0(long address, long length);
 314     private native void force0(FileDescriptor fd, long address, long length);
 315 
 316     // -- Covariant return type overrides
 317 
 318     /**
 319      * {@inheritDoc}
 320      */
 321     @Override
 322     public final MappedByteBuffer position(int newPosition) {
 323         super.position(newPosition);
 324         return this;
 325     }
 326 
 327     /**
 328      * {@inheritDoc}
 329      */
 330     @Override
 331     public final MappedByteBuffer limit(int newLimit) {
 332         super.limit(newLimit);
 333         return this;
 334     }
 335 
 336     /**
 337      * {@inheritDoc}
 338      */
 339     @Override
 340     public final MappedByteBuffer mark() {
 341         super.mark();
 342         return this;
 343     }
 344 
 345     /**
 346      * {@inheritDoc}
 347      */
 348     @Override
 349     public final MappedByteBuffer reset() {
 350         super.reset();
 351         return this;
 352     }
 353 
 354     /**
 355      * {@inheritDoc}
 356      */
 357     @Override
 358     public final MappedByteBuffer clear() {
 359         super.clear();
 360         return this;
 361     }
 362 
 363     /**
 364      * {@inheritDoc}
 365      */
 366     @Override
 367     public final MappedByteBuffer flip() {
 368         super.flip();
 369         return this;
 370     }
 371 
 372     /**
 373      * {@inheritDoc}
 374      */
 375     @Override
 376     public final MappedByteBuffer rewind() {
 377         super.rewind();
 378         return this;
 379     }
 380 }