FileChannelImpl.java 40.8 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27 28 29 30 31
 */

package sun.nio.ch;

import java.io.FileDescriptor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
32 33 34 35 36 37 38 39 40
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.FileLockInterruptionException;
import java.nio.channels.NonReadableChannelException;
import java.nio.channels.NonWritableChannelException;
import java.nio.channels.OverlappingFileLockException;
import java.nio.channels.ReadableByteChannel;
41
import java.nio.channels.SelectableChannel;
42 43
import java.nio.channels.WritableByteChannel;
import java.security.AccessController;
D
duke 已提交
44 45
import java.util.ArrayList;
import java.util.List;
46

D
duke 已提交
47 48 49 50 51 52 53
import sun.misc.Cleaner;
import sun.security.action.GetPropertyAction;

public class FileChannelImpl
    extends FileChannel
{
    // Memory allocation size for mapping buffers
54
    private static final long allocationGranularity;
D
duke 已提交
55

56 57 58
    // Used to make native read and write calls
    private final FileDispatcher nd;

D
duke 已提交
59
    // File descriptor
60
    private final FileDescriptor fd;
D
duke 已提交
61 62

    // File access mode (immutable)
63 64
    private final boolean writable;
    private final boolean readable;
65
    private final boolean append;
D
duke 已提交
66 67

    // Required to prevent finalization of creating stream (immutable)
68
    private final Object parent;
D
duke 已提交
69

70 71 72 73
    // The path of the referenced file
    // (null if the parent stream is created with a file descriptor)
    private final String path;

D
duke 已提交
74
    // Thread-safe set of IDs of native threads, for signalling
75
    private final NativeThreadSet threads = new NativeThreadSet(2);
D
duke 已提交
76 77

    // Lock for operations involving position and size
78
    private final Object positionLock = new Object();
D
duke 已提交
79

80
    private FileChannelImpl(FileDescriptor fd, String path, boolean readable,
81
                            boolean writable, boolean append, Object parent)
D
duke 已提交
82 83 84 85
    {
        this.fd = fd;
        this.readable = readable;
        this.writable = writable;
86
        this.append = append;
D
duke 已提交
87
        this.parent = parent;
88
        this.path = path;
89
        this.nd = new FileDispatcherImpl(append);
D
duke 已提交
90 91
    }

92
    // Used by FileInputStream.getChannel() and RandomAccessFile.getChannel()
93
    public static FileChannel open(FileDescriptor fd, String path,
D
duke 已提交
94 95 96
                                   boolean readable, boolean writable,
                                   Object parent)
    {
97
        return new FileChannelImpl(fd, path, readable, writable, false, parent);
98 99 100
    }

    // Used by FileOutputStream.getChannel
101
    public static FileChannel open(FileDescriptor fd, String path,
102 103 104
                                   boolean readable, boolean writable,
                                   boolean append, Object parent)
    {
105
        return new FileChannelImpl(fd, path, readable, writable, append, parent);
D
duke 已提交
106 107 108 109 110 111 112 113 114 115 116
    }

    private void ensureOpen() throws IOException {
        if (!isOpen())
            throw new ClosedChannelException();
    }


    // -- Standard channel operations --

    protected void implCloseChannel() throws IOException {
117
        // Release and invalidate any locks that we still hold
D
duke 已提交
118
        if (fileLockTable != null) {
119 120 121 122 123 124
            for (FileLock fl: fileLockTable.removeAll()) {
                synchronized (fl) {
                    if (fl.isValid()) {
                        nd.release(fd, fl.position(), fl.size());
                        ((FileLockImpl)fl).invalidate();
                    }
D
duke 已提交
125
                }
126
            }
D
duke 已提交
127 128
        }

129
        // signal any threads blocked on this channel
130 131
        threads.signalAndWait();

D
duke 已提交
132 133 134 135 136 137 138
        if (parent != null) {

            // Close the fd via the parent stream's close method.  The parent
            // will reinvoke our close method, which is defined in the
            // superclass AbstractInterruptibleChannel, but the isOpen logic in
            // that method will prevent this method from being reinvoked.
            //
139
            ((java.io.Closeable)parent).close();
D
duke 已提交
140 141 142 143 144 145 146 147 148 149 150 151
        } else {
            nd.close(fd);
        }

    }

    public int read(ByteBuffer dst) throws IOException {
        ensureOpen();
        if (!readable)
            throw new NonReadableChannelException();
        synchronized (positionLock) {
            int n = 0;
152
            int ti = -1;
D
duke 已提交
153 154
            try {
                begin();
155
                ti = threads.add();
D
duke 已提交
156 157 158
                if (!isOpen())
                    return 0;
                do {
159
                    n = IOUtil.read(fd, dst, -1, nd);
D
duke 已提交
160 161 162 163 164 165 166 167 168 169
                } while ((n == IOStatus.INTERRUPTED) && isOpen());
                return IOStatus.normalize(n);
            } finally {
                threads.remove(ti);
                end(n > 0);
                assert IOStatus.check(n);
            }
        }
    }

170 171 172 173 174
    public long read(ByteBuffer[] dsts, int offset, int length)
        throws IOException
    {
        if ((offset < 0) || (length < 0) || (offset > dsts.length - length))
            throw new IndexOutOfBoundsException();
D
duke 已提交
175 176 177 178 179
        ensureOpen();
        if (!readable)
            throw new NonReadableChannelException();
        synchronized (positionLock) {
            long n = 0;
180
            int ti = -1;
D
duke 已提交
181 182
            try {
                begin();
183
                ti = threads.add();
D
duke 已提交
184 185 186
                if (!isOpen())
                    return 0;
                do {
187
                    n = IOUtil.read(fd, dsts, offset, length, nd);
D
duke 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
                } while ((n == IOStatus.INTERRUPTED) && isOpen());
                return IOStatus.normalize(n);
            } finally {
                threads.remove(ti);
                end(n > 0);
                assert IOStatus.check(n);
            }
        }
    }

    public int write(ByteBuffer src) throws IOException {
        ensureOpen();
        if (!writable)
            throw new NonWritableChannelException();
        synchronized (positionLock) {
            int n = 0;
204
            int ti = -1;
D
duke 已提交
205 206
            try {
                begin();
207
                ti = threads.add();
D
duke 已提交
208 209 210
                if (!isOpen())
                    return 0;
                do {
211
                    n = IOUtil.write(fd, src, -1, nd);
D
duke 已提交
212 213 214 215 216 217 218 219 220 221
                } while ((n == IOStatus.INTERRUPTED) && isOpen());
                return IOStatus.normalize(n);
            } finally {
                threads.remove(ti);
                end(n > 0);
                assert IOStatus.check(n);
            }
        }
    }

222 223 224 225 226
    public long write(ByteBuffer[] srcs, int offset, int length)
        throws IOException
    {
        if ((offset < 0) || (length < 0) || (offset > srcs.length - length))
            throw new IndexOutOfBoundsException();
D
duke 已提交
227 228 229 230 231
        ensureOpen();
        if (!writable)
            throw new NonWritableChannelException();
        synchronized (positionLock) {
            long n = 0;
232
            int ti = -1;
D
duke 已提交
233 234
            try {
                begin();
235
                ti = threads.add();
D
duke 已提交
236 237 238
                if (!isOpen())
                    return 0;
                do {
239
                    n = IOUtil.write(fd, srcs, offset, length, nd);
D
duke 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
                } while ((n == IOStatus.INTERRUPTED) && isOpen());
                return IOStatus.normalize(n);
            } finally {
                threads.remove(ti);
                end(n > 0);
                assert IOStatus.check(n);
            }
        }
    }

    // -- Other operations --

    public long position() throws IOException {
        ensureOpen();
        synchronized (positionLock) {
            long p = -1;
256
            int ti = -1;
D
duke 已提交
257 258
            try {
                begin();
259
                ti = threads.add();
D
duke 已提交
260 261 262
                if (!isOpen())
                    return 0;
                do {
263 264
                    // in append-mode then position is advanced to end before writing
                    p = (append) ? nd.size(fd) : position0(fd, -1);
D
duke 已提交
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
                } while ((p == IOStatus.INTERRUPTED) && isOpen());
                return IOStatus.normalize(p);
            } finally {
                threads.remove(ti);
                end(p > -1);
                assert IOStatus.check(p);
            }
        }
    }

    public FileChannel position(long newPosition) throws IOException {
        ensureOpen();
        if (newPosition < 0)
            throw new IllegalArgumentException();
        synchronized (positionLock) {
            long p = -1;
281
            int ti = -1;
D
duke 已提交
282 283
            try {
                begin();
284
                ti = threads.add();
D
duke 已提交
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
                if (!isOpen())
                    return null;
                do {
                    p  = position0(fd, newPosition);
                } while ((p == IOStatus.INTERRUPTED) && isOpen());
                return this;
            } finally {
                threads.remove(ti);
                end(p > -1);
                assert IOStatus.check(p);
            }
        }
    }

    public long size() throws IOException {
        ensureOpen();
        synchronized (positionLock) {
            long s = -1;
303
            int ti = -1;
D
duke 已提交
304 305
            try {
                begin();
306
                ti = threads.add();
D
duke 已提交
307 308 309
                if (!isOpen())
                    return -1;
                do {
310
                    s = nd.size(fd);
D
duke 已提交
311 312 313 314 315 316 317 318 319 320
                } while ((s == IOStatus.INTERRUPTED) && isOpen());
                return IOStatus.normalize(s);
            } finally {
                threads.remove(ti);
                end(s > -1);
                assert IOStatus.check(s);
            }
        }
    }

321
    public FileChannel truncate(long newSize) throws IOException {
D
duke 已提交
322
        ensureOpen();
323 324
        if (newSize < 0)
            throw new IllegalArgumentException("Negative size");
D
duke 已提交
325 326 327 328 329
        if (!writable)
            throw new NonWritableChannelException();
        synchronized (positionLock) {
            int rv = -1;
            long p = -1;
330
            int ti = -1;
D
duke 已提交
331 332
            try {
                begin();
333
                ti = threads.add();
D
duke 已提交
334 335 336
                if (!isOpen())
                    return null;

337 338 339 340 341 342 343 344
                // get current size
                long size;
                do {
                    size = nd.size(fd);
                } while ((size == IOStatus.INTERRUPTED) && isOpen());
                if (!isOpen())
                    return null;

D
duke 已提交
345 346 347 348 349 350 351 352
                // get current position
                do {
                    p = position0(fd, -1);
                } while ((p == IOStatus.INTERRUPTED) && isOpen());
                if (!isOpen())
                    return null;
                assert p >= 0;

353 354 355 356 357 358 359 360
                // truncate file if given size is less than the current size
                if (newSize < size) {
                    do {
                        rv = nd.truncate(fd, newSize);
                    } while ((rv == IOStatus.INTERRUPTED) && isOpen());
                    if (!isOpen())
                        return null;
                }
D
duke 已提交
361

362 363 364
                // if position is beyond new size then adjust it
                if (p > newSize)
                    p = newSize;
D
duke 已提交
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
                do {
                    rv = (int)position0(fd, p);
                } while ((rv == IOStatus.INTERRUPTED) && isOpen());
                return this;
            } finally {
                threads.remove(ti);
                end(rv > -1);
                assert IOStatus.check(rv);
            }
        }
    }

    public void force(boolean metaData) throws IOException {
        ensureOpen();
        int rv = -1;
380
        int ti = -1;
D
duke 已提交
381 382
        try {
            begin();
383
            ti = threads.add();
D
duke 已提交
384 385 386
            if (!isOpen())
                return;
            do {
387
                rv = nd.force(fd, metaData);
D
duke 已提交
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
            } while ((rv == IOStatus.INTERRUPTED) && isOpen());
        } finally {
            threads.remove(ti);
            end(rv > -1);
            assert IOStatus.check(rv);
        }
    }

    // Assume at first that the underlying kernel supports sendfile();
    // set this to false if we find out later that it doesn't
    //
    private static volatile boolean transferSupported = true;

    // Assume that the underlying kernel sendfile() will work if the target
    // fd is a pipe; set this to false if we find out later that it doesn't
    //
    private static volatile boolean pipeSupported = true;

    // Assume that the underlying kernel sendfile() will work if the target
    // fd is a file; set this to false if we find out later that it doesn't
    //
    private static volatile boolean fileSupported = true;

411 412 413
    private long transferToDirectlyInternal(long position, int icount,
                                            WritableByteChannel target,
                                            FileDescriptor targetFD)
D
duke 已提交
414 415
        throws IOException
    {
416 417
        assert !nd.transferToDirectlyNeedsPositionLock() ||
               Thread.holdsLock(positionLock);
D
duke 已提交
418 419

        long n = -1;
420
        int ti = -1;
D
duke 已提交
421 422
        try {
            begin();
423
            ti = threads.add();
D
duke 已提交
424 425 426
            if (!isOpen())
                return -1;
            do {
427
                n = transferTo0(fd, position, icount, targetFD);
D
duke 已提交
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
            } while ((n == IOStatus.INTERRUPTED) && isOpen());
            if (n == IOStatus.UNSUPPORTED_CASE) {
                if (target instanceof SinkChannelImpl)
                    pipeSupported = false;
                if (target instanceof FileChannelImpl)
                    fileSupported = false;
                return IOStatus.UNSUPPORTED_CASE;
            }
            if (n == IOStatus.UNSUPPORTED) {
                // Don't bother trying again
                transferSupported = false;
                return IOStatus.UNSUPPORTED;
            }
            return IOStatus.normalize(n);
        } finally {
            threads.remove(ti);
            end (n > -1);
        }
    }

448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
    private long transferToDirectly(long position, int icount,
                                    WritableByteChannel target)
        throws IOException
    {
        if (!transferSupported)
            return IOStatus.UNSUPPORTED;

        FileDescriptor targetFD = null;
        if (target instanceof FileChannelImpl) {
            if (!fileSupported)
                return IOStatus.UNSUPPORTED_CASE;
            targetFD = ((FileChannelImpl)target).fd;
        } else if (target instanceof SelChImpl) {
            // Direct transfer to pipe causes EINVAL on some configurations
            if ((target instanceof SinkChannelImpl) && !pipeSupported)
                return IOStatus.UNSUPPORTED_CASE;

            // Platform-specific restrictions. Now there is only one:
            // Direct transfer to non-blocking channel could be forbidden
            SelectableChannel sc = (SelectableChannel)target;
            if (!nd.canTransferToDirectly(sc))
                return IOStatus.UNSUPPORTED_CASE;

            targetFD = ((SelChImpl)target).getFD();
        }

        if (targetFD == null)
            return IOStatus.UNSUPPORTED;
        int thisFDVal = IOUtil.fdVal(fd);
        int targetFDVal = IOUtil.fdVal(targetFD);
        if (thisFDVal == targetFDVal) // Not supported on some configurations
            return IOStatus.UNSUPPORTED;

        if (nd.transferToDirectlyNeedsPositionLock()) {
            synchronized (positionLock) {
                long pos = position();
                try {
                    return transferToDirectlyInternal(position, icount,
                                                      target, targetFD);
                } finally {
                    position(pos);
                }
            }
        } else {
            return transferToDirectlyInternal(position, icount, target, targetFD);
        }
    }

496 497 498 499
    // Maximum size to map when using a mapped buffer
    private static final long MAPPED_TRANSFER_SIZE = 8L*1024L*1024L;

    private long transferToTrustedChannel(long position, long count,
D
duke 已提交
500 501 502
                                          WritableByteChannel target)
        throws IOException
    {
503 504
        boolean isSelChImpl = (target instanceof SelChImpl);
        if (!((target instanceof FileChannelImpl) || isSelChImpl))
D
duke 已提交
505 506 507
            return IOStatus.UNSUPPORTED;

        // Trusted target: Use a mapped buffer
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
        long remaining = count;
        while (remaining > 0L) {
            long size = Math.min(remaining, MAPPED_TRANSFER_SIZE);
            try {
                MappedByteBuffer dbb = map(MapMode.READ_ONLY, position, size);
                try {
                    // ## Bug: Closing this channel will not terminate the write
                    int n = target.write(dbb);
                    assert n >= 0;
                    remaining -= n;
                    if (isSelChImpl) {
                        // one attempt to write to selectable channel
                        break;
                    }
                    assert n > 0;
                    position += n;
                } finally {
                    unmap(dbb);
                }
527 528 529 530 531 532
            } catch (ClosedByInterruptException e) {
                // target closed by interrupt as ClosedByInterruptException needs
                // to be thrown after closing this channel.
                assert !target.isOpen();
                try {
                    close();
533 534
                } catch (Throwable suppressed) {
                    e.addSuppressed(suppressed);
535 536
                }
                throw e;
537 538 539 540 541 542
            } catch (IOException ioe) {
                // Only throw exception if no bytes have been written
                if (remaining == count)
                    throw ioe;
                break;
            }
D
duke 已提交
543
        }
544
        return count - remaining;
D
duke 已提交
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
    }

    private long transferToArbitraryChannel(long position, int icount,
                                            WritableByteChannel target)
        throws IOException
    {
        // Untrusted target: Use a newly-erased buffer
        int c = Math.min(icount, TRANSFER_SIZE);
        ByteBuffer bb = Util.getTemporaryDirectBuffer(c);
        long tw = 0;                    // Total bytes written
        long pos = position;
        try {
            Util.erase(bb);
            while (tw < icount) {
                bb.limit(Math.min((int)(icount - tw), TRANSFER_SIZE));
                int nr = read(bb, pos);
                if (nr <= 0)
                    break;
                bb.flip();
                // ## Bug: Will block writing target if this channel
                // ##      is asynchronously closed
                int nw = target.write(bb);
                tw += nw;
                if (nw != nr)
                    break;
                pos += nw;
                bb.clear();
            }
            return tw;
        } catch (IOException x) {
            if (tw > 0)
                return tw;
            throw x;
        } finally {
            Util.releaseTemporaryDirectBuffer(bb);
        }
    }

    public long transferTo(long position, long count,
                           WritableByteChannel target)
        throws IOException
    {
        ensureOpen();
        if (!target.isOpen())
            throw new ClosedChannelException();
        if (!readable)
            throw new NonReadableChannelException();
        if (target instanceof FileChannelImpl &&
            !((FileChannelImpl)target).writable)
            throw new NonWritableChannelException();
        if ((position < 0) || (count < 0))
            throw new IllegalArgumentException();
        long sz = size();
        if (position > sz)
            return 0;
        int icount = (int)Math.min(count, Integer.MAX_VALUE);
        if ((sz - position) < icount)
            icount = (int)(sz - position);

        long n;

        // Attempt a direct transfer, if the kernel supports it
        if ((n = transferToDirectly(position, icount, target)) >= 0)
            return n;

        // Attempt a mapped transfer, but only to trusted channel types
        if ((n = transferToTrustedChannel(position, icount, target)) >= 0)
            return n;

        // Slow path for untrusted targets
        return transferToArbitraryChannel(position, icount, target);
    }

    private long transferFromFileChannel(FileChannelImpl src,
                                         long position, long count)
        throws IOException
    {
622 623
        if (!src.readable)
            throw new NonReadableChannelException();
D
duke 已提交
624
        synchronized (src.positionLock) {
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
            long pos = src.position();
            long max = Math.min(count, src.size() - pos);

            long remaining = max;
            long p = pos;
            while (remaining > 0L) {
                long size = Math.min(remaining, MAPPED_TRANSFER_SIZE);
                // ## Bug: Closing this channel will not terminate the write
                MappedByteBuffer bb = src.map(MapMode.READ_ONLY, p, size);
                try {
                    long n = write(bb, position);
                    assert n > 0;
                    p += n;
                    position += n;
                    remaining -= n;
                } catch (IOException ioe) {
                    // Only throw exception if no bytes have been written
                    if (remaining == max)
                        throw ioe;
                    break;
                } finally {
                    unmap(bb);
                }
D
duke 已提交
648
            }
649 650 651
            long nwritten = max - remaining;
            src.position(pos + nwritten);
            return nwritten;
D
duke 已提交
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
        }
    }

    private static final int TRANSFER_SIZE = 8192;

    private long transferFromArbitraryChannel(ReadableByteChannel src,
                                              long position, long count)
        throws IOException
    {
        // Untrusted target: Use a newly-erased buffer
        int c = (int)Math.min(count, TRANSFER_SIZE);
        ByteBuffer bb = Util.getTemporaryDirectBuffer(c);
        long tw = 0;                    // Total bytes written
        long pos = position;
        try {
            Util.erase(bb);
            while (tw < count) {
                bb.limit((int)Math.min((count - tw), (long)TRANSFER_SIZE));
                // ## Bug: Will block reading src if this channel
                // ##      is asynchronously closed
                int nr = src.read(bb);
                if (nr <= 0)
                    break;
                bb.flip();
                int nw = write(bb, pos);
                tw += nw;
                if (nw != nr)
                    break;
                pos += nw;
                bb.clear();
            }
            return tw;
        } catch (IOException x) {
            if (tw > 0)
                return tw;
            throw x;
        } finally {
            Util.releaseTemporaryDirectBuffer(bb);
        }
    }

    public long transferFrom(ReadableByteChannel src,
                             long position, long count)
        throws IOException
    {
        ensureOpen();
        if (!src.isOpen())
            throw new ClosedChannelException();
        if (!writable)
            throw new NonWritableChannelException();
        if ((position < 0) || (count < 0))
            throw new IllegalArgumentException();
        if (position > size())
            return 0;
        if (src instanceof FileChannelImpl)
           return transferFromFileChannel((FileChannelImpl)src,
                                          position, count);

        return transferFromArbitraryChannel(src, position, count);
    }

    public int read(ByteBuffer dst, long position) throws IOException {
        if (dst == null)
            throw new NullPointerException();
        if (position < 0)
            throw new IllegalArgumentException("Negative position");
        if (!readable)
            throw new NonReadableChannelException();
        ensureOpen();
721 722 723 724 725 726 727 728 729 730 731
        if (nd.needsPositionLock()) {
            synchronized (positionLock) {
                return readInternal(dst, position);
            }
        } else {
            return readInternal(dst, position);
        }
    }

    private int readInternal(ByteBuffer dst, long position) throws IOException {
        assert !nd.needsPositionLock() || Thread.holdsLock(positionLock);
D
duke 已提交
732
        int n = 0;
733
        int ti = -1;
D
duke 已提交
734 735
        try {
            begin();
736
            ti = threads.add();
D
duke 已提交
737 738 739
            if (!isOpen())
                return -1;
            do {
740
                n = IOUtil.read(fd, dst, position, nd);
D
duke 已提交
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
            } while ((n == IOStatus.INTERRUPTED) && isOpen());
            return IOStatus.normalize(n);
        } finally {
            threads.remove(ti);
            end(n > 0);
            assert IOStatus.check(n);
        }
    }

    public int write(ByteBuffer src, long position) throws IOException {
        if (src == null)
            throw new NullPointerException();
        if (position < 0)
            throw new IllegalArgumentException("Negative position");
        if (!writable)
            throw new NonWritableChannelException();
        ensureOpen();
758 759 760 761 762 763 764 765 766 767 768
        if (nd.needsPositionLock()) {
            synchronized (positionLock) {
                return writeInternal(src, position);
            }
        } else {
            return writeInternal(src, position);
        }
    }

    private int writeInternal(ByteBuffer src, long position) throws IOException {
        assert !nd.needsPositionLock() || Thread.holdsLock(positionLock);
D
duke 已提交
769
        int n = 0;
770
        int ti = -1;
D
duke 已提交
771 772
        try {
            begin();
773
            ti = threads.add();
D
duke 已提交
774 775 776
            if (!isOpen())
                return -1;
            do {
777
                n = IOUtil.write(fd, src, position, nd);
D
duke 已提交
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
            } while ((n == IOStatus.INTERRUPTED) && isOpen());
            return IOStatus.normalize(n);
        } finally {
            threads.remove(ti);
            end(n > 0);
            assert IOStatus.check(n);
        }
    }


    // -- Memory-mapped buffers --

    private static class Unmapper
        implements Runnable
    {
793 794 795
        // may be required to close file
        private static final NativeDispatcher nd = new FileDispatcherImpl();

796 797 798 799
        // keep track of mapped buffer usage
        static volatile int count;
        static volatile long totalSize;
        static volatile long totalCapacity;
D
duke 已提交
800

801 802 803 804 805 806 807 808
        private volatile long address;
        private final long size;
        private final int cap;
        private final FileDescriptor fd;

        private Unmapper(long address, long size, int cap,
                         FileDescriptor fd)
        {
D
duke 已提交
809 810 811
            assert (address != 0);
            this.address = address;
            this.size = size;
812
            this.cap = cap;
813
            this.fd = fd;
814 815 816 817 818 819

            synchronized (Unmapper.class) {
                count++;
                totalSize += size;
                totalCapacity += cap;
            }
D
duke 已提交
820 821 822 823 824 825 826 827
        }

        public void run() {
            if (address == 0)
                return;
            unmap0(address, size);
            address = 0;

828 829 830 831 832 833 834 835 836
            // if this mapping has a valid file descriptor then we close it
            if (fd.valid()) {
                try {
                    nd.close(fd);
                } catch (IOException ignore) {
                    // nothing we can do
                }
            }

837 838 839 840 841 842
            synchronized (Unmapper.class) {
                count--;
                totalSize -= size;
                totalCapacity -= cap;
            }
        }
D
duke 已提交
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
    }

    private static void unmap(MappedByteBuffer bb) {
        Cleaner cl = ((DirectBuffer)bb).cleaner();
        if (cl != null)
            cl.clean();
    }

    private static final int MAP_RO = 0;
    private static final int MAP_RW = 1;
    private static final int MAP_PV = 2;

    public MappedByteBuffer map(MapMode mode, long position, long size)
        throws IOException
    {
        ensureOpen();
859 860
        if (mode == null)
            throw new NullPointerException("Mode is null");
D
duke 已提交
861 862 863 864 865 866 867 868
        if (position < 0L)
            throw new IllegalArgumentException("Negative position");
        if (size < 0L)
            throw new IllegalArgumentException("Negative size");
        if (position + size < 0)
            throw new IllegalArgumentException("Position + size overflow");
        if (size > Integer.MAX_VALUE)
            throw new IllegalArgumentException("Size exceeds Integer.MAX_VALUE");
869

D
duke 已提交
870 871 872 873 874 875 876 877 878 879 880 881 882 883
        int imode = -1;
        if (mode == MapMode.READ_ONLY)
            imode = MAP_RO;
        else if (mode == MapMode.READ_WRITE)
            imode = MAP_RW;
        else if (mode == MapMode.PRIVATE)
            imode = MAP_PV;
        assert (imode >= 0);
        if ((mode != MapMode.READ_ONLY) && !writable)
            throw new NonWritableChannelException();
        if (!readable)
            throw new NonReadableChannelException();

        long addr = -1;
884
        int ti = -1;
D
duke 已提交
885 886
        try {
            begin();
887
            ti = threads.add();
D
duke 已提交
888 889
            if (!isOpen())
                return null;
890 891 892 893 894 895 896 897 898

            long filesize;
            do {
                filesize = nd.size(fd);
            } while ((filesize == IOStatus.INTERRUPTED) && isOpen());
            if (!isOpen())
                return null;

            if (filesize < position + size) { // Extend file size
D
duke 已提交
899 900 901 902 903 904
                if (!writable) {
                    throw new IOException("Channel not open for writing " +
                        "- cannot extend file to required size");
                }
                int rv;
                do {
905
                    rv = nd.truncate(fd, position + size);
D
duke 已提交
906
                } while ((rv == IOStatus.INTERRUPTED) && isOpen());
907 908
                if (!isOpen())
                    return null;
D
duke 已提交
909 910 911
            }
            if (size == 0) {
                addr = 0;
912 913
                // a valid file descriptor is not required
                FileDescriptor dummy = new FileDescriptor();
D
duke 已提交
914
                if ((!writable) || (imode == MAP_RO))
915
                    return Util.newMappedByteBufferR(0, 0, dummy, null);
D
duke 已提交
916
                else
917
                    return Util.newMappedByteBuffer(0, 0, dummy, null);
D
duke 已提交
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
            }

            int pagePosition = (int)(position % allocationGranularity);
            long mapPosition = position - pagePosition;
            long mapSize = size + pagePosition;
            try {
                // If no exception was thrown from map0, the address is valid
                addr = map0(imode, mapPosition, mapSize);
            } catch (OutOfMemoryError x) {
                // An OutOfMemoryError may indicate that we've exhausted memory
                // so force gc and re-attempt map
                System.gc();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException y) {
                    Thread.currentThread().interrupt();
                }
                try {
                    addr = map0(imode, mapPosition, mapSize);
                } catch (OutOfMemoryError y) {
                    // After a second OOME, fail
                    throw new IOException("Map failed", y);
                }
            }

943 944 945 946 947 948 949 950 951 952
            // On Windows, and potentially other platforms, we need an open
            // file descriptor for some mapping operations.
            FileDescriptor mfd;
            try {
                mfd = nd.duplicateForMapping(fd);
            } catch (IOException ioe) {
                unmap0(addr, mapSize);
                throw ioe;
            }

D
duke 已提交
953 954 955
            assert (IOStatus.checkAll(addr));
            assert (addr % allocationGranularity == 0);
            int isize = (int)size;
956 957 958 959 960 961 962 963 964 965 966 967
            Unmapper um = new Unmapper(addr, mapSize, isize, mfd);
            if ((!writable) || (imode == MAP_RO)) {
                return Util.newMappedByteBufferR(isize,
                                                 addr + pagePosition,
                                                 mfd,
                                                 um);
            } else {
                return Util.newMappedByteBuffer(isize,
                                                addr + pagePosition,
                                                mfd,
                                                um);
            }
D
duke 已提交
968 969 970 971 972 973
        } finally {
            threads.remove(ti);
            end(IOStatus.checkAll(addr));
        }
    }

974
    /**
975 976
     * Invoked by sun.management.ManagementFactoryHelper to create the management
     * interface for mapped buffers.
977
     */
978 979 980 981 982
    public static sun.misc.JavaNioAccess.BufferPool getMappedBufferPool() {
        return new sun.misc.JavaNioAccess.BufferPool() {
            @Override
            public String getName() {
                return "mapped";
983
            }
984 985 986 987 988 989 990 991 992 993 994 995 996
            @Override
            public long getCount() {
                return Unmapper.count;
            }
            @Override
            public long getTotalCapacity() {
                return Unmapper.totalCapacity;
            }
            @Override
            public long getMemoryUsed() {
                return Unmapper.totalSize;
            }
        };
997
    }
D
duke 已提交
998 999 1000

    // -- Locks --

1001

D
duke 已提交
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030

    // keeps track of locks on this file
    private volatile FileLockTable fileLockTable;

    // indicates if file locks are maintained system-wide (as per spec)
    private static boolean isSharedFileLockTable;

    // indicates if the disableSystemWideOverlappingFileLockCheck property
    // has been checked
    private static volatile boolean propertyChecked;

    // The lock list in J2SE 1.4/5.0 was local to each FileChannel instance so
    // the overlap check wasn't system wide when there were multiple channels to
    // the same file. This property is used to get 1.4/5.0 behavior if desired.
    private static boolean isSharedFileLockTable() {
        if (!propertyChecked) {
            synchronized (FileChannelImpl.class) {
                if (!propertyChecked) {
                    String value = AccessController.doPrivileged(
                        new GetPropertyAction(
                            "sun.nio.ch.disableSystemWideOverlappingFileLockCheck"));
                    isSharedFileLockTable = ((value == null) || value.equals("false"));
                    propertyChecked = true;
                }
            }
        }
        return isSharedFileLockTable;
    }

1031
    private FileLockTable fileLockTable() throws IOException {
D
duke 已提交
1032 1033 1034
        if (fileLockTable == null) {
            synchronized (this) {
                if (fileLockTable == null) {
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
                    if (isSharedFileLockTable()) {
                        int ti = threads.add();
                        try {
                            ensureOpen();
                            fileLockTable = FileLockTable.newSharedFileLockTable(this, fd);
                        } finally {
                            threads.remove(ti);
                        }
                    } else {
                        fileLockTable = new SimpleFileLockTable();
                    }
D
duke 已提交
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
                }
            }
        }
        return fileLockTable;
    }

    public FileLock lock(long position, long size, boolean shared)
        throws IOException
    {
        ensureOpen();
        if (shared && !readable)
            throw new NonReadableChannelException();
        if (!shared && !writable)
            throw new NonWritableChannelException();
        FileLockImpl fli = new FileLockImpl(this, position, size, shared);
        FileLockTable flt = fileLockTable();
        flt.add(fli);
1063
        boolean completed = false;
1064
        int ti = -1;
D
duke 已提交
1065 1066
        try {
            begin();
1067
            ti = threads.add();
D
duke 已提交
1068 1069
            if (!isOpen())
                return null;
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
            int n;
            do {
                n = nd.lock(fd, true, position, size, shared);
            } while ((n == FileDispatcher.INTERRUPTED) && isOpen());
            if (isOpen()) {
                if (n == FileDispatcher.RET_EX_LOCK) {
                    assert shared;
                    FileLockImpl fli2 = new FileLockImpl(this, position, size,
                                                         false);
                    flt.replace(fli, fli2);
                    fli = fli2;
                }
                completed = true;
D
duke 已提交
1083 1084
            }
        } finally {
1085 1086
            if (!completed)
                flt.remove(fli);
D
duke 已提交
1087 1088
            threads.remove(ti);
            try {
1089
                end(completed);
D
duke 已提交
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
            } catch (ClosedByInterruptException e) {
                throw new FileLockInterruptionException();
            }
        }
        return fli;
    }

    public FileLock tryLock(long position, long size, boolean shared)
        throws IOException
    {
        ensureOpen();
        if (shared && !readable)
            throw new NonReadableChannelException();
        if (!shared && !writable)
            throw new NonWritableChannelException();
        FileLockImpl fli = new FileLockImpl(this, position, size, shared);
        FileLockTable flt = fileLockTable();
        flt.add(fli);
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
        int result;

        int ti = threads.add();
        try {
            try {
                ensureOpen();
                result = nd.lock(fd, false, position, size, shared);
            } catch (IOException e) {
                flt.remove(fli);
                throw e;
            }
            if (result == FileDispatcher.NO_LOCK) {
                flt.remove(fli);
                return null;
            }
            if (result == FileDispatcher.RET_EX_LOCK) {
                assert shared;
                FileLockImpl fli2 = new FileLockImpl(this, position, size,
                                                     false);
                flt.replace(fli, fli2);
                return fli2;
            }
            return fli;
        } finally {
            threads.remove(ti);
D
duke 已提交
1133 1134 1135 1136
        }
    }

    void release(FileLockImpl fli) throws IOException {
1137 1138 1139 1140 1141 1142 1143
        int ti = threads.add();
        try {
            ensureOpen();
            nd.release(fd, fli.position(), fli.size());
        } finally {
            threads.remove(ti);
        }
D
duke 已提交
1144 1145 1146 1147
        assert fileLockTable != null;
        fileLockTable.remove(fli);
    }

1148
    // -- File lock support --
D
duke 已提交
1149 1150 1151 1152 1153

    /**
     * A simple file lock table that maintains a list of FileLocks obtained by a
     * FileChannel. Use to get 1.4/5.0 behaviour.
     */
1154
    private static class SimpleFileLockTable extends FileLockTable {
D
duke 已提交
1155
        // synchronize on list for access
1156
        private final List<FileLock> lockList = new ArrayList<FileLock>(2);
D
duke 已提交
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184

        public SimpleFileLockTable() {
        }

        private void checkList(long position, long size)
            throws OverlappingFileLockException
        {
            assert Thread.holdsLock(lockList);
            for (FileLock fl: lockList) {
                if (fl.overlaps(position, size)) {
                    throw new OverlappingFileLockException();
                }
            }
        }

        public void add(FileLock fl) throws OverlappingFileLockException {
            synchronized (lockList) {
                checkList(fl.position(), fl.size());
                lockList.add(fl);
            }
        }

        public void remove(FileLock fl) {
            synchronized (lockList) {
                lockList.remove(fl);
            }
        }

1185
        public List<FileLock> removeAll() {
D
duke 已提交
1186
            synchronized(lockList) {
1187 1188 1189
                List<FileLock> result = new ArrayList<FileLock>(lockList);
                lockList.clear();
                return result;
D
duke 已提交
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
            }
        }

        public void replace(FileLock fl1, FileLock fl2) {
            synchronized (lockList) {
                lockList.remove(fl1);
                lockList.add(fl2);
            }
        }
    }

    // -- Native methods --

    // Creates a new mapping
    private native long map0(int prot, long position, long length)
        throws IOException;

    // Removes an existing mapping
    private static native int unmap0(long address, long length);

    // Transfers from src to dst, or returns -2 if kernel can't do that
1211 1212
    private native long transferTo0(FileDescriptor src, long position,
                                    long count, FileDescriptor dst);
D
duke 已提交
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222

    // Sets or reports this file's position
    // If offset is -1, the current position is returned
    // otherwise the position is set to offset
    private native long position0(FileDescriptor fd, long offset);

    // Caches fieldIDs
    private static native long initIDs();

    static {
1223
        IOUtil.load();
D
duke 已提交
1224 1225 1226 1227
        allocationGranularity = initIDs();
    }

}