+/*
+ * need to avoid a race between an msync of a range of pages dirtied via mmap
+ * vs a filesystem such as HFS deciding to write a 'hole' to disk via cluster_write's
+ * zerofill mechanism before it has seen the VNOP_PAGEOUTs for the pages being msync'd
+ *
+ * we should never force-zero-fill pages that are already valid in the cache...
+ * the entire page contains valid data (either from disk, zero-filled or dirtied
+ * via an mmap) so we can only do damage by trying to zero-fill
+ *
+ */
+static int
+cluster_zero_range(upl_t upl, upl_page_info_t *pl, int flags, int io_offset, off_t zero_off, off_t upl_f_offset, int bytes_to_zero)
+{
+ int zero_pg_index;
+ boolean_t need_cluster_zero = TRUE;
+
+ if ((flags & (IO_NOZEROVALID | IO_NOZERODIRTY))) {
+
+ bytes_to_zero = min(bytes_to_zero, PAGE_SIZE - (int)(zero_off & PAGE_MASK_64));
+ zero_pg_index = (int)((zero_off - upl_f_offset) / PAGE_SIZE_64);
+
+ if (upl_valid_page(pl, zero_pg_index)) {
+ /*
+ * never force zero valid pages - dirty or clean
+ * we'll leave these in the UPL for cluster_write_copy to deal with
+ */
+ need_cluster_zero = FALSE;
+ }
+ }
+ if (need_cluster_zero == TRUE)
+ cluster_zero(upl, io_offset, bytes_to_zero, NULL);
+
+ return (bytes_to_zero);
+}
+
+
+static int
+cluster_write_copy(vnode_t vp, struct uio *uio, u_int32_t io_req_size, off_t oldEOF, off_t newEOF, off_t headOff,
+ off_t tailOff, int flags, int (*callback)(buf_t, void *), void *callback_arg)
+{
+ upl_page_info_t *pl;
+ upl_t upl;
+ vm_offset_t upl_offset = 0;
+ vm_size_t upl_size;
+ off_t upl_f_offset;
+ int pages_in_upl;
+ int start_offset;
+ int xfer_resid;
+ int io_size;
+ int io_offset;
+ int bytes_to_zero;
+ int bytes_to_move;
+ kern_return_t kret;
+ int retval = 0;
+ int io_resid;
+ long long total_size;
+ long long zero_cnt;
+ off_t zero_off;
+ long long zero_cnt1;
+ off_t zero_off1;
+ off_t write_off = 0;
+ int write_cnt = 0;
+ boolean_t first_pass = FALSE;
+ struct cl_extent cl;
+ struct cl_writebehind *wbp;
+ int bflag;
+ u_int max_cluster_pgcount;
+ u_int max_io_size;
+
+ if (uio) {
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 40)) | DBG_FUNC_START,
+ (int)uio->uio_offset, io_req_size, (int)oldEOF, (int)newEOF, 0);
+
+ io_resid = io_req_size;
+ } else {
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 40)) | DBG_FUNC_START,
+ 0, 0, (int)oldEOF, (int)newEOF, 0);
+
+ io_resid = 0;
+ }
+ if (flags & IO_PASSIVE)
+ bflag = CL_PASSIVE;
+ else
+ bflag = 0;
+ if (flags & IO_NOCACHE)
+ bflag |= CL_NOCACHE;
+
+ if (flags & IO_SKIP_ENCRYPTION)
+ bflag |= CL_ENCRYPTED;
+
+ zero_cnt = 0;
+ zero_cnt1 = 0;
+ zero_off = 0;
+ zero_off1 = 0;
+
+ max_cluster_pgcount = MAX_CLUSTER_SIZE(vp) / PAGE_SIZE;
+ max_io_size = cluster_max_io_size(vp->v_mount, CL_WRITE);
+
+ if (flags & IO_HEADZEROFILL) {
+ /*
+ * some filesystems (HFS is one) don't support unallocated holes within a file...
+ * so we zero fill the intervening space between the old EOF and the offset
+ * where the next chunk of real data begins.... ftruncate will also use this
+ * routine to zero fill to the new EOF when growing a file... in this case, the
+ * uio structure will not be provided
+ */
+ if (uio) {
+ if (headOff < uio->uio_offset) {
+ zero_cnt = uio->uio_offset - headOff;
+ zero_off = headOff;
+ }
+ } else if (headOff < newEOF) {
+ zero_cnt = newEOF - headOff;
+ zero_off = headOff;
+ }
+ } else {
+ if (uio && uio->uio_offset > oldEOF) {
+ zero_off = uio->uio_offset & ~PAGE_MASK_64;
+
+ if (zero_off >= oldEOF) {
+ zero_cnt = uio->uio_offset - zero_off;
+
+ flags |= IO_HEADZEROFILL;
+ }
+ }
+ }
+ if (flags & IO_TAILZEROFILL) {
+ if (uio) {
+ zero_off1 = uio->uio_offset + io_req_size;
+
+ if (zero_off1 < tailOff)
+ zero_cnt1 = tailOff - zero_off1;
+ }
+ } else {
+ if (uio && newEOF > oldEOF) {
+ zero_off1 = uio->uio_offset + io_req_size;
+
+ if (zero_off1 == newEOF && (zero_off1 & PAGE_MASK_64)) {
+ zero_cnt1 = PAGE_SIZE_64 - (zero_off1 & PAGE_MASK_64);
+
+ flags |= IO_TAILZEROFILL;
+ }
+ }
+ }
+ if (zero_cnt == 0 && uio == (struct uio *) 0) {
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 40)) | DBG_FUNC_END,
+ retval, 0, 0, 0, 0);
+ return (0);
+ }
+ if (uio) {
+ write_off = uio->uio_offset;
+ write_cnt = uio_resid(uio);
+ /*
+ * delay updating the sequential write info
+ * in the control block until we've obtained
+ * the lock for it
+ */
+ first_pass = TRUE;
+ }
+ while ((total_size = (io_resid + zero_cnt + zero_cnt1)) && retval == 0) {
+ /*
+ * for this iteration of the loop, figure out where our starting point is
+ */
+ if (zero_cnt) {
+ start_offset = (int)(zero_off & PAGE_MASK_64);
+ upl_f_offset = zero_off - start_offset;
+ } else if (io_resid) {
+ start_offset = (int)(uio->uio_offset & PAGE_MASK_64);
+ upl_f_offset = uio->uio_offset - start_offset;
+ } else {
+ start_offset = (int)(zero_off1 & PAGE_MASK_64);
+ upl_f_offset = zero_off1 - start_offset;
+ }
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 46)) | DBG_FUNC_NONE,
+ (int)zero_off, (int)zero_cnt, (int)zero_off1, (int)zero_cnt1, 0);
+
+ if (total_size > max_io_size)
+ total_size = max_io_size;
+
+ cl.b_addr = (daddr64_t)(upl_f_offset / PAGE_SIZE_64);
+
+ if (uio && ((flags & (IO_SYNC | IO_HEADZEROFILL | IO_TAILZEROFILL)) == 0)) {
+ /*
+ * assumption... total_size <= io_resid
+ * because IO_HEADZEROFILL and IO_TAILZEROFILL not set
+ */
+ if ((start_offset + total_size) > max_io_size)
+ total_size = max_io_size - start_offset;
+ xfer_resid = total_size;
+
+ retval = cluster_copy_ubc_data_internal(vp, uio, &xfer_resid, 1, 1);
+
+ if (retval)
+ break;
+
+ io_resid -= (total_size - xfer_resid);
+ total_size = xfer_resid;
+ start_offset = (int)(uio->uio_offset & PAGE_MASK_64);
+ upl_f_offset = uio->uio_offset - start_offset;
+
+ if (total_size == 0) {
+ if (start_offset) {
+ /*
+ * the write did not finish on a page boundary
+ * which will leave upl_f_offset pointing to the
+ * beginning of the last page written instead of
+ * the page beyond it... bump it in this case
+ * so that the cluster code records the last page
+ * written as dirty
+ */
+ upl_f_offset += PAGE_SIZE_64;
+ }
+ upl_size = 0;
+
+ goto check_cluster;
+ }
+ }
+ /*
+ * compute the size of the upl needed to encompass
+ * the requested write... limit each call to cluster_io
+ * to the maximum UPL size... cluster_io will clip if
+ * this exceeds the maximum io_size for the device,
+ * make sure to account for
+ * a starting offset that's not page aligned
+ */
+ upl_size = (start_offset + total_size + (PAGE_SIZE - 1)) & ~PAGE_MASK;
+
+ if (upl_size > max_io_size)
+ upl_size = max_io_size;
+
+ pages_in_upl = upl_size / PAGE_SIZE;
+ io_size = upl_size - start_offset;
+
+ if ((long long)io_size > total_size)
+ io_size = total_size;
+
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 41)) | DBG_FUNC_START, upl_size, io_size, total_size, 0, 0);
+
+
+ /*
+ * Gather the pages from the buffer cache.
+ * The UPL_WILL_MODIFY flag lets the UPL subsystem know
+ * that we intend to modify these pages.
+ */
+ kret = ubc_create_upl(vp,
+ upl_f_offset,
+ upl_size,
+ &upl,
+ &pl,
+ UPL_SET_LITE | (( uio!=NULL && (uio->uio_flags & UIO_FLAGS_IS_COMPRESSED_FILE)) ? 0 : UPL_WILL_MODIFY));
+ if (kret != KERN_SUCCESS)
+ panic("cluster_write_copy: failed to get pagelist");
+
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 41)) | DBG_FUNC_END,
+ upl, (int)upl_f_offset, start_offset, 0, 0);
+
+ if (start_offset && upl_f_offset < oldEOF && !upl_valid_page(pl, 0)) {
+ int read_size;
+
+ /*
+ * we're starting in the middle of the first page of the upl
+ * and the page isn't currently valid, so we're going to have
+ * to read it in first... this is a synchronous operation
+ */
+ read_size = PAGE_SIZE;
+
+ if ((upl_f_offset + read_size) > oldEOF)
+ read_size = oldEOF - upl_f_offset;
+
+ retval = cluster_io(vp, upl, 0, upl_f_offset, read_size,
+ CL_READ | bflag, (buf_t)NULL, (struct clios *)NULL, callback, callback_arg);
+ if (retval) {
+ /*
+ * we had an error during the read which causes us to abort
+ * the current cluster_write request... before we do, we need
+ * to release the rest of the pages in the upl without modifying
+ * there state and mark the failed page in error
+ */
+ ubc_upl_abort_range(upl, 0, PAGE_SIZE, UPL_ABORT_DUMP_PAGES|UPL_ABORT_FREE_ON_EMPTY);
+
+ if (upl_size > PAGE_SIZE)
+ ubc_upl_abort_range(upl, 0, upl_size, UPL_ABORT_FREE_ON_EMPTY);
+
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 45)) | DBG_FUNC_NONE,
+ upl, 0, 0, retval, 0);
+ break;
+ }
+ }
+ if ((start_offset == 0 || upl_size > PAGE_SIZE) && ((start_offset + io_size) & PAGE_MASK)) {
+ /*
+ * the last offset we're writing to in this upl does not end on a page
+ * boundary... if it's not beyond the old EOF, then we'll also need to
+ * pre-read this page in if it isn't already valid
+ */
+ upl_offset = upl_size - PAGE_SIZE;
+
+ if ((upl_f_offset + start_offset + io_size) < oldEOF &&
+ !upl_valid_page(pl, upl_offset / PAGE_SIZE)) {
+ int read_size;
+
+ read_size = PAGE_SIZE;
+
+ if ((off_t)(upl_f_offset + upl_offset + read_size) > oldEOF)
+ read_size = oldEOF - (upl_f_offset + upl_offset);
+
+ retval = cluster_io(vp, upl, upl_offset, upl_f_offset + upl_offset, read_size,
+ CL_READ | bflag, (buf_t)NULL, (struct clios *)NULL, callback, callback_arg);
+ if (retval) {
+ /*
+ * we had an error during the read which causes us to abort
+ * the current cluster_write request... before we do, we
+ * need to release the rest of the pages in the upl without
+ * modifying there state and mark the failed page in error
+ */
+ ubc_upl_abort_range(upl, upl_offset, PAGE_SIZE, UPL_ABORT_DUMP_PAGES|UPL_ABORT_FREE_ON_EMPTY);
+
+ if (upl_size > PAGE_SIZE)
+ ubc_upl_abort_range(upl, 0, upl_size, UPL_ABORT_FREE_ON_EMPTY);
+
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 45)) | DBG_FUNC_NONE,
+ upl, 0, 0, retval, 0);
+ break;
+ }
+ }
+ }
+ xfer_resid = io_size;
+ io_offset = start_offset;
+
+ while (zero_cnt && xfer_resid) {
+
+ if (zero_cnt < (long long)xfer_resid)
+ bytes_to_zero = zero_cnt;
+ else
+ bytes_to_zero = xfer_resid;
+
+ bytes_to_zero = cluster_zero_range(upl, pl, flags, io_offset, zero_off, upl_f_offset, bytes_to_zero);
+
+ xfer_resid -= bytes_to_zero;
+ zero_cnt -= bytes_to_zero;
+ zero_off += bytes_to_zero;
+ io_offset += bytes_to_zero;
+ }
+ if (xfer_resid && io_resid) {
+ u_int32_t io_requested;
+
+ bytes_to_move = min(io_resid, xfer_resid);
+ io_requested = bytes_to_move;
+
+ retval = cluster_copy_upl_data(uio, upl, io_offset, (int *)&io_requested);
+
+ if (retval) {
+ ubc_upl_abort_range(upl, 0, upl_size, UPL_ABORT_DUMP_PAGES | UPL_ABORT_FREE_ON_EMPTY);
+
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 45)) | DBG_FUNC_NONE,
+ upl, 0, 0, retval, 0);
+ } else {
+ io_resid -= bytes_to_move;
+ xfer_resid -= bytes_to_move;
+ io_offset += bytes_to_move;
+ }
+ }
+ while (xfer_resid && zero_cnt1 && retval == 0) {
+
+ if (zero_cnt1 < (long long)xfer_resid)
+ bytes_to_zero = zero_cnt1;
+ else
+ bytes_to_zero = xfer_resid;
+
+ bytes_to_zero = cluster_zero_range(upl, pl, flags, io_offset, zero_off1, upl_f_offset, bytes_to_zero);
+
+ xfer_resid -= bytes_to_zero;
+ zero_cnt1 -= bytes_to_zero;
+ zero_off1 += bytes_to_zero;
+ io_offset += bytes_to_zero;
+ }
+ if (retval == 0) {
+ int cl_index;
+ int ret_cluster_try_push;
+
+ io_size += start_offset;
+
+ if ((upl_f_offset + io_size) >= newEOF && (u_int)io_size < upl_size) {
+ /*
+ * if we're extending the file with this write
+ * we'll zero fill the rest of the page so that
+ * if the file gets extended again in such a way as to leave a
+ * hole starting at this EOF, we'll have zero's in the correct spot
+ */
+ cluster_zero(upl, io_size, upl_size - io_size, NULL);
+ }
+ /*
+ * release the upl now if we hold one since...
+ * 1) pages in it may be present in the sparse cluster map
+ * and may span 2 separate buckets there... if they do and
+ * we happen to have to flush a bucket to make room and it intersects
+ * this upl, a deadlock may result on page BUSY
+ * 2) we're delaying the I/O... from this point forward we're just updating
+ * the cluster state... no need to hold the pages, so commit them
+ * 3) IO_SYNC is set...
+ * because we had to ask for a UPL that provides currenty non-present pages, the
+ * UPL has been automatically set to clear the dirty flags (both software and hardware)
+ * upon committing it... this is not the behavior we want since it's possible for
+ * pages currently present as part of a mapped file to be dirtied while the I/O is in flight.
+ * we'll pick these pages back up later with the correct behavior specified.
+ * 4) we don't want to hold pages busy in a UPL and then block on the cluster lock... if a flush
+ * of this vnode is in progress, we will deadlock if the pages being flushed intersect the pages
+ * we hold since the flushing context is holding the cluster lock.
+ */
+ ubc_upl_commit_range(upl, 0, upl_size,
+ UPL_COMMIT_SET_DIRTY | UPL_COMMIT_INACTIVATE | UPL_COMMIT_FREE_ON_EMPTY);
+check_cluster:
+ /*
+ * calculate the last logical block number
+ * that this delayed I/O encompassed
+ */
+ cl.e_addr = (daddr64_t)((upl_f_offset + (off_t)upl_size) / PAGE_SIZE_64);
+
+ if (flags & IO_SYNC) {
+ /*
+ * if the IO_SYNC flag is set than we need to
+ * bypass any clusters and immediately issue
+ * the I/O
+ */
+ goto issue_io;
+ }
+ /*
+ * take the lock to protect our accesses
+ * of the writebehind and sparse cluster state
+ */
+ wbp = cluster_get_wbp(vp, CLW_ALLOCATE | CLW_RETURNLOCKED);
+
+ if (wbp->cl_scmap) {
+
+ if ( !(flags & IO_NOCACHE)) {
+ /*
+ * we've fallen into the sparse
+ * cluster method of delaying dirty pages
+ */
+ sparse_cluster_add(&(wbp->cl_scmap), vp, &cl, newEOF, callback, callback_arg);
+
+ lck_mtx_unlock(&wbp->cl_lockw);
+
+ continue;
+ }
+ /*
+ * must have done cached writes that fell into
+ * the sparse cluster mechanism... we've switched
+ * to uncached writes on the file, so go ahead
+ * and push whatever's in the sparse map
+ * and switch back to normal clustering
+ */
+ wbp->cl_number = 0;
+
+ sparse_cluster_push(&(wbp->cl_scmap), vp, newEOF, PUSH_ALL, 0, callback, callback_arg);
+ /*
+ * no clusters of either type present at this point
+ * so just go directly to start_new_cluster since
+ * we know we need to delay this I/O since we've
+ * already released the pages back into the cache
+ * to avoid the deadlock with sparse_cluster_push
+ */
+ goto start_new_cluster;
+ }
+ if (first_pass) {
+ if (write_off == wbp->cl_last_write)
+ wbp->cl_seq_written += write_cnt;
+ else
+ wbp->cl_seq_written = write_cnt;
+
+ wbp->cl_last_write = write_off + write_cnt;
+
+ first_pass = FALSE;
+ }
+ if (wbp->cl_number == 0)
+ /*
+ * no clusters currently present
+ */
+ goto start_new_cluster;
+
+ for (cl_index = 0; cl_index < wbp->cl_number; cl_index++) {
+ /*
+ * check each cluster that we currently hold
+ * try to merge some or all of this write into
+ * one or more of the existing clusters... if
+ * any portion of the write remains, start a
+ * new cluster
+ */
+ if (cl.b_addr >= wbp->cl_clusters[cl_index].b_addr) {
+ /*
+ * the current write starts at or after the current cluster
+ */
+ if (cl.e_addr <= (wbp->cl_clusters[cl_index].b_addr + max_cluster_pgcount)) {
+ /*
+ * we have a write that fits entirely
+ * within the existing cluster limits
+ */
+ if (cl.e_addr > wbp->cl_clusters[cl_index].e_addr)
+ /*
+ * update our idea of where the cluster ends
+ */
+ wbp->cl_clusters[cl_index].e_addr = cl.e_addr;
+ break;
+ }
+ if (cl.b_addr < (wbp->cl_clusters[cl_index].b_addr + max_cluster_pgcount)) {
+ /*
+ * we have a write that starts in the middle of the current cluster
+ * but extends beyond the cluster's limit... we know this because
+ * of the previous checks
+ * we'll extend the current cluster to the max
+ * and update the b_addr for the current write to reflect that
+ * the head of it was absorbed into this cluster...
+ * note that we'll always have a leftover tail in this case since
+ * full absorbtion would have occurred in the clause above
+ */
+ wbp->cl_clusters[cl_index].e_addr = wbp->cl_clusters[cl_index].b_addr + max_cluster_pgcount;
+
+ cl.b_addr = wbp->cl_clusters[cl_index].e_addr;
+ }
+ /*
+ * we come here for the case where the current write starts
+ * beyond the limit of the existing cluster or we have a leftover
+ * tail after a partial absorbtion
+ *
+ * in either case, we'll check the remaining clusters before
+ * starting a new one
+ */
+ } else {
+ /*
+ * the current write starts in front of the cluster we're currently considering
+ */
+ if ((wbp->cl_clusters[cl_index].e_addr - cl.b_addr) <= max_cluster_pgcount) {
+ /*
+ * we can just merge the new request into
+ * this cluster and leave it in the cache
+ * since the resulting cluster is still
+ * less than the maximum allowable size
+ */
+ wbp->cl_clusters[cl_index].b_addr = cl.b_addr;
+
+ if (cl.e_addr > wbp->cl_clusters[cl_index].e_addr) {
+ /*
+ * the current write completely
+ * envelops the existing cluster and since
+ * each write is limited to at most max_cluster_pgcount pages
+ * we can just use the start and last blocknos of the write
+ * to generate the cluster limits
+ */
+ wbp->cl_clusters[cl_index].e_addr = cl.e_addr;
+ }
+ break;
+ }
+
+ /*
+ * if we were to combine this write with the current cluster
+ * we would exceed the cluster size limit.... so,
+ * let's see if there's any overlap of the new I/O with
+ * the cluster we're currently considering... in fact, we'll
+ * stretch the cluster out to it's full limit and see if we
+ * get an intersection with the current write
+ *
+ */
+ if (cl.e_addr > wbp->cl_clusters[cl_index].e_addr - max_cluster_pgcount) {
+ /*
+ * the current write extends into the proposed cluster
+ * clip the length of the current write after first combining it's
+ * tail with the newly shaped cluster
+ */
+ wbp->cl_clusters[cl_index].b_addr = wbp->cl_clusters[cl_index].e_addr - max_cluster_pgcount;
+
+ cl.e_addr = wbp->cl_clusters[cl_index].b_addr;
+ }
+ /*
+ * if we get here, there was no way to merge
+ * any portion of this write with this cluster
+ * or we could only merge part of it which
+ * will leave a tail...
+ * we'll check the remaining clusters before starting a new one
+ */
+ }
+ }
+ if (cl_index < wbp->cl_number)
+ /*
+ * we found an existing cluster(s) that we
+ * could entirely merge this I/O into
+ */
+ goto delay_io;
+
+ if (!((unsigned int)vfs_flags(vp->v_mount) & MNT_DEFWRITE) &&
+ wbp->cl_number == MAX_CLUSTERS &&
+ wbp->cl_seq_written >= (MAX_CLUSTERS * (max_cluster_pgcount * PAGE_SIZE))) {
+ uint32_t n;
+
+ if (vp->v_mount->mnt_minsaturationbytecount) {
+ n = vp->v_mount->mnt_minsaturationbytecount / MAX_CLUSTER_SIZE(vp);
+
+ if (n > MAX_CLUSTERS)
+ n = MAX_CLUSTERS;
+ } else
+ n = 0;
+
+ if (n == 0) {
+ if (vp->v_mount->mnt_kern_flag & MNTK_SSD)
+ n = WRITE_BEHIND_SSD;
+ else
+ n = WRITE_BEHIND;
+ }
+ while (n--)
+ cluster_try_push(wbp, vp, newEOF, 0, 0, callback, callback_arg, NULL);
+ }
+ if (wbp->cl_number < MAX_CLUSTERS) {
+ /*
+ * we didn't find an existing cluster to
+ * merge into, but there's room to start
+ * a new one
+ */
+ goto start_new_cluster;
+ }
+ /*
+ * no exisitng cluster to merge with and no
+ * room to start a new one... we'll try
+ * pushing one of the existing ones... if none of
+ * them are able to be pushed, we'll switch
+ * to the sparse cluster mechanism
+ * cluster_try_push updates cl_number to the
+ * number of remaining clusters... and
+ * returns the number of currently unused clusters
+ */
+ ret_cluster_try_push = 0;
+
+ /*
+ * if writes are not deferred, call cluster push immediately
+ */
+ if (!((unsigned int)vfs_flags(vp->v_mount) & MNT_DEFWRITE)) {
+
+ ret_cluster_try_push = cluster_try_push(wbp, vp, newEOF, (flags & IO_NOCACHE) ? 0 : PUSH_DELAY, 0, callback, callback_arg, NULL);
+ }
+
+ /*
+ * execute following regardless of writes being deferred or not
+ */
+ if (ret_cluster_try_push == 0) {
+ /*
+ * no more room in the normal cluster mechanism
+ * so let's switch to the more expansive but expensive
+ * sparse mechanism....
+ */
+ sparse_cluster_switch(wbp, vp, newEOF, callback, callback_arg);
+ sparse_cluster_add(&(wbp->cl_scmap), vp, &cl, newEOF, callback, callback_arg);
+
+ lck_mtx_unlock(&wbp->cl_lockw);
+
+ continue;
+ }
+start_new_cluster:
+ wbp->cl_clusters[wbp->cl_number].b_addr = cl.b_addr;
+ wbp->cl_clusters[wbp->cl_number].e_addr = cl.e_addr;
+
+ wbp->cl_clusters[wbp->cl_number].io_flags = 0;
+
+ if (flags & IO_NOCACHE)
+ wbp->cl_clusters[wbp->cl_number].io_flags |= CLW_IONOCACHE;
+
+ if (bflag & CL_PASSIVE)
+ wbp->cl_clusters[wbp->cl_number].io_flags |= CLW_IOPASSIVE;
+
+ wbp->cl_number++;
+delay_io:
+ lck_mtx_unlock(&wbp->cl_lockw);
+
+ continue;
+issue_io:
+ /*
+ * we don't hold the lock at this point
+ *
+ * we've already dropped the current upl, so pick it back up with COPYOUT_FROM set
+ * so that we correctly deal with a change in state of the hardware modify bit...
+ * we do this via cluster_push_now... by passing along the IO_SYNC flag, we force
+ * cluster_push_now to wait until all the I/Os have completed... cluster_push_now is also
+ * responsible for generating the correct sized I/O(s)
+ */
+ retval = cluster_push_now(vp, &cl, newEOF, flags, callback, callback_arg);
+ }
+ }
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 40)) | DBG_FUNC_END, retval, 0, io_resid, 0, 0);
+
+ return (retval);
+}
+
+
+
+int
+cluster_read(vnode_t vp, struct uio *uio, off_t filesize, int xflags)
+{
+ return cluster_read_ext(vp, uio, filesize, xflags, NULL, NULL);
+}
+
+
+int
+cluster_read_ext(vnode_t vp, struct uio *uio, off_t filesize, int xflags, int (*callback)(buf_t, void *), void *callback_arg)
+{
+ int retval = 0;
+ int flags;
+ user_ssize_t cur_resid;
+ u_int32_t io_size;
+ u_int32_t read_length = 0;
+ int read_type = IO_COPY;
+
+ flags = xflags;
+
+ if (vp->v_flag & VNOCACHE_DATA)
+ flags |= IO_NOCACHE;
+ if ((vp->v_flag & VRAOFF) || speculative_reads_disabled)
+ flags |= IO_RAOFF;
+
+ if (flags & IO_SKIP_ENCRYPTION)
+ flags |= IO_ENCRYPTED;
+
+ /*
+ * do a read through the cache if one of the following is true....
+ * NOCACHE is not true
+ * the uio request doesn't target USERSPACE
+ * Alternatively, if IO_ENCRYPTED is set, then we want to bypass the cache as well.
+ * Reading encrypted data from a CP filesystem should never result in the data touching
+ * the UBC.
+ *
+ * otherwise, find out if we want the direct or contig variant for
+ * the first vector in the uio request
+ */
+ if ( ((flags & IO_NOCACHE) && UIO_SEG_IS_USER_SPACE(uio->uio_segflg)) || (flags & IO_ENCRYPTED) ) {
+
+ retval = cluster_io_type(uio, &read_type, &read_length, 0);
+ }
+
+ while ((cur_resid = uio_resid(uio)) && uio->uio_offset < filesize && retval == 0) {
+
+ switch (read_type) {
+
+ case IO_COPY:
+ /*
+ * make sure the uio_resid isn't too big...
+ * internally, we want to handle all of the I/O in
+ * chunk sizes that fit in a 32 bit int
+ */
+ if (cur_resid > (user_ssize_t)(MAX_IO_REQUEST_SIZE))
+ io_size = MAX_IO_REQUEST_SIZE;
+ else
+ io_size = (u_int32_t)cur_resid;
+
+ retval = cluster_read_copy(vp, uio, io_size, filesize, flags, callback, callback_arg);
+ break;
+
+ case IO_DIRECT:
+ retval = cluster_read_direct(vp, uio, filesize, &read_type, &read_length, flags, callback, callback_arg);
+ break;
+
+ case IO_CONTIG:
+ retval = cluster_read_contig(vp, uio, filesize, &read_type, &read_length, callback, callback_arg, flags);
+ break;
+
+ case IO_UNKNOWN:
+ retval = cluster_io_type(uio, &read_type, &read_length, 0);
+ break;
+ }
+ }
+ return (retval);
+}
+
+
+
+static void
+cluster_read_upl_release(upl_t upl, int start_pg, int last_pg, int take_reference)
+{
+ int range;
+ int abort_flags = UPL_ABORT_FREE_ON_EMPTY;
+
+ if ((range = last_pg - start_pg)) {
+ if (take_reference)
+ abort_flags |= UPL_ABORT_REFERENCE;
+
+ ubc_upl_abort_range(upl, start_pg * PAGE_SIZE, range * PAGE_SIZE, abort_flags);
+ }
+}
+
+
+static int
+cluster_read_copy(vnode_t vp, struct uio *uio, u_int32_t io_req_size, off_t filesize, int flags, int (*callback)(buf_t, void *), void *callback_arg)
+{
+ upl_page_info_t *pl;
+ upl_t upl;
+ vm_offset_t upl_offset;
+ u_int32_t upl_size;
+ off_t upl_f_offset;
+ int start_offset;
+ int start_pg;
+ int last_pg;
+ int uio_last = 0;
+ int pages_in_upl;
+ off_t max_size;
+ off_t last_ioread_offset;
+ off_t last_request_offset;
+ kern_return_t kret;
+ int error = 0;
+ int retval = 0;
+ u_int32_t size_of_prefetch;
+ u_int32_t xsize;
+ u_int32_t io_size;
+ u_int32_t max_rd_size;
+ u_int32_t max_io_size;
+ u_int32_t max_prefetch;
+ u_int rd_ahead_enabled = 1;
+ u_int prefetch_enabled = 1;
+ struct cl_readahead * rap;
+ struct clios iostate;
+ struct cl_extent extent;
+ int bflag;
+ int take_reference = 1;
+ int policy = IOPOL_DEFAULT;
+ boolean_t iolock_inited = FALSE;
+
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 32)) | DBG_FUNC_START,
+ (int)uio->uio_offset, io_req_size, (int)filesize, flags, 0);
+
+ if (flags & IO_ENCRYPTED) {
+ panic ("encrypted blocks will hit UBC!");
+ }
+
+ policy = throttle_get_io_policy(NULL);
+
+ if (policy == THROTTLE_LEVEL_TIER3 || policy == THROTTLE_LEVEL_TIER2 || (flags & IO_NOCACHE))
+ take_reference = 0;
+
+ if (flags & IO_PASSIVE)
+ bflag = CL_PASSIVE;
+ else
+ bflag = 0;
+
+ if (flags & IO_NOCACHE)
+ bflag |= CL_NOCACHE;
+
+ if (flags & IO_SKIP_ENCRYPTION)
+ bflag |= CL_ENCRYPTED;
+
+ max_io_size = cluster_max_io_size(vp->v_mount, CL_READ);
+ max_prefetch = MAX_PREFETCH(vp, max_io_size, (vp->v_mount->mnt_kern_flag & MNTK_SSD));
+ max_rd_size = max_prefetch;
+
+ last_request_offset = uio->uio_offset + io_req_size;
+
+ if (last_request_offset > filesize)
+ last_request_offset = filesize;
+
+ if ((flags & (IO_RAOFF|IO_NOCACHE)) || ((last_request_offset & ~PAGE_MASK_64) == (uio->uio_offset & ~PAGE_MASK_64))) {
+ rd_ahead_enabled = 0;
+ rap = NULL;
+ } else {
+ if (cluster_is_throttled(vp)) {
+ /*
+ * we're in the throttle window, at the very least
+ * we want to limit the size of the I/O we're about
+ * to issue
+ */
+ rd_ahead_enabled = 0;
+ prefetch_enabled = 0;
+
+ max_rd_size = THROTTLE_MAX_IOSIZE;
+ }
+ if ((rap = cluster_get_rap(vp)) == NULL)
+ rd_ahead_enabled = 0;
+ else {
+ extent.b_addr = uio->uio_offset / PAGE_SIZE_64;
+ extent.e_addr = (last_request_offset - 1) / PAGE_SIZE_64;
+ }
+ }
+ if (rap != NULL && rap->cl_ralen && (rap->cl_lastr == extent.b_addr || (rap->cl_lastr + 1) == extent.b_addr)) {
+ /*
+ * determine if we already have a read-ahead in the pipe courtesy of the
+ * last read systemcall that was issued...
+ * if so, pick up it's extent to determine where we should start
+ * with respect to any read-ahead that might be necessary to
+ * garner all the data needed to complete this read systemcall
+ */
+ last_ioread_offset = (rap->cl_maxra * PAGE_SIZE_64) + PAGE_SIZE_64;
+
+ if (last_ioread_offset < uio->uio_offset)
+ last_ioread_offset = (off_t)0;
+ else if (last_ioread_offset > last_request_offset)
+ last_ioread_offset = last_request_offset;
+ } else
+ last_ioread_offset = (off_t)0;
+
+ while (io_req_size && uio->uio_offset < filesize && retval == 0) {
+
+ max_size = filesize - uio->uio_offset;
+
+ if ((off_t)(io_req_size) < max_size)
+ io_size = io_req_size;
+ else
+ io_size = max_size;
+
+ if (!(flags & IO_NOCACHE)) {
+
+ while (io_size) {
+ u_int32_t io_resid;
+ u_int32_t io_requested;
+
+ /*
+ * if we keep finding the pages we need already in the cache, then
+ * don't bother to call cluster_read_prefetch since it costs CPU cycles
+ * to determine that we have all the pages we need... once we miss in
+ * the cache and have issued an I/O, than we'll assume that we're likely
+ * to continue to miss in the cache and it's to our advantage to try and prefetch
+ */
+ if (last_request_offset && last_ioread_offset && (size_of_prefetch = (last_request_offset - last_ioread_offset))) {
+ if ((last_ioread_offset - uio->uio_offset) <= max_rd_size && prefetch_enabled) {
+ /*
+ * we've already issued I/O for this request and
+ * there's still work to do and
+ * our prefetch stream is running dry, so issue a
+ * pre-fetch I/O... the I/O latency will overlap
+ * with the copying of the data
+ */
+ if (size_of_prefetch > max_rd_size)
+ size_of_prefetch = max_rd_size;
+
+ size_of_prefetch = cluster_read_prefetch(vp, last_ioread_offset, size_of_prefetch, filesize, callback, callback_arg, bflag);
+
+ last_ioread_offset += (off_t)(size_of_prefetch * PAGE_SIZE);
+
+ if (last_ioread_offset > last_request_offset)
+ last_ioread_offset = last_request_offset;
+ }
+ }
+ /*
+ * limit the size of the copy we're about to do so that
+ * we can notice that our I/O pipe is running dry and
+ * get the next I/O issued before it does go dry
+ */
+ if (last_ioread_offset && io_size > (max_io_size / 4))
+ io_resid = (max_io_size / 4);
+ else
+ io_resid = io_size;
+
+ io_requested = io_resid;
+
+ retval = cluster_copy_ubc_data_internal(vp, uio, (int *)&io_resid, 0, take_reference);
+
+ xsize = io_requested - io_resid;
+
+ io_size -= xsize;
+ io_req_size -= xsize;
+
+ if (retval || io_resid)
+ /*
+ * if we run into a real error or
+ * a page that is not in the cache
+ * we need to leave streaming mode
+ */
+ break;
+
+ if (rd_ahead_enabled && (io_size == 0 || last_ioread_offset == last_request_offset)) {
+ /*
+ * we're already finished the I/O for this read request
+ * let's see if we should do a read-ahead
+ */
+ cluster_read_ahead(vp, &extent, filesize, rap, callback, callback_arg, bflag);
+ }
+ }
+ if (retval)
+ break;
+ if (io_size == 0) {
+ if (rap != NULL) {
+ if (extent.e_addr < rap->cl_lastr)
+ rap->cl_maxra = 0;
+ rap->cl_lastr = extent.e_addr;
+ }
+ break;
+ }
+ /*
+ * recompute max_size since cluster_copy_ubc_data_internal
+ * may have advanced uio->uio_offset
+ */
+ max_size = filesize - uio->uio_offset;
+ }
+
+ iostate.io_completed = 0;
+ iostate.io_issued = 0;
+ iostate.io_error = 0;
+ iostate.io_wanted = 0;
+
+ if ( (flags & IO_RETURN_ON_THROTTLE) ) {
+ if (cluster_is_throttled(vp) == THROTTLE_NOW) {
+ if ( !cluster_io_present_in_BC(vp, uio->uio_offset)) {
+ /*
+ * we're in the throttle window and at least 1 I/O
+ * has already been issued by a throttleable thread
+ * in this window, so return with EAGAIN to indicate
+ * to the FS issuing the cluster_read call that it
+ * should now throttle after dropping any locks
+ */
+ throttle_info_update_by_mount(vp->v_mount);
+
+ retval = EAGAIN;
+ break;
+ }
+ }
+ }
+
+ /*
+ * compute the size of the upl needed to encompass
+ * the requested read... limit each call to cluster_io
+ * to the maximum UPL size... cluster_io will clip if
+ * this exceeds the maximum io_size for the device,
+ * make sure to account for
+ * a starting offset that's not page aligned
+ */
+ start_offset = (int)(uio->uio_offset & PAGE_MASK_64);
+ upl_f_offset = uio->uio_offset - (off_t)start_offset;
+
+ if (io_size > max_rd_size)
+ io_size = max_rd_size;
+
+ upl_size = (start_offset + io_size + (PAGE_SIZE - 1)) & ~PAGE_MASK;
+
+ if (flags & IO_NOCACHE) {
+ if (upl_size > max_io_size)
+ upl_size = max_io_size;
+ } else {
+ if (upl_size > max_io_size / 4) {
+ upl_size = max_io_size / 4;
+ upl_size &= ~PAGE_MASK;
+
+ if (upl_size == 0)
+ upl_size = PAGE_SIZE;
+ }
+ }
+ pages_in_upl = upl_size / PAGE_SIZE;
+
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 33)) | DBG_FUNC_START,
+ upl, (int)upl_f_offset, upl_size, start_offset, 0);
+
+ kret = ubc_create_upl(vp,
+ upl_f_offset,
+ upl_size,
+ &upl,
+ &pl,
+ UPL_FILE_IO | UPL_SET_LITE);
+ if (kret != KERN_SUCCESS)
+ panic("cluster_read_copy: failed to get pagelist");
+
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 33)) | DBG_FUNC_END,
+ upl, (int)upl_f_offset, upl_size, start_offset, 0);
+
+ /*
+ * scan from the beginning of the upl looking for the first
+ * non-valid page.... this will become the first page in
+ * the request we're going to make to 'cluster_io'... if all
+ * of the pages are valid, we won't call through to 'cluster_io'
+ */
+ for (start_pg = 0; start_pg < pages_in_upl; start_pg++) {
+ if (!upl_valid_page(pl, start_pg))
+ break;
+ }
+
+ /*
+ * scan from the starting invalid page looking for a valid
+ * page before the end of the upl is reached, if we
+ * find one, then it will be the last page of the request to
+ * 'cluster_io'
+ */
+ for (last_pg = start_pg; last_pg < pages_in_upl; last_pg++) {
+ if (upl_valid_page(pl, last_pg))
+ break;
+ }
+
+ if (start_pg < last_pg) {
+ /*
+ * we found a range of 'invalid' pages that must be filled
+ * if the last page in this range is the last page of the file
+ * we may have to clip the size of it to keep from reading past
+ * the end of the last physical block associated with the file
+ */
+ if (iolock_inited == FALSE) {
+ lck_mtx_init(&iostate.io_mtxp, cl_mtx_grp, cl_mtx_attr);
+
+ iolock_inited = TRUE;
+ }
+ upl_offset = start_pg * PAGE_SIZE;
+ io_size = (last_pg - start_pg) * PAGE_SIZE;
+
+ if ((off_t)(upl_f_offset + upl_offset + io_size) > filesize)
+ io_size = filesize - (upl_f_offset + upl_offset);
+
+ /*
+ * issue an asynchronous read to cluster_io
+ */
+
+ error = cluster_io(vp, upl, upl_offset, upl_f_offset + upl_offset,
+ io_size, CL_READ | CL_ASYNC | bflag, (buf_t)NULL, &iostate, callback, callback_arg);
+
+ if (rap) {
+ if (extent.e_addr < rap->cl_maxra) {
+ /*
+ * we've just issued a read for a block that should have been
+ * in the cache courtesy of the read-ahead engine... something
+ * has gone wrong with the pipeline, so reset the read-ahead
+ * logic which will cause us to restart from scratch
+ */
+ rap->cl_maxra = 0;
+ }
+ }
+ }
+ if (error == 0) {
+ /*
+ * if the read completed successfully, or there was no I/O request
+ * issued, than copy the data into user land via 'cluster_upl_copy_data'
+ * we'll first add on any 'valid'
+ * pages that were present in the upl when we acquired it.
+ */
+ u_int val_size;
+
+ for (uio_last = last_pg; uio_last < pages_in_upl; uio_last++) {
+ if (!upl_valid_page(pl, uio_last))
+ break;
+ }
+ if (uio_last < pages_in_upl) {
+ /*
+ * there were some invalid pages beyond the valid pages
+ * that we didn't issue an I/O for, just release them
+ * unchanged now, so that any prefetch/readahed can
+ * include them
+ */
+ ubc_upl_abort_range(upl, uio_last * PAGE_SIZE,
+ (pages_in_upl - uio_last) * PAGE_SIZE, UPL_ABORT_FREE_ON_EMPTY);
+ }
+
+ /*
+ * compute size to transfer this round, if io_req_size is
+ * still non-zero after this attempt, we'll loop around and
+ * set up for another I/O.
+ */
+ val_size = (uio_last * PAGE_SIZE) - start_offset;
+
+ if (val_size > max_size)
+ val_size = max_size;
+
+ if (val_size > io_req_size)
+ val_size = io_req_size;
+
+ if ((uio->uio_offset + val_size) > last_ioread_offset)
+ last_ioread_offset = uio->uio_offset + val_size;
+
+ if ((size_of_prefetch = (last_request_offset - last_ioread_offset)) && prefetch_enabled) {
+
+ if ((last_ioread_offset - (uio->uio_offset + val_size)) <= upl_size) {
+ /*
+ * if there's still I/O left to do for this request, and...
+ * we're not in hard throttle mode, and...
+ * we're close to using up the previous prefetch, then issue a
+ * new pre-fetch I/O... the I/O latency will overlap
+ * with the copying of the data
+ */
+ if (size_of_prefetch > max_rd_size)
+ size_of_prefetch = max_rd_size;
+
+ size_of_prefetch = cluster_read_prefetch(vp, last_ioread_offset, size_of_prefetch, filesize, callback, callback_arg, bflag);
+
+ last_ioread_offset += (off_t)(size_of_prefetch * PAGE_SIZE);
+
+ if (last_ioread_offset > last_request_offset)
+ last_ioread_offset = last_request_offset;
+ }
+
+ } else if ((uio->uio_offset + val_size) == last_request_offset) {
+ /*
+ * this transfer will finish this request, so...
+ * let's try to read ahead if we're in
+ * a sequential access pattern and we haven't
+ * explicitly disabled it
+ */
+ if (rd_ahead_enabled)
+ cluster_read_ahead(vp, &extent, filesize, rap, callback, callback_arg, bflag);
+
+ if (rap != NULL) {
+ if (extent.e_addr < rap->cl_lastr)
+ rap->cl_maxra = 0;
+ rap->cl_lastr = extent.e_addr;
+ }
+ }
+ if (iolock_inited == TRUE)
+ cluster_iostate_wait(&iostate, 0, "cluster_read_copy");
+
+ if (iostate.io_error)
+ error = iostate.io_error;
+ else {
+ u_int32_t io_requested;
+
+ io_requested = val_size;
+
+ retval = cluster_copy_upl_data(uio, upl, start_offset, (int *)&io_requested);
+
+ io_req_size -= (val_size - io_requested);
+ }
+ } else {
+ if (iolock_inited == TRUE)
+ cluster_iostate_wait(&iostate, 0, "cluster_read_copy");
+ }
+ if (start_pg < last_pg) {
+ /*
+ * compute the range of pages that we actually issued an I/O for
+ * and either commit them as valid if the I/O succeeded
+ * or abort them if the I/O failed or we're not supposed to
+ * keep them in the cache
+ */
+ io_size = (last_pg - start_pg) * PAGE_SIZE;
+
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 35)) | DBG_FUNC_START, upl, start_pg * PAGE_SIZE, io_size, error, 0);
+
+ if (error || (flags & IO_NOCACHE))
+ ubc_upl_abort_range(upl, start_pg * PAGE_SIZE, io_size,
+ UPL_ABORT_DUMP_PAGES | UPL_ABORT_FREE_ON_EMPTY);
+ else {
+ int commit_flags = UPL_COMMIT_CLEAR_DIRTY | UPL_COMMIT_FREE_ON_EMPTY;
+
+ if (take_reference)
+ commit_flags |= UPL_COMMIT_INACTIVATE;
+ else
+ commit_flags |= UPL_COMMIT_SPECULATE;
+
+ ubc_upl_commit_range(upl, start_pg * PAGE_SIZE, io_size, commit_flags);
+ }
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 35)) | DBG_FUNC_END, upl, start_pg * PAGE_SIZE, io_size, error, 0);
+ }
+ if ((last_pg - start_pg) < pages_in_upl) {
+ /*
+ * the set of pages that we issued an I/O for did not encompass
+ * the entire upl... so just release these without modifying
+ * their state
+ */
+ if (error)
+ ubc_upl_abort_range(upl, 0, upl_size, UPL_ABORT_FREE_ON_EMPTY);
+ else {
+
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 35)) | DBG_FUNC_START,
+ upl, -1, pages_in_upl - (last_pg - start_pg), 0, 0);
+
+ /*
+ * handle any valid pages at the beginning of
+ * the upl... release these appropriately
+ */
+ cluster_read_upl_release(upl, 0, start_pg, take_reference);
+
+ /*
+ * handle any valid pages immediately after the
+ * pages we issued I/O for... ... release these appropriately
+ */
+ cluster_read_upl_release(upl, last_pg, uio_last, take_reference);
+
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 35)) | DBG_FUNC_END, upl, -1, -1, 0, 0);
+ }
+ }
+ if (retval == 0)
+ retval = error;
+
+ if (io_req_size) {
+ if (cluster_is_throttled(vp)) {
+ /*
+ * we're in the throttle window, at the very least
+ * we want to limit the size of the I/O we're about
+ * to issue
+ */
+ rd_ahead_enabled = 0;
+ prefetch_enabled = 0;
+ max_rd_size = THROTTLE_MAX_IOSIZE;
+ } else {
+ if (max_rd_size == THROTTLE_MAX_IOSIZE) {
+ /*
+ * coming out of throttled state
+ */
+ if (policy != THROTTLE_LEVEL_TIER3 && policy != THROTTLE_LEVEL_TIER2) {
+ if (rap != NULL)
+ rd_ahead_enabled = 1;
+ prefetch_enabled = 1;
+ }
+ max_rd_size = max_prefetch;
+ last_ioread_offset = 0;
+ }
+ }
+ }
+ }
+ if (iolock_inited == TRUE) {
+ /*
+ * cluster_io returned an error after it
+ * had already issued some I/O. we need
+ * to wait for that I/O to complete before
+ * we can destroy the iostate mutex...
+ * 'retval' already contains the early error
+ * so no need to pick it up from iostate.io_error
+ */
+ cluster_iostate_wait(&iostate, 0, "cluster_read_copy");
+
+ lck_mtx_destroy(&iostate.io_mtxp, cl_mtx_grp);
+ }
+ if (rap != NULL) {
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 32)) | DBG_FUNC_END,
+ (int)uio->uio_offset, io_req_size, rap->cl_lastr, retval, 0);
+
+ lck_mtx_unlock(&rap->cl_lockr);
+ } else {
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 32)) | DBG_FUNC_END,
+ (int)uio->uio_offset, io_req_size, 0, retval, 0);
+ }
+
+ return (retval);
+}
+
+/*
+ * We don't want another read/write lock for every vnode in the system
+ * so we keep a hash of them here. There should never be very many of
+ * these around at any point in time.
+ */
+cl_direct_read_lock_t *cluster_lock_direct_read(vnode_t vp, lck_rw_type_t type)
+{
+ struct cl_direct_read_locks *head
+ = &cl_direct_read_locks[(uintptr_t)vp / sizeof(*vp)
+ % CL_DIRECT_READ_LOCK_BUCKETS];
+
+ struct cl_direct_read_lock *lck, *new_lck = NULL;
+
+ for (;;) {
+ lck_spin_lock(&cl_direct_read_spin_lock);
+
+ LIST_FOREACH(lck, head, chain) {
+ if (lck->vp == vp) {
+ ++lck->ref_count;
+ lck_spin_unlock(&cl_direct_read_spin_lock);
+ if (new_lck) {
+ // Someone beat us to it, ditch the allocation
+ lck_rw_destroy(&new_lck->rw_lock, cl_mtx_grp);
+ FREE(new_lck, M_TEMP);
+ }
+ lck_rw_lock(&lck->rw_lock, type);
+ return lck;
+ }
+ }
+
+ if (new_lck) {
+ // Use the lock we allocated
+ LIST_INSERT_HEAD(head, new_lck, chain);
+ lck_spin_unlock(&cl_direct_read_spin_lock);
+ lck_rw_lock(&new_lck->rw_lock, type);
+ return new_lck;
+ }
+
+ lck_spin_unlock(&cl_direct_read_spin_lock);
+
+ // Allocate a new lock
+ MALLOC(new_lck, cl_direct_read_lock_t *, sizeof(*new_lck),
+ M_TEMP, M_WAITOK);
+ lck_rw_init(&new_lck->rw_lock, cl_mtx_grp, cl_mtx_attr);
+ new_lck->vp = vp;
+ new_lck->ref_count = 1;
+
+ // Got to go round again
+ }
+}
+
+void cluster_unlock_direct_read(cl_direct_read_lock_t *lck)
+{
+ lck_rw_done(&lck->rw_lock);
+
+ lck_spin_lock(&cl_direct_read_spin_lock);
+ if (lck->ref_count == 1) {
+ LIST_REMOVE(lck, chain);
+ lck_spin_unlock(&cl_direct_read_spin_lock);
+ lck_rw_destroy(&lck->rw_lock, cl_mtx_grp);
+ FREE(lck, M_TEMP);
+ } else {
+ --lck->ref_count;
+ lck_spin_unlock(&cl_direct_read_spin_lock);
+ }
+}
+
+static int
+cluster_read_direct(vnode_t vp, struct uio *uio, off_t filesize, int *read_type, u_int32_t *read_length,
+ int flags, int (*callback)(buf_t, void *), void *callback_arg)
+{
+ upl_t upl;
+ upl_page_info_t *pl;
+ off_t max_io_size;
+ vm_offset_t upl_offset, vector_upl_offset = 0;
+ upl_size_t upl_size, vector_upl_size = 0;
+ vm_size_t upl_needed_size;
+ unsigned int pages_in_pl;
+ upl_control_flags_t upl_flags;
+ kern_return_t kret;
+ unsigned int i;
+ int force_data_sync;
+ int retval = 0;
+ int no_zero_fill = 0;
+ int io_flag = 0;
+ int misaligned = 0;
+ struct clios iostate;
+ user_addr_t iov_base;
+ u_int32_t io_req_size;
+ u_int32_t offset_in_file;
+ u_int32_t offset_in_iovbase;
+ u_int32_t io_size;
+ u_int32_t io_min;
+ u_int32_t xsize;
+ u_int32_t devblocksize;
+ u_int32_t mem_alignment_mask;
+ u_int32_t max_upl_size;
+ u_int32_t max_rd_size;
+ u_int32_t max_rd_ahead;
+ u_int32_t max_vector_size;
+ boolean_t strict_uncached_IO = FALSE;
+ boolean_t io_throttled = FALSE;
+
+ u_int32_t vector_upl_iosize = 0;
+ int issueVectorUPL = 0,useVectorUPL = (uio->uio_iovcnt > 1);
+ off_t v_upl_uio_offset = 0;
+ int vector_upl_index=0;
+ upl_t vector_upl = NULL;
+ cl_direct_read_lock_t *lock = NULL;
+
+ user_addr_t orig_iov_base = 0;
+ user_addr_t last_iov_base = 0;
+ user_addr_t next_iov_base = 0;
+
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 70)) | DBG_FUNC_START,
+ (int)uio->uio_offset, (int)filesize, *read_type, *read_length, 0);
+
+ max_upl_size = cluster_max_io_size(vp->v_mount, CL_READ);
+
+ max_rd_size = max_upl_size;
+ max_rd_ahead = max_rd_size * IO_SCALE(vp, 2);
+
+ io_flag = CL_COMMIT | CL_READ | CL_ASYNC | CL_NOZERO | CL_DIRECT_IO;
+
+ if (flags & IO_PASSIVE)
+ io_flag |= CL_PASSIVE;
+
+ if (flags & IO_ENCRYPTED) {
+ io_flag |= CL_RAW_ENCRYPTED;
+ }
+
+ if (flags & IO_NOCACHE) {
+ io_flag |= CL_NOCACHE;
+ }
+
+ if (flags & IO_SKIP_ENCRYPTION)
+ io_flag |= CL_ENCRYPTED;
+
+ iostate.io_completed = 0;
+ iostate.io_issued = 0;
+ iostate.io_error = 0;
+ iostate.io_wanted = 0;
+
+ lck_mtx_init(&iostate.io_mtxp, cl_mtx_grp, cl_mtx_attr);
+
+ devblocksize = (u_int32_t)vp->v_mount->mnt_devblocksize;
+ mem_alignment_mask = (u_int32_t)vp->v_mount->mnt_alignmentmask;
+
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 70)) | DBG_FUNC_NONE,
+ (int)devblocksize, (int)mem_alignment_mask, 0, 0, 0);
+
+ if (devblocksize == 1) {
+ /*
+ * the AFP client advertises a devblocksize of 1
+ * however, its BLOCKMAP routine maps to physical
+ * blocks that are PAGE_SIZE in size...
+ * therefore we can't ask for I/Os that aren't page aligned
+ * or aren't multiples of PAGE_SIZE in size
+ * by setting devblocksize to PAGE_SIZE, we re-instate
+ * the old behavior we had before the mem_alignment_mask
+ * changes went in...
+ */
+ devblocksize = PAGE_SIZE;
+ }
+
+ strict_uncached_IO = ubc_strict_uncached_IO(vp);
+
+ orig_iov_base = uio_curriovbase(uio);
+ last_iov_base = orig_iov_base;
+
+next_dread:
+ io_req_size = *read_length;
+ iov_base = uio_curriovbase(uio);
+
+ offset_in_file = (u_int32_t)uio->uio_offset & (devblocksize - 1);
+ offset_in_iovbase = (u_int32_t)iov_base & mem_alignment_mask;
+
+ if (offset_in_file || offset_in_iovbase) {
+ /*
+ * one of the 2 important offsets is misaligned
+ * so fire an I/O through the cache for this entire vector
+ */
+ misaligned = 1;
+ }
+ if (iov_base & (devblocksize - 1)) {
+ /*
+ * the offset in memory must be on a device block boundary
+ * so that we can guarantee that we can generate an
+ * I/O that ends on a page boundary in cluster_io
+ */
+ misaligned = 1;
+ }
+
+ max_io_size = filesize - uio->uio_offset;
+
+ /*
+ * The user must request IO in aligned chunks. If the
+ * offset into the file is bad, or the userland pointer
+ * is non-aligned, then we cannot service the encrypted IO request.
+ */
+ if (flags & IO_ENCRYPTED) {
+ if (misaligned || (io_req_size & (devblocksize - 1)))
+ retval = EINVAL;
+
+ max_io_size = roundup(max_io_size, devblocksize);
+ }
+
+ if ((off_t)io_req_size > max_io_size)
+ io_req_size = max_io_size;
+
+ /*
+ * When we get to this point, we know...
+ * -- the offset into the file is on a devblocksize boundary
+ */
+
+ while (io_req_size && retval == 0) {
+ u_int32_t io_start;
+
+ if (cluster_is_throttled(vp)) {
+ /*
+ * we're in the throttle window, at the very least
+ * we want to limit the size of the I/O we're about
+ * to issue
+ */
+ max_rd_size = THROTTLE_MAX_IOSIZE;
+ max_rd_ahead = THROTTLE_MAX_IOSIZE - 1;
+ max_vector_size = THROTTLE_MAX_IOSIZE;
+ } else {
+ max_rd_size = max_upl_size;
+ max_rd_ahead = max_rd_size * IO_SCALE(vp, 2);
+ max_vector_size = MAX_VECTOR_UPL_SIZE;
+ }
+ io_start = io_size = io_req_size;
+
+ /*
+ * First look for pages already in the cache
+ * and move them to user space. But only do this
+ * check if we are not retrieving encrypted data directly
+ * from the filesystem; those blocks should never
+ * be in the UBC.
+ *
+ * cluster_copy_ubc_data returns the resid
+ * in io_size
+ */
+ if ((strict_uncached_IO == FALSE) && ((flags & IO_ENCRYPTED) == 0)) {
+ retval = cluster_copy_ubc_data_internal(vp, uio, (int *)&io_size, 0, 0);
+ }
+ /*
+ * calculate the number of bytes actually copied
+ * starting size - residual
+ */
+ xsize = io_start - io_size;
+
+ io_req_size -= xsize;
+
+ if(useVectorUPL && (xsize || (iov_base & PAGE_MASK))) {
+ /*
+ * We found something in the cache or we have an iov_base that's not
+ * page-aligned.
+ *
+ * Issue all I/O's that have been collected within this Vectored UPL.
+ */
+ if(vector_upl_index) {
+ retval = vector_cluster_io(vp, vector_upl, vector_upl_offset, v_upl_uio_offset, vector_upl_iosize, io_flag, (buf_t)NULL, &iostate, callback, callback_arg);
+ reset_vector_run_state();
+ }
+
+ if(xsize)
+ useVectorUPL = 0;
+
+ /*
+ * After this point, if we are using the Vector UPL path and the base is
+ * not page-aligned then the UPL with that base will be the first in the vector UPL.
+ */
+ }
+
+ /*
+ * check to see if we are finished with this request.
+ *
+ * If we satisfied this IO already, then io_req_size will be 0.
+ * Otherwise, see if the IO was mis-aligned and needs to go through
+ * the UBC to deal with the 'tail'.
+ *
+ */
+ if (io_req_size == 0 || (misaligned)) {
+ /*
+ * see if there's another uio vector to
+ * process that's of type IO_DIRECT
+ *
+ * break out of while loop to get there
+ */
+ break;
+ }
+ /*
+ * assume the request ends on a device block boundary
+ */
+ io_min = devblocksize;
+
+ /*
+ * we can handle I/O's in multiples of the device block size
+ * however, if io_size isn't a multiple of devblocksize we
+ * want to clip it back to the nearest page boundary since
+ * we are going to have to go through cluster_read_copy to
+ * deal with the 'overhang'... by clipping it to a PAGE_SIZE
+ * multiple, we avoid asking the drive for the same physical
+ * blocks twice.. once for the partial page at the end of the
+ * request and a 2nd time for the page we read into the cache
+ * (which overlaps the end of the direct read) in order to
+ * get at the overhang bytes
+ */
+ if (io_size & (devblocksize - 1)) {
+ assert(!(flags & IO_ENCRYPTED));
+ /*
+ * Clip the request to the previous page size boundary
+ * since request does NOT end on a device block boundary
+ */
+ io_size &= ~PAGE_MASK;
+ io_min = PAGE_SIZE;
+ }
+ if (retval || io_size < io_min) {
+ /*
+ * either an error or we only have the tail left to
+ * complete via the copy path...
+ * we may have already spun some portion of this request
+ * off as async requests... we need to wait for the I/O
+ * to complete before returning
+ */
+ goto wait_for_dreads;
+ }
+
+ /*
+ * Don't re-check the UBC data if we are looking for uncached IO
+ * or asking for encrypted blocks.
+ */
+ if ((strict_uncached_IO == FALSE) && ((flags & IO_ENCRYPTED) == 0)) {
+
+ if ((xsize = io_size) > max_rd_size)
+ xsize = max_rd_size;
+
+ io_size = 0;
+
+ if (!lock) {
+ /*
+ * We hold a lock here between the time we check the
+ * cache and the time we issue I/O. This saves us
+ * from having to lock the pages in the cache. Not
+ * all clients will care about this lock but some
+ * clients may want to guarantee stability between
+ * here and when the I/O is issued in which case they
+ * will take the lock exclusively.
+ */
+ lock = cluster_lock_direct_read(vp, LCK_RW_TYPE_SHARED);
+ }
+
+ ubc_range_op(vp, uio->uio_offset, uio->uio_offset + xsize, UPL_ROP_ABSENT, (int *)&io_size);
+
+ if (io_size == 0) {
+ /*
+ * a page must have just come into the cache
+ * since the first page in this range is no
+ * longer absent, go back and re-evaluate
+ */
+ continue;
+ }
+ }
+ if ( (flags & IO_RETURN_ON_THROTTLE) ) {
+ if (cluster_is_throttled(vp) == THROTTLE_NOW) {
+ if ( !cluster_io_present_in_BC(vp, uio->uio_offset)) {
+ /*
+ * we're in the throttle window and at least 1 I/O
+ * has already been issued by a throttleable thread
+ * in this window, so return with EAGAIN to indicate
+ * to the FS issuing the cluster_read call that it
+ * should now throttle after dropping any locks
+ */
+ throttle_info_update_by_mount(vp->v_mount);
+
+ io_throttled = TRUE;
+ goto wait_for_dreads;
+ }
+ }
+ }
+ if (io_size > max_rd_size)
+ io_size = max_rd_size;
+
+ iov_base = uio_curriovbase(uio);
+
+ upl_offset = (vm_offset_t)((u_int32_t)iov_base & PAGE_MASK);
+ upl_needed_size = (upl_offset + io_size + (PAGE_SIZE -1)) & ~PAGE_MASK;
+
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 72)) | DBG_FUNC_START,
+ (int)upl_offset, upl_needed_size, (int)iov_base, io_size, 0);
+
+ if (upl_offset == 0 && ((io_size & PAGE_MASK) == 0))
+ no_zero_fill = 1;
+ else
+ no_zero_fill = 0;
+
+ vm_map_t map = UIO_SEG_IS_USER_SPACE(uio->uio_segflg) ? current_map() : kernel_map;
+ for (force_data_sync = 0; force_data_sync < 3; force_data_sync++) {
+ pages_in_pl = 0;
+ upl_size = upl_needed_size;
+ upl_flags = UPL_FILE_IO | UPL_NO_SYNC | UPL_SET_INTERNAL | UPL_SET_LITE | UPL_SET_IO_WIRE
+ | UPL_MEMORY_TAG_MAKE(VM_KERN_MEMORY_FILE);
+ if (no_zero_fill)
+ upl_flags |= UPL_NOZEROFILL;
+ if (force_data_sync)
+ upl_flags |= UPL_FORCE_DATA_SYNC;
+
+ kret = vm_map_create_upl(map,
+ (vm_map_offset_t)(iov_base & ~((user_addr_t)PAGE_MASK)),
+ &upl_size, &upl, NULL, &pages_in_pl, &upl_flags);
+
+ if (kret != KERN_SUCCESS) {
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 72)) | DBG_FUNC_END,
+ (int)upl_offset, upl_size, io_size, kret, 0);
+ /*
+ * failed to get pagelist
+ *
+ * we may have already spun some portion of this request
+ * off as async requests... we need to wait for the I/O
+ * to complete before returning
+ */
+ goto wait_for_dreads;
+ }
+ pages_in_pl = upl_size / PAGE_SIZE;
+ pl = UPL_GET_INTERNAL_PAGE_LIST(upl);
+
+ for (i = 0; i < pages_in_pl; i++) {
+ if (!upl_page_present(pl, i))
+ break;
+ }
+ if (i == pages_in_pl)
+ break;
+
+ ubc_upl_abort(upl, 0);
+ }
+ if (force_data_sync >= 3) {
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 72)) | DBG_FUNC_END,
+ (int)upl_offset, upl_size, io_size, kret, 0);
+
+ goto wait_for_dreads;
+ }
+ /*
+ * Consider the possibility that upl_size wasn't satisfied.
+ */
+ if (upl_size < upl_needed_size) {
+ if (upl_size && upl_offset == 0)
+ io_size = upl_size;
+ else
+ io_size = 0;
+ }
+ if (io_size == 0) {
+ ubc_upl_abort(upl, 0);
+ goto wait_for_dreads;
+ }
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 72)) | DBG_FUNC_END,
+ (int)upl_offset, upl_size, io_size, kret, 0);
+
+ if(useVectorUPL) {
+ vm_offset_t end_off = ((iov_base + io_size) & PAGE_MASK);
+ if(end_off)
+ issueVectorUPL = 1;
+ /*
+ * After this point, if we are using a vector UPL, then
+ * either all the UPL elements end on a page boundary OR
+ * this UPL is the last element because it does not end
+ * on a page boundary.
+ */
+ }
+
+ /*
+ * request asynchronously so that we can overlap
+ * the preparation of the next I/O
+ * if there are already too many outstanding reads
+ * wait until some have completed before issuing the next read
+ */
+ cluster_iostate_wait(&iostate, max_rd_ahead, "cluster_read_direct");
+
+ if (iostate.io_error) {
+ /*
+ * one of the earlier reads we issued ran into a hard error
+ * don't issue any more reads, cleanup the UPL
+ * that was just created but not used, then
+ * go wait for any other reads to complete before
+ * returning the error to the caller
+ */
+ ubc_upl_abort(upl, 0);
+
+ goto wait_for_dreads;
+ }
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 73)) | DBG_FUNC_START,
+ upl, (int)upl_offset, (int)uio->uio_offset, io_size, 0);
+
+ if(!useVectorUPL) {
+ if (no_zero_fill)
+ io_flag &= ~CL_PRESERVE;
+ else
+ io_flag |= CL_PRESERVE;
+
+ retval = cluster_io(vp, upl, upl_offset, uio->uio_offset, io_size, io_flag, (buf_t)NULL, &iostate, callback, callback_arg);
+
+ } else {
+
+ if(!vector_upl_index) {
+ vector_upl = vector_upl_create(upl_offset);
+ v_upl_uio_offset = uio->uio_offset;
+ vector_upl_offset = upl_offset;
+ }
+
+ vector_upl_set_subupl(vector_upl,upl, upl_size);
+ vector_upl_set_iostate(vector_upl, upl, vector_upl_size, upl_size);
+ vector_upl_index++;
+ vector_upl_size += upl_size;
+ vector_upl_iosize += io_size;
+
+ if(issueVectorUPL || vector_upl_index == MAX_VECTOR_UPL_ELEMENTS || vector_upl_size >= max_vector_size) {
+ retval = vector_cluster_io(vp, vector_upl, vector_upl_offset, v_upl_uio_offset, vector_upl_iosize, io_flag, (buf_t)NULL, &iostate, callback, callback_arg);
+ reset_vector_run_state();
+ }
+ }
+ last_iov_base = iov_base + io_size;
+
+ if (lock) {
+ // We don't need to wait for the I/O to complete
+ cluster_unlock_direct_read(lock);
+ lock = NULL;
+ }
+
+ /*
+ * update the uio structure
+ */
+ if ((flags & IO_ENCRYPTED) && (max_io_size < io_size)) {
+ uio_update(uio, (user_size_t)max_io_size);
+ }
+ else {
+ uio_update(uio, (user_size_t)io_size);
+ }
+
+ io_req_size -= io_size;
+
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 73)) | DBG_FUNC_END,
+ upl, (int)uio->uio_offset, io_req_size, retval, 0);
+
+ } /* end while */
+
+ if (retval == 0 && iostate.io_error == 0 && io_req_size == 0 && uio->uio_offset < filesize) {
+
+ retval = cluster_io_type(uio, read_type, read_length, 0);
+
+ if (retval == 0 && *read_type == IO_DIRECT) {
+
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 70)) | DBG_FUNC_NONE,
+ (int)uio->uio_offset, (int)filesize, *read_type, *read_length, 0);
+
+ goto next_dread;
+ }
+ }
+
+wait_for_dreads:
+
+ if(retval == 0 && iostate.io_error == 0 && useVectorUPL && vector_upl_index) {
+ retval = vector_cluster_io(vp, vector_upl, vector_upl_offset, v_upl_uio_offset, vector_upl_iosize, io_flag, (buf_t)NULL, &iostate, callback, callback_arg);
+ reset_vector_run_state();
+ }
+
+ // We don't need to wait for the I/O to complete
+ if (lock)
+ cluster_unlock_direct_read(lock);
+
+ /*
+ * make sure all async reads that are part of this stream
+ * have completed before we return
+ */
+ cluster_iostate_wait(&iostate, 0, "cluster_read_direct");
+
+ if (iostate.io_error)
+ retval = iostate.io_error;
+
+ lck_mtx_destroy(&iostate.io_mtxp, cl_mtx_grp);
+
+ if (io_throttled == TRUE && retval == 0)
+ retval = EAGAIN;
+
+ for (next_iov_base = orig_iov_base; next_iov_base < last_iov_base; next_iov_base += PAGE_SIZE) {
+ /*
+ * This is specifically done for pmap accounting purposes.
+ * vm_pre_fault() will call vm_fault() to enter the page into
+ * the pmap if there isn't _a_ physical page for that VA already.
+ */
+ vm_pre_fault(vm_map_trunc_page(next_iov_base, PAGE_MASK));
+ }
+
+ if (io_req_size && retval == 0) {
+ /*
+ * we couldn't handle the tail of this request in DIRECT mode
+ * so fire it through the copy path
+ */
+ retval = cluster_read_copy(vp, uio, io_req_size, filesize, flags, callback, callback_arg);
+
+ *read_type = IO_UNKNOWN;
+ }
+ KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 70)) | DBG_FUNC_END,
+ (int)uio->uio_offset, (int)uio_resid(uio), io_req_size, retval, 0);
+
+ return (retval);
+}
+
+