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 sun.nio.ch;
  27 
  28 import java.io.FileDescriptor;
  29 import java.io.IOException;
  30 import java.io.UncheckedIOException;
  31 import java.lang.ref.Cleaner.Cleanable;
  32 import java.nio.ByteBuffer;
  33 import java.nio.MappedByteBuffer;
  34 import java.nio.channels.AsynchronousCloseException;
  35 import java.nio.channels.ClosedByInterruptException;
  36 import java.nio.channels.ClosedChannelException;
  37 import java.nio.channels.FileChannel;
  38 import java.nio.channels.FileLock;
  39 import java.nio.channels.FileLockInterruptionException;
  40 import java.nio.channels.NonReadableChannelException;
  41 import java.nio.channels.NonWritableChannelException;
  42 import java.nio.channels.ReadableByteChannel;
  43 import java.nio.channels.SelectableChannel;
  44 import java.nio.channels.WritableByteChannel;
  45 
  46 import jdk.internal.access.JavaIOFileDescriptorAccess;
  47 import jdk.internal.access.JavaNioAccess;
  48 import jdk.internal.access.SharedSecrets;
  49 import jdk.internal.ref.Cleaner;
  50 import jdk.internal.ref.CleanerFactory;
  51 
  52 public class FileChannelImpl
  53     extends FileChannel
  54 {
  55     // Memory allocation size for mapping buffers
  56     private static final long allocationGranularity;
  57 
  58     // Access to FileDescriptor internals
  59     private static final JavaIOFileDescriptorAccess fdAccess =
  60         SharedSecrets.getJavaIOFileDescriptorAccess();
  61 
  62     // Used to make native read and write calls
  63     private final FileDispatcher nd;
  64 
  65     // File descriptor
  66     private final FileDescriptor fd;
  67 
  68     // File access mode (immutable)
  69     private final boolean writable;
  70     private final boolean readable;
  71 
  72     // Required to prevent finalization of creating stream (immutable)
  73     private final Object parent;
  74 
  75     // The path of the referenced file
  76     // (null if the parent stream is created with a file descriptor)
  77     private final String path;
  78 
  79     // Thread-safe set of IDs of native threads, for signalling
  80     private final NativeThreadSet threads = new NativeThreadSet(2);
  81 
  82     // Lock for operations involving position and size
  83     private final Object positionLock = new Object();
  84 
  85     // blocking operations are not interruptible
  86     private volatile boolean uninterruptible;
  87 
  88     // DirectIO flag
  89     private final boolean direct;
  90 
  91     // IO alignment value for DirectIO
  92     private final int alignment;
  93 
  94     // Cleanable with an action which closes this channel's file descriptor
  95     private final Cleanable closer;
  96 
  97     private static class Closer implements Runnable {
  98         private final FileDescriptor fd;
  99 
 100         Closer(FileDescriptor fd) {
 101             this.fd = fd;
 102         }
 103 
 104         public void run() {
 105             try {
 106                 fdAccess.close(fd);
 107             } catch (IOException ioe) {
 108                 // Rethrow as unchecked so the exception can be propagated as needed
 109                 throw new UncheckedIOException("close", ioe);
 110             }
 111         }
 112     }
 113 
 114     private FileChannelImpl(FileDescriptor fd, String path, boolean readable,
 115                             boolean writable, boolean direct, Object parent)
 116     {
 117         this.fd = fd;
 118         this.readable = readable;
 119         this.writable = writable;
 120         this.parent = parent;
 121         this.path = path;
 122         this.direct = direct;
 123         this.nd = new FileDispatcherImpl();
 124         if (direct) {
 125             assert path != null;
 126             this.alignment = nd.setDirectIO(fd, path);
 127         } else {
 128             this.alignment = -1;
 129         }
 130 
 131         // Register a cleaning action if and only if there is no parent
 132         // as the parent will take care of closing the file descriptor.
 133         // FileChannel is used by the LambdaMetaFactory so a lambda cannot
 134         // be used here hence we use a nested class instead.
 135         this.closer = parent != null ? null :
 136             CleanerFactory.cleaner().register(this, new Closer(fd));
 137     }
 138 
 139     // Used by FileInputStream.getChannel(), FileOutputStream.getChannel
 140     // and RandomAccessFile.getChannel()
 141     public static FileChannel open(FileDescriptor fd, String path,
 142                                    boolean readable, boolean writable,
 143                                    boolean direct, Object parent)
 144     {
 145         return new FileChannelImpl(fd, path, readable, writable, direct, parent);
 146     }
 147 
 148     private void ensureOpen() throws IOException {
 149         if (!isOpen())
 150             throw new ClosedChannelException();
 151     }
 152 
 153     public void setUninterruptible() {
 154         uninterruptible = true;
 155     }
 156 
 157     private void beginBlocking() {
 158         if (!uninterruptible) begin();
 159     }
 160 
 161     private void endBlocking(boolean completed) throws AsynchronousCloseException {
 162         if (!uninterruptible) end(completed);
 163     }
 164 
 165     // -- Standard channel operations --
 166 
 167     protected void implCloseChannel() throws IOException {
 168         if (!fd.valid())
 169             return; // nothing to do
 170 
 171         // Release and invalidate any locks that we still hold
 172         if (fileLockTable != null) {
 173             for (FileLock fl: fileLockTable.removeAll()) {
 174                 synchronized (fl) {
 175                     if (fl.isValid()) {
 176                         nd.release(fd, fl.position(), fl.size());
 177                         ((FileLockImpl)fl).invalidate();
 178                     }
 179                 }
 180             }
 181         }
 182 
 183         // signal any threads blocked on this channel
 184         threads.signalAndWait();
 185 
 186         if (parent != null) {
 187 
 188             // Close the fd via the parent stream's close method.  The parent
 189             // will reinvoke our close method, which is defined in the
 190             // superclass AbstractInterruptibleChannel, but the isOpen logic in
 191             // that method will prevent this method from being reinvoked.
 192             //
 193             ((java.io.Closeable)parent).close();
 194         } else if (closer != null) {
 195             // Perform the cleaning action so it is not redone when
 196             // this channel becomes phantom reachable.
 197             try {
 198                 closer.clean();
 199             } catch (UncheckedIOException uioe) {
 200                 throw uioe.getCause();
 201             }
 202         } else {
 203             fdAccess.close(fd);
 204         }
 205 
 206     }
 207 
 208     public int read(ByteBuffer dst) throws IOException {
 209         ensureOpen();
 210         if (!readable)
 211             throw new NonReadableChannelException();
 212         synchronized (positionLock) {
 213             if (direct)
 214                 Util.checkChannelPositionAligned(position(), alignment);
 215             int n = 0;
 216             int ti = -1;
 217             try {
 218                 beginBlocking();
 219                 ti = threads.add();
 220                 if (!isOpen())
 221                     return 0;
 222                 do {
 223                     n = IOUtil.read(fd, dst, -1, direct, alignment, nd);
 224                 } while ((n == IOStatus.INTERRUPTED) && isOpen());
 225                 return IOStatus.normalize(n);
 226             } finally {
 227                 threads.remove(ti);
 228                 endBlocking(n > 0);
 229                 assert IOStatus.check(n);
 230             }
 231         }
 232     }
 233 
 234     public long read(ByteBuffer[] dsts, int offset, int length)
 235         throws IOException
 236     {
 237         if ((offset < 0) || (length < 0) || (offset > dsts.length - length))
 238             throw new IndexOutOfBoundsException();
 239         ensureOpen();
 240         if (!readable)
 241             throw new NonReadableChannelException();
 242         synchronized (positionLock) {
 243             if (direct)
 244                 Util.checkChannelPositionAligned(position(), alignment);
 245             long n = 0;
 246             int ti = -1;
 247             try {
 248                 beginBlocking();
 249                 ti = threads.add();
 250                 if (!isOpen())
 251                     return 0;
 252                 do {
 253                     n = IOUtil.read(fd, dsts, offset, length,
 254                             direct, alignment, nd);
 255                 } while ((n == IOStatus.INTERRUPTED) && isOpen());
 256                 return IOStatus.normalize(n);
 257             } finally {
 258                 threads.remove(ti);
 259                 endBlocking(n > 0);
 260                 assert IOStatus.check(n);
 261             }
 262         }
 263     }
 264 
 265     public int write(ByteBuffer src) throws IOException {
 266         ensureOpen();
 267         if (!writable)
 268             throw new NonWritableChannelException();
 269         synchronized (positionLock) {
 270             if (direct)
 271                 Util.checkChannelPositionAligned(position(), alignment);
 272             int n = 0;
 273             int ti = -1;
 274             try {
 275                 beginBlocking();
 276                 ti = threads.add();
 277                 if (!isOpen())
 278                     return 0;
 279                 do {
 280                     n = IOUtil.write(fd, src, -1, direct, alignment, nd);
 281                 } while ((n == IOStatus.INTERRUPTED) && isOpen());
 282                 return IOStatus.normalize(n);
 283             } finally {
 284                 threads.remove(ti);
 285                 endBlocking(n > 0);
 286                 assert IOStatus.check(n);
 287             }
 288         }
 289     }
 290 
 291     public long write(ByteBuffer[] srcs, int offset, int length)
 292         throws IOException
 293     {
 294         if ((offset < 0) || (length < 0) || (offset > srcs.length - length))
 295             throw new IndexOutOfBoundsException();
 296         ensureOpen();
 297         if (!writable)
 298             throw new NonWritableChannelException();
 299         synchronized (positionLock) {
 300             if (direct)
 301                 Util.checkChannelPositionAligned(position(), alignment);
 302             long n = 0;
 303             int ti = -1;
 304             try {
 305                 beginBlocking();
 306                 ti = threads.add();
 307                 if (!isOpen())
 308                     return 0;
 309                 do {
 310                     n = IOUtil.write(fd, srcs, offset, length,
 311                             direct, alignment, nd);
 312                 } while ((n == IOStatus.INTERRUPTED) && isOpen());
 313                 return IOStatus.normalize(n);
 314             } finally {
 315                 threads.remove(ti);
 316                 endBlocking(n > 0);
 317                 assert IOStatus.check(n);
 318             }
 319         }
 320     }
 321 
 322     // -- Other operations --
 323 
 324     public long position() throws IOException {
 325         ensureOpen();
 326         synchronized (positionLock) {
 327             long p = -1;
 328             int ti = -1;
 329             try {
 330                 beginBlocking();
 331                 ti = threads.add();
 332                 if (!isOpen())
 333                     return 0;
 334                 boolean append = fdAccess.getAppend(fd);
 335                 do {
 336                     // in append-mode then position is advanced to end before writing
 337                     p = (append) ? nd.size(fd) : nd.seek(fd, -1);
 338                 } while ((p == IOStatus.INTERRUPTED) && isOpen());
 339                 return IOStatus.normalize(p);
 340             } finally {
 341                 threads.remove(ti);
 342                 endBlocking(p > -1);
 343                 assert IOStatus.check(p);
 344             }
 345         }
 346     }
 347 
 348     public FileChannel position(long newPosition) throws IOException {
 349         ensureOpen();
 350         if (newPosition < 0)
 351             throw new IllegalArgumentException();
 352         synchronized (positionLock) {
 353             long p = -1;
 354             int ti = -1;
 355             try {
 356                 beginBlocking();
 357                 ti = threads.add();
 358                 if (!isOpen())
 359                     return null;
 360                 do {
 361                     p = nd.seek(fd, newPosition);
 362                 } while ((p == IOStatus.INTERRUPTED) && isOpen());
 363                 return this;
 364             } finally {
 365                 threads.remove(ti);
 366                 endBlocking(p > -1);
 367                 assert IOStatus.check(p);
 368             }
 369         }
 370     }
 371 
 372     public long size() throws IOException {
 373         ensureOpen();
 374         synchronized (positionLock) {
 375             long s = -1;
 376             int ti = -1;
 377             try {
 378                 beginBlocking();
 379                 ti = threads.add();
 380                 if (!isOpen())
 381                     return -1;
 382                 do {
 383                     s = nd.size(fd);
 384                 } while ((s == IOStatus.INTERRUPTED) && isOpen());
 385                 return IOStatus.normalize(s);
 386             } finally {
 387                 threads.remove(ti);
 388                 endBlocking(s > -1);
 389                 assert IOStatus.check(s);
 390             }
 391         }
 392     }
 393 
 394     public FileChannel truncate(long newSize) throws IOException {
 395         ensureOpen();
 396         if (newSize < 0)
 397             throw new IllegalArgumentException("Negative size");
 398         if (!writable)
 399             throw new NonWritableChannelException();
 400         synchronized (positionLock) {
 401             int rv = -1;
 402             long p = -1;
 403             int ti = -1;
 404             long rp = -1;
 405             try {
 406                 beginBlocking();
 407                 ti = threads.add();
 408                 if (!isOpen())
 409                     return null;
 410 
 411                 // get current size
 412                 long size;
 413                 do {
 414                     size = nd.size(fd);
 415                 } while ((size == IOStatus.INTERRUPTED) && isOpen());
 416                 if (!isOpen())
 417                     return null;
 418 
 419                 // get current position
 420                 do {
 421                     p = nd.seek(fd, -1);
 422                 } while ((p == IOStatus.INTERRUPTED) && isOpen());
 423                 if (!isOpen())
 424                     return null;
 425                 assert p >= 0;
 426 
 427                 // truncate file if given size is less than the current size
 428                 if (newSize < size) {
 429                     do {
 430                         rv = nd.truncate(fd, newSize);
 431                     } while ((rv == IOStatus.INTERRUPTED) && isOpen());
 432                     if (!isOpen())
 433                         return null;
 434                 }
 435 
 436                 // if position is beyond new size then adjust it
 437                 if (p > newSize)
 438                     p = newSize;
 439                 do {
 440                     rp = nd.seek(fd, p);
 441                 } while ((rp == IOStatus.INTERRUPTED) && isOpen());
 442                 return this;
 443             } finally {
 444                 threads.remove(ti);
 445                 endBlocking(rv > -1);
 446                 assert IOStatus.check(rv);
 447             }
 448         }
 449     }
 450 
 451     public void force(boolean metaData) throws IOException {
 452         ensureOpen();
 453         int rv = -1;
 454         int ti = -1;
 455         try {
 456             beginBlocking();
 457             ti = threads.add();
 458             if (!isOpen())
 459                 return;
 460             do {
 461                 rv = nd.force(fd, metaData);
 462             } while ((rv == IOStatus.INTERRUPTED) && isOpen());
 463         } finally {
 464             threads.remove(ti);
 465             endBlocking(rv > -1);
 466             assert IOStatus.check(rv);
 467         }
 468     }
 469 
 470     // Assume at first that the underlying kernel supports sendfile();
 471     // set this to false if we find out later that it doesn't
 472     //
 473     private static volatile boolean transferSupported = true;
 474 
 475     // Assume that the underlying kernel sendfile() will work if the target
 476     // fd is a pipe; set this to false if we find out later that it doesn't
 477     //
 478     private static volatile boolean pipeSupported = true;
 479 
 480     // Assume that the underlying kernel sendfile() will work if the target
 481     // fd is a file; set this to false if we find out later that it doesn't
 482     //
 483     private static volatile boolean fileSupported = true;
 484 
 485     private long transferToDirectlyInternal(long position, int icount,
 486                                             WritableByteChannel target,
 487                                             FileDescriptor targetFD)
 488         throws IOException
 489     {
 490         assert !nd.transferToDirectlyNeedsPositionLock() ||
 491                Thread.holdsLock(positionLock);
 492 
 493         long n = -1;
 494         int ti = -1;
 495         try {
 496             beginBlocking();
 497             ti = threads.add();
 498             if (!isOpen())
 499                 return -1;
 500             do {
 501                 n = transferTo0(fd, position, icount, targetFD);
 502             } while ((n == IOStatus.INTERRUPTED) && isOpen());
 503             if (n == IOStatus.UNSUPPORTED_CASE) {
 504                 if (target instanceof SinkChannelImpl)
 505                     pipeSupported = false;
 506                 if (target instanceof FileChannelImpl)
 507                     fileSupported = false;
 508                 return IOStatus.UNSUPPORTED_CASE;
 509             }
 510             if (n == IOStatus.UNSUPPORTED) {
 511                 // Don't bother trying again
 512                 transferSupported = false;
 513                 return IOStatus.UNSUPPORTED;
 514             }
 515             return IOStatus.normalize(n);
 516         } finally {
 517             threads.remove(ti);
 518             end (n > -1);
 519         }
 520     }
 521 
 522     private long transferToDirectly(long position, int icount,
 523                                     WritableByteChannel target)
 524         throws IOException
 525     {
 526         if (!transferSupported)
 527             return IOStatus.UNSUPPORTED;
 528 
 529         FileDescriptor targetFD = null;
 530         if (target instanceof FileChannelImpl) {
 531             if (!fileSupported)
 532                 return IOStatus.UNSUPPORTED_CASE;
 533             targetFD = ((FileChannelImpl)target).fd;
 534         } else if (target instanceof SelChImpl) {
 535             // Direct transfer to pipe causes EINVAL on some configurations
 536             if ((target instanceof SinkChannelImpl) && !pipeSupported)
 537                 return IOStatus.UNSUPPORTED_CASE;
 538 
 539             // Platform-specific restrictions. Now there is only one:
 540             // Direct transfer to non-blocking channel could be forbidden
 541             SelectableChannel sc = (SelectableChannel)target;
 542             if (!nd.canTransferToDirectly(sc))
 543                 return IOStatus.UNSUPPORTED_CASE;
 544 
 545             targetFD = ((SelChImpl)target).getFD();
 546         }
 547 
 548         if (targetFD == null)
 549             return IOStatus.UNSUPPORTED;
 550         int thisFDVal = IOUtil.fdVal(fd);
 551         int targetFDVal = IOUtil.fdVal(targetFD);
 552         if (thisFDVal == targetFDVal) // Not supported on some configurations
 553             return IOStatus.UNSUPPORTED;
 554 
 555         if (nd.transferToDirectlyNeedsPositionLock()) {
 556             synchronized (positionLock) {
 557                 long pos = position();
 558                 try {
 559                     return transferToDirectlyInternal(position, icount,
 560                                                       target, targetFD);
 561                 } finally {
 562                     position(pos);
 563                 }
 564             }
 565         } else {
 566             return transferToDirectlyInternal(position, icount, target, targetFD);
 567         }
 568     }
 569 
 570     // Maximum size to map when using a mapped buffer
 571     private static final long MAPPED_TRANSFER_SIZE = 8L*1024L*1024L;
 572 
 573     private long transferToTrustedChannel(long position, long count,
 574                                           WritableByteChannel target)
 575         throws IOException
 576     {
 577         boolean isSelChImpl = (target instanceof SelChImpl);
 578         if (!((target instanceof FileChannelImpl) || isSelChImpl))
 579             return IOStatus.UNSUPPORTED;
 580 
 581         // Trusted target: Use a mapped buffer
 582         long remaining = count;
 583         while (remaining > 0L) {
 584             long size = Math.min(remaining, MAPPED_TRANSFER_SIZE);
 585             try {
 586                 MappedByteBuffer dbb = map(MapMode.READ_ONLY, position, size);
 587                 try {
 588                     // ## Bug: Closing this channel will not terminate the write
 589                     int n = target.write(dbb);
 590                     assert n >= 0;
 591                     remaining -= n;
 592                     if (isSelChImpl) {
 593                         // one attempt to write to selectable channel
 594                         break;
 595                     }
 596                     assert n > 0;
 597                     position += n;
 598                 } finally {
 599                     unmap(dbb);
 600                 }
 601             } catch (ClosedByInterruptException e) {
 602                 // target closed by interrupt as ClosedByInterruptException needs
 603                 // to be thrown after closing this channel.
 604                 assert !target.isOpen();
 605                 try {
 606                     close();
 607                 } catch (Throwable suppressed) {
 608                     e.addSuppressed(suppressed);
 609                 }
 610                 throw e;
 611             } catch (IOException ioe) {
 612                 // Only throw exception if no bytes have been written
 613                 if (remaining == count)
 614                     throw ioe;
 615                 break;
 616             }
 617         }
 618         return count - remaining;
 619     }
 620 
 621     private long transferToArbitraryChannel(long position, int icount,
 622                                             WritableByteChannel target)
 623         throws IOException
 624     {
 625         // Untrusted target: Use a newly-erased buffer
 626         int c = Math.min(icount, TRANSFER_SIZE);
 627         ByteBuffer bb = ByteBuffer.allocate(c);
 628         long tw = 0;                    // Total bytes written
 629         long pos = position;
 630         try {
 631             while (tw < icount) {
 632                 bb.limit(Math.min((int)(icount - tw), TRANSFER_SIZE));
 633                 int nr = read(bb, pos);
 634                 if (nr <= 0)
 635                     break;
 636                 bb.flip();
 637                 // ## Bug: Will block writing target if this channel
 638                 // ##      is asynchronously closed
 639                 int nw = target.write(bb);
 640                 tw += nw;
 641                 if (nw != nr)
 642                     break;
 643                 pos += nw;
 644                 bb.clear();
 645             }
 646             return tw;
 647         } catch (IOException x) {
 648             if (tw > 0)
 649                 return tw;
 650             throw x;
 651         }
 652     }
 653 
 654     public long transferTo(long position, long count,
 655                            WritableByteChannel target)
 656         throws IOException
 657     {
 658         ensureOpen();
 659         if (!target.isOpen())
 660             throw new ClosedChannelException();
 661         if (!readable)
 662             throw new NonReadableChannelException();
 663         if (target instanceof FileChannelImpl &&
 664             !((FileChannelImpl)target).writable)
 665             throw new NonWritableChannelException();
 666         if ((position < 0) || (count < 0))
 667             throw new IllegalArgumentException();
 668         long sz = size();
 669         if (position > sz)
 670             return 0;
 671         int icount = (int)Math.min(count, Integer.MAX_VALUE);
 672         if ((sz - position) < icount)
 673             icount = (int)(sz - position);
 674 
 675         long n;
 676 
 677         // Attempt a direct transfer, if the kernel supports it
 678         if ((n = transferToDirectly(position, icount, target)) >= 0)
 679             return n;
 680 
 681         // Attempt a mapped transfer, but only to trusted channel types
 682         if ((n = transferToTrustedChannel(position, icount, target)) >= 0)
 683             return n;
 684 
 685         // Slow path for untrusted targets
 686         return transferToArbitraryChannel(position, icount, target);
 687     }
 688 
 689     private long transferFromFileChannel(FileChannelImpl src,
 690                                          long position, long count)
 691         throws IOException
 692     {
 693         if (!src.readable)
 694             throw new NonReadableChannelException();
 695         synchronized (src.positionLock) {
 696             long pos = src.position();
 697             long max = Math.min(count, src.size() - pos);
 698 
 699             long remaining = max;
 700             long p = pos;
 701             while (remaining > 0L) {
 702                 long size = Math.min(remaining, MAPPED_TRANSFER_SIZE);
 703                 // ## Bug: Closing this channel will not terminate the write
 704                 MappedByteBuffer bb = src.map(MapMode.READ_ONLY, p, size);
 705                 try {
 706                     long n = write(bb, position);
 707                     assert n > 0;
 708                     p += n;
 709                     position += n;
 710                     remaining -= n;
 711                 } catch (IOException ioe) {
 712                     // Only throw exception if no bytes have been written
 713                     if (remaining == max)
 714                         throw ioe;
 715                     break;
 716                 } finally {
 717                     unmap(bb);
 718                 }
 719             }
 720             long nwritten = max - remaining;
 721             src.position(pos + nwritten);
 722             return nwritten;
 723         }
 724     }
 725 
 726     private static final int TRANSFER_SIZE = 8192;
 727 
 728     private long transferFromArbitraryChannel(ReadableByteChannel src,
 729                                               long position, long count)
 730         throws IOException
 731     {
 732         // Untrusted target: Use a newly-erased buffer
 733         int c = (int)Math.min(count, TRANSFER_SIZE);
 734         ByteBuffer bb = ByteBuffer.allocate(c);
 735         long tw = 0;                    // Total bytes written
 736         long pos = position;
 737         try {
 738             while (tw < count) {
 739                 bb.limit((int)Math.min((count - tw), (long)TRANSFER_SIZE));
 740                 // ## Bug: Will block reading src if this channel
 741                 // ##      is asynchronously closed
 742                 int nr = src.read(bb);
 743                 if (nr <= 0)
 744                     break;
 745                 bb.flip();
 746                 int nw = write(bb, pos);
 747                 tw += nw;
 748                 if (nw != nr)
 749                     break;
 750                 pos += nw;
 751                 bb.clear();
 752             }
 753             return tw;
 754         } catch (IOException x) {
 755             if (tw > 0)
 756                 return tw;
 757             throw x;
 758         }
 759     }
 760 
 761     public long transferFrom(ReadableByteChannel src,
 762                              long position, long count)
 763         throws IOException
 764     {
 765         ensureOpen();
 766         if (!src.isOpen())
 767             throw new ClosedChannelException();
 768         if (!writable)
 769             throw new NonWritableChannelException();
 770         if ((position < 0) || (count < 0))
 771             throw new IllegalArgumentException();
 772         if (position > size())
 773             return 0;
 774         if (src instanceof FileChannelImpl)
 775            return transferFromFileChannel((FileChannelImpl)src,
 776                                           position, count);
 777 
 778         return transferFromArbitraryChannel(src, position, count);
 779     }
 780 
 781     public int read(ByteBuffer dst, long position) throws IOException {
 782         if (dst == null)
 783             throw new NullPointerException();
 784         if (position < 0)
 785             throw new IllegalArgumentException("Negative position");
 786         if (!readable)
 787             throw new NonReadableChannelException();
 788         if (direct)
 789             Util.checkChannelPositionAligned(position, alignment);
 790         ensureOpen();
 791         if (nd.needsPositionLock()) {
 792             synchronized (positionLock) {
 793                 return readInternal(dst, position);
 794             }
 795         } else {
 796             return readInternal(dst, position);
 797         }
 798     }
 799 
 800     private int readInternal(ByteBuffer dst, long position) throws IOException {
 801         assert !nd.needsPositionLock() || Thread.holdsLock(positionLock);
 802         int n = 0;
 803         int ti = -1;
 804 
 805         try {
 806             beginBlocking();
 807             ti = threads.add();
 808             if (!isOpen())
 809                 return -1;
 810             do {
 811                 n = IOUtil.read(fd, dst, position, direct, alignment, nd);
 812             } while ((n == IOStatus.INTERRUPTED) && isOpen());
 813             return IOStatus.normalize(n);
 814         } finally {
 815             threads.remove(ti);
 816             endBlocking(n > 0);
 817             assert IOStatus.check(n);
 818         }
 819     }
 820 
 821     public int write(ByteBuffer src, long position) throws IOException {
 822         if (src == null)
 823             throw new NullPointerException();
 824         if (position < 0)
 825             throw new IllegalArgumentException("Negative position");
 826         if (!writable)
 827             throw new NonWritableChannelException();
 828         if (direct)
 829             Util.checkChannelPositionAligned(position, alignment);
 830         ensureOpen();
 831         if (nd.needsPositionLock()) {
 832             synchronized (positionLock) {
 833                 return writeInternal(src, position);
 834             }
 835         } else {
 836             return writeInternal(src, position);
 837         }
 838     }
 839 
 840     private int writeInternal(ByteBuffer src, long position) throws IOException {
 841         assert !nd.needsPositionLock() || Thread.holdsLock(positionLock);
 842         int n = 0;
 843         int ti = -1;
 844         try {
 845             beginBlocking();
 846             ti = threads.add();
 847             if (!isOpen())
 848                 return -1;
 849             do {
 850                 n = IOUtil.write(fd, src, position, direct, alignment, nd);
 851             } while ((n == IOStatus.INTERRUPTED) && isOpen());
 852             return IOStatus.normalize(n);
 853         } finally {
 854             threads.remove(ti);
 855             endBlocking(n > 0);
 856             assert IOStatus.check(n);
 857         }
 858     }
 859 
 860 
 861     // -- Memory-mapped buffers --
 862 
 863     private static class Unmapper
 864         implements Runnable
 865     {
 866         // may be required to close file
 867         private static final NativeDispatcher nd = new FileDispatcherImpl();
 868 
 869         // keep track of mapped buffer usage
 870         static volatile int count;
 871         static volatile long totalSize;
 872         static volatile long totalCapacity;
 873 
 874         private volatile long address;
 875         private final long size;
 876         private final int cap;
 877         private final FileDescriptor fd;
 878 
 879         private Unmapper(long address, long size, int cap,
 880                          FileDescriptor fd)
 881         {
 882             assert (address != 0);
 883             this.address = address;
 884             this.size = size;
 885             this.cap = cap;
 886             this.fd = fd;
 887 
 888             synchronized (Unmapper.class) {
 889                 count++;
 890                 totalSize += size;
 891                 totalCapacity += cap;
 892             }
 893         }
 894 
 895         public void run() {
 896             if (address == 0)
 897                 return;
 898             unmap0(address, size);
 899             address = 0;
 900 
 901             // if this mapping has a valid file descriptor then we close it
 902             if (fd.valid()) {
 903                 try {
 904                     nd.close(fd);
 905                 } catch (IOException ignore) {
 906                     // nothing we can do
 907                 }
 908             }
 909 
 910             synchronized (Unmapper.class) {
 911                 count--;
 912                 totalSize -= size;
 913                 totalCapacity -= cap;
 914             }
 915         }
 916     }
 917 
 918     private static void unmap(MappedByteBuffer bb) {
 919         Cleaner cl = ((DirectBuffer)bb).cleaner();
 920         if (cl != null)
 921             cl.clean();
 922     }
 923 
 924     private static final int MAP_RO = 0;
 925     private static final int MAP_RW = 1;
 926     private static final int MAP_PV = 2;
 927 
 928     public MappedByteBuffer map(MapMode mode, long position, long size)
 929         throws IOException
 930     {
 931         ensureOpen();
 932         if (mode == null)
 933             throw new NullPointerException("Mode is null");
 934         if (position < 0L)
 935             throw new IllegalArgumentException("Negative position");
 936         if (size < 0L)
 937             throw new IllegalArgumentException("Negative size");
 938         if (position + size < 0)
 939             throw new IllegalArgumentException("Position + size overflow");
 940         if (size > Integer.MAX_VALUE)
 941             throw new IllegalArgumentException("Size exceeds Integer.MAX_VALUE");
 942 
 943         int imode;
 944         if (mode == MapMode.READ_ONLY)
 945             imode = MAP_RO;
 946         else if (mode == MapMode.READ_WRITE)
 947             imode = MAP_RW;
 948         else if (mode == MapMode.PRIVATE)
 949             imode = MAP_PV;
 950         else
 951             throw new UnsupportedOperationException();
 952         if ((mode != MapMode.READ_ONLY) && !writable)
 953             throw new NonWritableChannelException();
 954         if (!readable)
 955             throw new NonReadableChannelException();
 956 
 957         long addr = -1;
 958         int ti = -1;
 959         try {
 960             beginBlocking();
 961             ti = threads.add();
 962             if (!isOpen())
 963                 return null;
 964 
 965             long mapSize;
 966             int pagePosition;
 967             synchronized (positionLock) {
 968                 long filesize;
 969                 do {
 970                     filesize = nd.size(fd);
 971                 } while ((filesize == IOStatus.INTERRUPTED) && isOpen());
 972                 if (!isOpen())
 973                     return null;
 974 
 975                 if (filesize < position + size) { // Extend file size
 976                     if (!writable) {
 977                         throw new IOException("Channel not open for writing " +
 978                             "- cannot extend file to required size");
 979                     }
 980                     int rv;
 981                     do {
 982                         rv = nd.truncate(fd, position + size);
 983                     } while ((rv == IOStatus.INTERRUPTED) && isOpen());
 984                     if (!isOpen())
 985                         return null;
 986                 }
 987 
 988                 if (size == 0) {
 989                     addr = 0;
 990                     // a valid file descriptor is not required
 991                     FileDescriptor dummy = new FileDescriptor();
 992                     if ((!writable) || (imode == MAP_RO))
 993                         return Util.newMappedByteBufferR(0, 0, dummy, null);
 994                     else
 995                         return Util.newMappedByteBuffer(0, 0, dummy, null);
 996                 }
 997 
 998                 pagePosition = (int)(position % allocationGranularity);
 999                 long mapPosition = position - pagePosition;
1000                 mapSize = size + pagePosition;
1001                 try {
1002                     // If map0 did not throw an exception, the address is valid
1003                     addr = map0(imode, mapPosition, mapSize);
1004                 } catch (OutOfMemoryError x) {
1005                     // An OutOfMemoryError may indicate that we've exhausted
1006                     // memory so force gc and re-attempt map
1007                     System.gc();
1008                     try {
1009                         Thread.sleep(100);
1010                     } catch (InterruptedException y) {
1011                         Thread.currentThread().interrupt();
1012                     }
1013                     try {
1014                         addr = map0(imode, mapPosition, mapSize);
1015                     } catch (OutOfMemoryError y) {
1016                         // After a second OOME, fail
1017                         throw new IOException("Map failed", y);
1018                     }
1019                 }
1020             } // synchronized
1021 
1022             // On Windows, and potentially other platforms, we need an open
1023             // file descriptor for some mapping operations.
1024             FileDescriptor mfd;
1025             try {
1026                 mfd = nd.duplicateForMapping(fd);
1027             } catch (IOException ioe) {
1028                 unmap0(addr, mapSize);
1029                 throw ioe;
1030             }
1031 
1032             assert (IOStatus.checkAll(addr));
1033             assert (addr % allocationGranularity == 0);
1034             int isize = (int)size;
1035             Unmapper um = new Unmapper(addr, mapSize, isize, mfd);
1036             if ((!writable) || (imode == MAP_RO)) {
1037                 return Util.newMappedByteBufferR(isize,
1038                                                  addr + pagePosition,
1039                                                  mfd,
1040                                                  um);
1041             } else {
1042                 return Util.newMappedByteBuffer(isize,
1043                                                 addr + pagePosition,
1044                                                 mfd,
1045                                                 um);
1046             }
1047         } finally {
1048             threads.remove(ti);
1049             endBlocking(IOStatus.checkAll(addr));
1050         }
1051     }
1052 
1053     /**
1054      * Invoked by sun.management.ManagementFactoryHelper to create the management
1055      * interface for mapped buffers.
1056      */
1057     public static JavaNioAccess.BufferPool getMappedBufferPool() {
1058         return new JavaNioAccess.BufferPool() {
1059             @Override
1060             public String getName() {
1061                 return "mapped";
1062             }
1063             @Override
1064             public long getCount() {
1065                 return Unmapper.count;
1066             }
1067             @Override
1068             public long getTotalCapacity() {
1069                 return Unmapper.totalCapacity;
1070             }
1071             @Override
1072             public long getMemoryUsed() {
1073                 return Unmapper.totalSize;
1074             }
1075         };
1076     }
1077 
1078     // -- Locks --
1079 
1080     // keeps track of locks on this file
1081     private volatile FileLockTable fileLockTable;
1082 
1083     private FileLockTable fileLockTable() throws IOException {
1084         if (fileLockTable == null) {
1085             synchronized (this) {
1086                 if (fileLockTable == null) {
1087                     int ti = threads.add();
1088                     try {
1089                         ensureOpen();
1090                         fileLockTable = new FileLockTable(this, fd);
1091                     } finally {
1092                         threads.remove(ti);
1093                     }
1094                 }
1095             }
1096         }
1097         return fileLockTable;
1098     }
1099 
1100     public FileLock lock(long position, long size, boolean shared)
1101         throws IOException
1102     {
1103         ensureOpen();
1104         if (shared && !readable)
1105             throw new NonReadableChannelException();
1106         if (!shared && !writable)
1107             throw new NonWritableChannelException();
1108         FileLockImpl fli = new FileLockImpl(this, position, size, shared);
1109         FileLockTable flt = fileLockTable();
1110         flt.add(fli);
1111         boolean completed = false;
1112         int ti = -1;
1113         try {
1114             beginBlocking();
1115             ti = threads.add();
1116             if (!isOpen())
1117                 return null;
1118             int n;
1119             do {
1120                 n = nd.lock(fd, true, position, size, shared);
1121             } while ((n == FileDispatcher.INTERRUPTED) && isOpen());
1122             if (isOpen()) {
1123                 if (n == FileDispatcher.RET_EX_LOCK) {
1124                     assert shared;
1125                     FileLockImpl fli2 = new FileLockImpl(this, position, size,
1126                                                          false);
1127                     flt.replace(fli, fli2);
1128                     fli = fli2;
1129                 }
1130                 completed = true;
1131             }
1132         } finally {
1133             if (!completed)
1134                 flt.remove(fli);
1135             threads.remove(ti);
1136             try {
1137                 endBlocking(completed);
1138             } catch (ClosedByInterruptException e) {
1139                 throw new FileLockInterruptionException();
1140             }
1141         }
1142         return fli;
1143     }
1144 
1145     public FileLock tryLock(long position, long size, boolean shared)
1146         throws IOException
1147     {
1148         ensureOpen();
1149         if (shared && !readable)
1150             throw new NonReadableChannelException();
1151         if (!shared && !writable)
1152             throw new NonWritableChannelException();
1153         FileLockImpl fli = new FileLockImpl(this, position, size, shared);
1154         FileLockTable flt = fileLockTable();
1155         flt.add(fli);
1156         int result;
1157 
1158         int ti = threads.add();
1159         try {
1160             try {
1161                 ensureOpen();
1162                 result = nd.lock(fd, false, position, size, shared);
1163             } catch (IOException e) {
1164                 flt.remove(fli);
1165                 throw e;
1166             }
1167             if (result == FileDispatcher.NO_LOCK) {
1168                 flt.remove(fli);
1169                 return null;
1170             }
1171             if (result == FileDispatcher.RET_EX_LOCK) {
1172                 assert shared;
1173                 FileLockImpl fli2 = new FileLockImpl(this, position, size,
1174                                                      false);
1175                 flt.replace(fli, fli2);
1176                 return fli2;
1177             }
1178             return fli;
1179         } finally {
1180             threads.remove(ti);
1181         }
1182     }
1183 
1184     void release(FileLockImpl fli) throws IOException {
1185         int ti = threads.add();
1186         try {
1187             ensureOpen();
1188             nd.release(fd, fli.position(), fli.size());
1189         } finally {
1190             threads.remove(ti);
1191         }
1192         assert fileLockTable != null;
1193         fileLockTable.remove(fli);
1194     }
1195 
1196     // -- Native methods --
1197 
1198     // Creates a new mapping
1199     private native long map0(int prot, long position, long length)
1200         throws IOException;
1201 
1202     // Removes an existing mapping
1203     private static native int unmap0(long address, long length);
1204 
1205     // Transfers from src to dst, or returns -2 if kernel can't do that
1206     private native long transferTo0(FileDescriptor src, long position,
1207                                     long count, FileDescriptor dst);
1208 
1209     // Caches fieldIDs
1210     private static native long initIDs();
1211 
1212     static {
1213         IOUtil.load();
1214         allocationGranularity = initIDs();
1215     }
1216 }