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     // This should only be invoked by the DirectByteBuffer constructors
81     //
82     MappedByteBuffer(int mark, int pos, int lim, int cap, // package-private
83                      FileDescriptor fd)
84     {
85         super(mark, pos, lim, cap);
86         this.fd = fd;
87     }
88
89     MappedByteBuffer(int mark, int pos, int lim, int cap) { // package-private
90         super(mark, pos, lim, cap);
91         this.fd = null;
92     }
93
94     // Returns the distance (in bytes) of the buffer from the page aligned address
95     // of the mapping. Computed each time to avoid storing in every direct buffer.
96     private long mappingOffset() {
97         int ps = Bits.pageSize();
98         long offset = address % ps;
99         return (offset >= 0) ? offset : (ps + offset);
100     }
101
102     private long mappingAddress(long mappingOffset) {
103         return address - mappingOffset;
104     }
105
106     private long mappingLength(long mappingOffset) {
107         return (long)capacity() + mappingOffset;
108     }
109
110     /**
111      * Tells whether or not this buffer's content is resident in physical
112      * memory.
113      *
114      * <p> A return value of {@code true} implies that it is highly likely
115      * that all of the data in this buffer is resident in physical memory and
116      * may therefore be accessed without incurring any virtual-memory page
117      * faults or I/O operations.  A return value of {@code false} does not
118      * necessarily imply that the buffer's content is not resident in physical
119      * memory.
120      *
121      * <p> The returned value is a hint, rather than a guarantee, because the
122      * underlying operating system may have paged out some of the buffer's data
123      * by the time that an invocation of this method returns.  </p>
124      *
125      * @return  {@code trueif it is likely that this buffer's content
126      *          is resident in physical memory
127      */

128     public final boolean isLoaded() {
129         if (fd == null) {
130             return true;
131         }
132         if ((address == 0) || (capacity() == 0))
133             return true;
134         long offset = mappingOffset();
135         long length = mappingLength(offset);
136         return isLoaded0(mappingAddress(offset), length, Bits.pageCount(length));
137     }
138
139     // not used, but a potential target for a store, see load() for details.
140     private static byte unused;
141
142     /**
143      * Loads this buffer's content into physical memory.
144      *
145      * <p> This method makes a best effort to ensure that, when it returns,
146      * this buffer's content is resident in physical memory.  Invoking this
147      * method may cause some number of page faults and I/O operations to
148      * occur. </p>
149      *
150      * @return  This buffer
151      */

152     public final MappedByteBuffer load() {
153         if (fd == null) {
154             return this;
155         }
156         if ((address == 0) || (capacity() == 0))
157             return this;
158         long offset = mappingOffset();
159         long length = mappingLength(offset);
160         load0(mappingAddress(offset), length);
161
162         // Read a byte from each page to bring it into memory. A checksum
163         // is computed as we go along to prevent the compiler from otherwise
164         // considering the loop as dead code.
165         Unsafe unsafe = Unsafe.getUnsafe();
166         int ps = Bits.pageSize();
167         int count = Bits.pageCount(length);
168         long a = mappingAddress(offset);
169         byte x = 0;
170         try {
171             for (int i=0; i<count; i++) {
172                 // TODO consider changing to getByteOpaque thus avoiding
173                 // dead code elimination and the need to calculate a checksum
174                 x ^= unsafe.getByte(a);
175                 a += ps;
176             }
177         } finally {
178             Reference.reachabilityFence(this);
179         }
180         if (unused != 0)
181             unused = x;
182
183         return this;
184     }
185
186     /**
187      * Forces any changes made to this buffer's content to be written to the
188      * storage device containing the mapped file.
189      *
190      * <p> If the file mapped into this buffer resides on a local storage
191      * device then when this method returns it is guaranteed that all changes
192      * made to the buffer since it was created, or since this method was last
193      * invoked, will have been written to that device.
194      *
195      * <p> If the file does not reside on a local device then no such guarantee
196      * is made.
197      *
198      * <p> If this buffer was not mapped in read/write mode ({@link
199      * java.nio.channels.FileChannel.MapMode#READ_WRITE}) then invoking this
200      * method has no effect. </p>
201      *
202      * @return  This buffer
203      */

204     public final MappedByteBuffer force() {
205         if (fd == null) {
206             return this;
207         }
208         if ((address != 0) && (capacity() != 0)) {
209             long offset = mappingOffset();
210             force0(fd, mappingAddress(offset), mappingLength(offset));
211         }
212         return this;
213     }
214
215     private native boolean isLoaded0(long address, long length, int pageCount);
216     private native void load0(long address, long length);
217     private native void force0(FileDescriptor fd, long address, long length);
218
219     // -- Covariant return type overrides
220
221     /**
222      * {@inheritDoc}
223      */

224     @Override
225     public final MappedByteBuffer position(int newPosition) {
226         super.position(newPosition);
227         return this;
228     }
229
230     /**
231      * {@inheritDoc}
232      */

233     @Override
234     public final MappedByteBuffer limit(int newLimit) {
235         super.limit(newLimit);
236         return this;
237     }
238
239     /**
240      * {@inheritDoc}
241      */

242     @Override
243     public final MappedByteBuffer mark() {
244         super.mark();
245         return this;
246     }
247
248     /**
249      * {@inheritDoc}
250      */

251     @Override
252     public final MappedByteBuffer reset() {
253         super.reset();
254         return this;
255     }
256
257     /**
258      * {@inheritDoc}
259      */

260     @Override
261     public final MappedByteBuffer clear() {
262         super.clear();
263         return this;
264     }
265
266     /**
267      * {@inheritDoc}
268      */

269     @Override
270     public final MappedByteBuffer flip() {
271         super.flip();
272         return this;
273     }
274
275     /**
276      * {@inheritDoc}
277      */

278     @Override
279     public final MappedByteBuffer rewind() {
280         super.rewind();
281         return this;
282     }
283 }
284