Call sync_file_range on the given file descriptor. See the manpage
for this syscall for more information. On systems where this
call is not available, does nothing.

@throws NativeIOException if there is an error with the syscall
496944
public static void syncFileRangeIfPossible(
      FileDescriptor fd, long offset, long nbytes, int flags)
      throws NativeIOException {
    InjectionHandler.processEvent(InjectionEventCore.NATIVEIO_SYNC_FILE_RANGE,
        flags);
    if (nativeLoaded && syncFileRangePossible) {
      try {
        sync_file_range(fd, offset, nbytes, flags);
      } catch (UnsupportedOperationException uoe) {
        LOG.warn("syncFileRangeIfPossible() failed", uoe);
        syncFileRangePossible = false;
      } catch (UnsatisfiedLinkError ule) {
        LOG.warn("syncFileRangeIfPossible() failed", ule);
        syncFileRangePossible = false;
      } catch (NativeIOException nie) {
        LOG.warn("syncFileRangeIfPossible() failed: fd " + fd + " offset "
            + offset + " nbytes " + nbytes + " flags " + flags, nie);
        throw nie;
      }
    }
  }
721543
def _read_range(self, start, end=0):
        
        stream = _BytesIO()
        try:
            with _handle_azure_exception():
                self._get_to_stream(
                    stream=stream, start_range=start,
                    end_range=(end - 1) if end else None, **self._client_kwargs)

        # Check for end of file
        except _AzureHttpError as exception:
            if exception.status_code == 416:
                # EOF
                return bytes()
            raise

        return stream.getvalue()
825736
public static void sync(long sourceFileTimeStamp, File generatedSourceFile, File classFile, String className, boolean keepgenerated, boolean keepGeneratedclassfiles) {
        if(com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable(Level.FINEST)){
            logger.logp(Level.FINEST, CLASS_NAME, "sync", "Synching for sourceFile ts [" + sourceFileTimeStamp + "]");
        }
        if (keepGeneratedclassfiles == false) {
            boolean delete = classFile.delete();
            if(com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable(Level.FINEST)){
                    logger.logp(Level.FINEST, CLASS_NAME, "sync", (delete?"Deleted":"Unable to delete") + " classFile [" + classFile +"]");
            }
            File[] icList = generatedSourceFile.getParentFile().listFiles(new InnerclassFilenameFilter(className)); //205761
            for (int i=0;i<icList.length;i++) {
                if (icList[i].isFile()) {
                    boolean innerDelete = icList[i].delete();
                    if(com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable(Level.FINEST)){
                        logger.logp(Level.FINEST, CLASS_NAME, "sync", (innerDelete?"Deleted":"Unable to delete")+" inner classFile [" + icList[i] +"]");
                    }
                }
            }           
        }
        else {
        boolean rc = classFile.setLastModified(sourceFileTimeStamp);
                    if(com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable(Level.FINEST)){
                            logger.logp(Level.FINEST, CLASS_NAME, "sync", (rc?"Updated":"Unable to update") +" lastModified timestamp for classFile [" + classFile +"] [" + classFile.lastModified()+ "]");
                    }
        }
        
        if (generatedSourceFile.exists()) {
        if (keepgenerated == false) {
            boolean delete = generatedSourceFile.delete();
                            if(com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable(Level.FINEST)){
                                    logger.logp(Level.FINEST, CLASS_NAME, "sync", (delete?"Deleted":"Unable to delete") + " generatedSourceFile [" + generatedSourceFile +"]");
                            }
        }
        else {
                            boolean rc = generatedSourceFile.setLastModified(sourceFileTimeStamp);
                            if(com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable(Level.FINEST)){
                                    logger.logp(Level.FINEST, CLASS_NAME, "sync", (rc?"Updated":"Unable to update") +" lastModified timestamp for generatedSourceFile [" + generatedSourceFile +"] [" + generatedSourceFile.lastModified()+ "]");
                            }
        }
        }
    }
164434
synchronized void sync()
    {
        try
        {
            // check we have more work to do
            if (allocatePosition.get() <= lastSyncedOffset + SYNC_MARKER_SIZE)
                return;

            // allocate a new sync marker; this is both necessary in itself, but also serves to demarcate
            // the point at which we can safely consider records to have been completely written to
            int nextMarker;
            nextMarker = allocate(SYNC_MARKER_SIZE);
            boolean close = false;
            if (nextMarker < 0)
            {
                // ensure no more of this CLS is writeable, and mark ourselves for closing
                discardUnusedTail();
                close = true;

                // wait for modifications guards both discardedTailFrom, and any outstanding appends
                waitForModifications();

                if (discardedTailFrom < buffer.capacity() - SYNC_MARKER_SIZE)
                {
                    // if there's room in the discard section to write an empty header, use that as the nextMarker
                    nextMarker = discardedTailFrom;
                }
                else
                {
                    // not enough space left in the buffer, so mark the next sync marker as the EOF position
                    nextMarker = buffer.capacity();
                }
            }
            else
            {
                waitForModifications();
            }

            assert nextMarker > lastSyncedOffset;

            // write previous sync marker to point to next sync marker
            // we don't chain the crcs here to ensure this method is idempotent if it fails
            int offset = lastSyncedOffset;
            final PureJavaCrc32 crc = new PureJavaCrc32();
            crc.updateInt((int) (id & 0xFFFFFFFFL));
            crc.updateInt((int) (id >>> 32));
            crc.updateInt(offset);
            buffer.putInt(offset, nextMarker);
            buffer.putInt(offset + 4, crc.getCrc());

            // zero out the next sync marker so replayer can cleanly exit
            if (nextMarker < buffer.capacity())
            {
                buffer.putInt(nextMarker, 0);
                buffer.putInt(nextMarker + 4, 0);
            }

            // actually perform the sync and signal those waiting for it
            buffer.force();

            if (close)
                nextMarker = buffer.capacity();

            lastSyncedOffset = nextMarker;
            syncComplete.signalAll();

            CLibrary.trySkipCache(fd, offset, nextMarker);
            if (close)
                internalClose();
        }
        catch (Exception e) // MappedByteBuffer.force() does not declare IOException but can actually throw it
        {
            throw new FSWriteError(e, getPath());
        }
    }
756698
public static void touch(File f) throws IOException
	{
		if (f.createNewFile())
		{
			// The modify time is already set
		}
		else
		{
			boolean success = f.setLastModified(System.currentTimeMillis());

			if (!success)
				log.warn("[FileHelper] {touch} Failed to update modify time on " + f);
		}
	}
146220
public void stopSyncInternal(AlluxioURI syncPoint, MountTable.Resolution resolution) {
    try (LockResource r = new LockResource(mSyncManagerLock)) {
      LOG.debug("stop syncPoint {}", syncPoint.getPath());
      RemoveSyncPointEntry removeSyncPoint = File.RemoveSyncPointEntry.newBuilder()
          .setSyncpointPath(syncPoint.toString())
          .setMountId(resolution.getMountId())
          .build();
      apply(removeSyncPoint);
      try {
        stopSyncPostJournal(syncPoint);
      } catch (Throwable e) {
        // revert state;
        AddSyncPointEntry addSyncPoint =
            File.AddSyncPointEntry.newBuilder()
                .setSyncpointPath(syncPoint.toString()).build();
        apply(addSyncPoint);
        recoverFromStopSync(syncPoint, resolution.getMountId());
      }
    }
  }
1214759
protected long checkRegions(long offset, int length) throws IOException {
        if (offset + length > filledUpTo)
            throw new IOException("Can't access memory outside the file size (" + filledUpTo
                    + " bytes). You've requested portion " + offset + "-" + (offset + length) + " bytes. File: "
                    + osFile.getAbsolutePath() + "\n" + "actual Filesize: " + size + "\n" + "actual filledUpTo: "
                    + filledUpTo);
        return offset;
    }
606597
def send_local_content
        response.headers['Accept-Ranges'] = 'bytes'
        if request.head?
          local_content_head
        elsif request.headers['Range']
          send_range_for_local_file
        else
          send_local_file_contents
        end
      end
1157442
static int write(FileDescriptor fd, ByteBuffer src, long position,
                     NativeDispatcher nd)
        throws IOException
    {
        if (src instanceof DirectBuffer)
            return writeFromNativeBuffer(fd, src, position, nd);

        // Substitute a native buffer
        int pos = src.position();
        int lim = src.limit();
        assert (pos <= lim);
        int rem = (pos <= lim ? lim - pos : 0);
        ByteBuffer bb = Util.getTemporaryDirectBuffer(rem);
        try {
            bb.put(src);
            bb.flip();
            // Do not update src until we see how many bytes were written
            src.position(pos);

            int n = writeFromNativeBuffer(fd, bb, position, nd);
            if (n > 0) {
                // now update src
                src.position(pos + n);
            }
            return n;
        } finally {
            Util.offerFirstTemporaryDirectBuffer(bb);
        }
    }
365964
public void sync() {
		if (!validState) {
			throw new InvalidStateException();
		}
		if (useMmap) {
			syncAllMmaps();
		}
		if (fileChannel != null) {
			try {
				fileChannel.force(false);
			} catch (Exception ign) {
			}
		}
		if (callback != null) {
			callback.synched();
		}
	}
312749
public static ISynchronizationPoint<IOException> rename(File source, File destination, byte priority) {
		// TODO we should use the roots instead of drive
		TaskManager t1 = Threading.getDrivesTaskManager().getTaskManager(source);
		TaskManager t2 = Threading.getDrivesTaskManager().getTaskManager(destination);
		if (t1 == t2)
			return new RenameFileTask(t1, source, destination, priority).start().getOutput();
		AsyncWork<Long, IOException> copy = IOUtil.copy(source, destination, priority, source.length(), null, 0, null);
		SynchronizationPoint<IOException> result = new SynchronizationPoint<>();
		copy.listenInline(() -> {
			new RemoveFileTask(source, priority).start().getOutput().listenInline(result);
		}, result);
		return result;
	}
489943
@SuppressWarnings("resource")
	public static ISynchronizationPoint<IOException> savePropertiesFile(Properties properties, File file, Charset charset, byte priority) {
		FileIO.ReadWrite io = new FileIO.ReadWrite(file, priority);
		AsyncWork<Void,IOException> resize = io.setSizeAsync(0);
		SynchronizationPoint<IOException> result = new SynchronizationPoint<>();
		resize.listenInline(new Runnable() {
			@Override
			public void run() {
				if (resize.hasError()) {
					result.error(resize.getError());
					io.closeAsync();
					return;
				}
				savePropertiesFile(properties, io, charset, priority, true).listenInline(result);
			}
		});
		return result;
	}
1306968
@Override
    public T fromFile(final File file) throws IllegalArgumentException, DescriptorImportException {
        // Precondition checks
        if (file == null) {
            throw new IllegalArgumentException("File not specified");
        }

        // Delegate
        try {
            return this.fromStream(new FileInputStream(file));
        } catch (final FileNotFoundException e) {
            throw new IllegalArgumentException("Specified file does not exist or is a directory: "
                + file.getAbsolutePath());
        }
    }
20825
void updateFileMonitor(Long monitorInterval, String fileMonitorType) {
        if (this.monitorInterval.equals(monitorInterval) && this.monitorType.equals(fileMonitorType)) {
            return;
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Updating FileMonitor with a new monitoring interval: " + monitorInterval + " and type: " + fileMonitorType);
        }

        this.monitorInterval = monitorInterval;
        this.monitorType = fileMonitorType;

        Hashtable<String, Object> properties = getFileMonitorProperties();
        serviceRegistration.setProperties(properties);
    }
283393
public static long syncFile(InputStream in, RandomAccessFile out) throws IOException {
		byte[] inBuff = new byte[BLOCK_SIZE];
		byte[] outBuff = new byte[BLOCK_SIZE];
		long pos = 0;
		long bytesWritten = 0;
		int numBytes;
		while((numBytes=in.read(inBuff, 0, BLOCK_SIZE))!=-1) {
			if(DEBUG) System.err.println(pos+": Read " + numBytes + " bytes of input");
			out.seek(pos);
			long blockEnd = pos + numBytes;
			if(out.length()>=blockEnd) {
				// Read block from out
				if(DEBUG) System.err.println(pos+": Reading " + numBytes + " bytes of output");
				out.readFully(outBuff, 0, numBytes);
				if(!AoArrays.equals(inBuff, outBuff, 0, numBytes)) {
					if(DEBUG) System.err.println(pos+": Updating " + numBytes + " bytes of output");
					out.seek(pos);
					if(!DRY_RUN) out.write(inBuff, 0, numBytes);
					bytesWritten += numBytes;
				} else {
					if(DEBUG) System.err.println(pos+": Data matches, not writing");
				}
			} else {
				// At end, write entire block
				if(DEBUG) System.err.println(pos+": Appending " + numBytes +" bytes to output");
				if(!DRY_RUN) out.write(inBuff, 0, numBytes);
				bytesWritten += numBytes;
			}
			pos = blockEnd;
		}
		if(out.length()!=pos) {
			if(DEBUG) System.err.println(pos+": Truncating output to " + pos + " bytes");
			assert out.length()>pos;
			if(!DRY_RUN) {
				try {
					out.setLength(pos);
				} catch(IOException e) {
					System.err.println("Warning: Unable to truncate output to " + pos +" bytes");
				}
			}
		}
		return bytesWritten;
	}
58775
public static void ioprioSetIfPossible(int ioprio_value) throws IOException {
    if (nativeLoaded && ioprioPossible) {
      try {
        ioprio_set(ioprio_value);
      } catch (UnsupportedOperationException uoe) {
        LOG.warn("ioprioSetIfPossible() failed", uoe);
        ioprioPossible = false;
      } catch (UnsatisfiedLinkError ule) {
        LOG.warn("ioprioSetIfPossible() failed", ule);
        ioprioPossible = false;
      } catch (NativeIOException nie) {
        LOG.warn("ioprioSetIfPossible() failed", nie);
        throw nie;
      }
    }
  }
651203
boolean checkFileProgress(INodeFile v, boolean checkall) 
    throws IOException {
    INode.enforceRegularStorageINode(v, 
        "checkFileProgress is not supported for non-regular files");
    if (checkall) {
      //
      // check all blocks of the file.
      //
      int closeFileReplicationMin =
        Math.min(v.getReplication(), this.minCloseReplication);
      for (Block block : v.getBlocks()) {
        if (!checkBlockProgress(v, block, closeFileReplicationMin)) {
          return false;
        }
      }
      return true;
    } else {
      //
      // check the penultimate block of this file
      //
      Block b = v.getStorage().getPenultimateBlock();
      return checkBlockProgress(v, b, minReplication);
    }
  }