1 /*
2 * Copyright (c) 2000-2020 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
29 /*
30 * Copyright (c) 1993
31 * The Regents of the University of California. All rights reserved.
32 *
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
35 * are met:
36 * 1. Redistributions of source code must retain the above copyright
37 * notice, this list of conditions and the following disclaimer.
38 * 2. Redistributions in binary form must reproduce the above copyright
39 * notice, this list of conditions and the following disclaimer in the
40 * documentation and/or other materials provided with the distribution.
41 * 3. All advertising materials mentioning features or use of this software
42 * must display the following acknowledgement:
43 * This product includes software developed by the University of
44 * California, Berkeley and its contributors.
45 * 4. Neither the name of the University nor the names of its contributors
46 * may be used to endorse or promote products derived from this software
47 * without specific prior written permission.
48 *
49 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59 * SUCH DAMAGE.
60 *
61 * @(#)vfs_cluster.c 8.10 (Berkeley) 3/28/95
62 */
63
64 #include <sys/param.h>
65 #include <sys/proc_internal.h>
66 #include <sys/buf_internal.h>
67 #include <sys/mount_internal.h>
68 #include <sys/vnode_internal.h>
69 #include <sys/trace.h>
70 #include <kern/kalloc.h>
71 #include <sys/time.h>
72 #include <sys/kernel.h>
73 #include <sys/resourcevar.h>
74 #include <miscfs/specfs/specdev.h>
75 #include <sys/uio_internal.h>
76 #include <libkern/libkern.h>
77 #include <machine/machine_routines.h>
78 #include <machine/smp.h>
79
80 #include <sys/ubc_internal.h>
81 #include <vm/vnode_pager.h>
82 #include <vm/vm_upl.h>
83
84 #include <mach/mach_types.h>
85 #include <mach/memory_object_types.h>
86 #include <mach/vm_map.h>
87 #include <mach/upl.h>
88 #include <mach/thread_info.h>
89 #include <kern/task.h>
90 #include <kern/policy_internal.h>
91 #include <kern/thread.h>
92
93 #include <vm/vm_kern_xnu.h>
94 #include <vm/vm_map_xnu.h>
95 #include <vm/vm_pageout_xnu.h>
96 #include <vm/vm_fault.h>
97 #include <vm/vm_ubc.h>
98
99 #include <sys/kdebug.h>
100 #include <sys/kdebug_triage.h>
101 #include <libkern/OSAtomic.h>
102
103 #include <sys/sdt.h>
104
105 #include <stdbool.h>
106
107 #include <vfs/vfs_disk_conditioner.h>
108
109 #if 0
110 #undef KERNEL_DEBUG
111 #define KERNEL_DEBUG KERNEL_DEBUG_CONSTANT
112 #endif
113
114
115 #define CL_READ 0x01
116 #define CL_WRITE 0x02
117 #define CL_ASYNC 0x04
118 #define CL_COMMIT 0x08
119 #define CL_PAGEOUT 0x10
120 #define CL_AGE 0x20
121 #define CL_NOZERO 0x40
122 #define CL_PAGEIN 0x80
123 #define CL_DEV_MEMORY 0x100
124 #define CL_PRESERVE 0x200
125 #define CL_THROTTLE 0x400
126 #define CL_KEEPCACHED 0x800
127 #define CL_DIRECT_IO 0x1000
128 #define CL_PASSIVE 0x2000
129 #define CL_IOSTREAMING 0x4000
130 #define CL_CLOSE 0x8000
131 #define CL_ENCRYPTED 0x10000
132 #define CL_RAW_ENCRYPTED 0x20000
133 #define CL_NOCACHE 0x40000
134 #define CL_DIRECT_IO_FSBLKSZ 0x80000
135
136 #define MAX_VECTOR_UPL_SIZE (2 * MAX_UPL_SIZE_BYTES)
137
138 #define CLUSTER_IO_WAITING ((buf_t)1)
139
140 extern void vector_upl_set_iostate(upl_t, upl_t, vm_offset_t, upl_size_t);
141
142 struct clios {
143 lck_mtx_t io_mtxp;
144 u_int io_completed; /* amount of io that has currently completed */
145 u_int io_issued; /* amount of io that was successfully issued */
146 int io_error; /* error code of first error encountered */
147 int io_wanted; /* someone is sleeping waiting for a change in state */
148 };
149
150 struct cl_direct_read_lock {
151 LIST_ENTRY(cl_direct_read_lock) chain;
152 int32_t ref_count;
153 vnode_t vp;
154 lck_rw_t rw_lock;
155 };
156
157 #define CL_DIRECT_READ_LOCK_BUCKETS 61
158
159 static LIST_HEAD(cl_direct_read_locks, cl_direct_read_lock)
160 cl_direct_read_locks[CL_DIRECT_READ_LOCK_BUCKETS];
161
162 static LCK_GRP_DECLARE(cl_mtx_grp, "cluster I/O");
163 static LCK_MTX_DECLARE(cl_transaction_mtxp, &cl_mtx_grp);
164 static LCK_SPIN_DECLARE(cl_direct_read_spin_lock, &cl_mtx_grp);
165
166 static ZONE_DEFINE(cl_rd_zone, "cluster_read",
167 sizeof(struct cl_readahead), ZC_ZFREE_CLEARMEM);
168
169 static ZONE_DEFINE(cl_wr_zone, "cluster_write",
170 sizeof(struct cl_writebehind), ZC_ZFREE_CLEARMEM);
171
172 #define IO_UNKNOWN 0
173 #define IO_DIRECT 1
174 #define IO_CONTIG 2
175 #define IO_COPY 3
176
177 #define PUSH_DELAY 0x01
178 #define PUSH_ALL 0x02
179 #define PUSH_SYNC 0x04
180
181
182 static void cluster_EOT(buf_t cbp_head, buf_t cbp_tail, int zero_offset, size_t verify_block_size);
183 static void cluster_wait_IO(buf_t cbp_head, int async);
184 static void cluster_complete_transaction(buf_t *cbp_head, void *callback_arg, int *retval, int flags, int needwait);
185
186 static int cluster_io_type(struct uio *uio, int *io_type, u_int32_t *io_length, u_int32_t min_length);
187
188 static int cluster_io(vnode_t vp, upl_t upl, vm_offset_t upl_offset, off_t f_offset, int non_rounded_size,
189 int flags, buf_t real_bp, struct clios *iostate, int (*)(buf_t, void *), void *callback_arg);
190 static void cluster_iodone_verify_continue(void);
191 static int cluster_iodone(buf_t bp, void *callback_arg);
192 static int cluster_iodone_finish(buf_t cbp_head, void *callback_arg);
193 static int cluster_ioerror(upl_t upl, int upl_offset, int abort_size, int error, int io_flags, vnode_t vp);
194 static int cluster_is_throttled(vnode_t vp);
195
196 static void cluster_iostate_wait(struct clios *iostate, u_int target, const char *wait_name);
197
198 static void cluster_syncup(vnode_t vp, off_t newEOF, int (*)(buf_t, void *), void *callback_arg, int flags);
199
200 static void cluster_read_upl_release(upl_t upl, int start_pg, int last_pg, int take_reference);
201 static int cluster_copy_ubc_data_internal(vnode_t vp, struct uio *uio, int *io_resid, int mark_dirty, int take_reference);
202
203 static int cluster_read_copy(vnode_t vp, struct uio *uio, u_int32_t io_req_size, off_t filesize, int flags,
204 int (*)(buf_t, void *), void *callback_arg) __attribute__((noinline));
205 static int cluster_read_direct(vnode_t vp, struct uio *uio, off_t filesize, int *read_type, u_int32_t *read_length,
206 int flags, int (*)(buf_t, void *), void *callback_arg) __attribute__((noinline));
207 static int cluster_read_contig(vnode_t vp, struct uio *uio, off_t filesize, int *read_type, u_int32_t *read_length,
208 int (*)(buf_t, void *), void *callback_arg, int flags) __attribute__((noinline));
209
210 static int cluster_write_copy(vnode_t vp, struct uio *uio, u_int32_t io_req_size, off_t oldEOF, off_t newEOF,
211 off_t headOff, off_t tailOff, int flags, int (*)(buf_t, void *), void *callback_arg) __attribute__((noinline));
212 static int cluster_write_direct(vnode_t vp, struct uio *uio, off_t oldEOF, off_t newEOF, int *write_type, u_int32_t *write_length,
213 int flags, int (*callback)(buf_t, void *), void *callback_arg, uint32_t min_io_size) __attribute__((noinline));
214 static int cluster_write_contig(vnode_t vp, struct uio *uio, off_t newEOF,
215 int *write_type, u_int32_t *write_length, int (*)(buf_t, void *), void *callback_arg, int bflag) __attribute__((noinline));
216
217 static void cluster_update_state_internal(vnode_t vp, struct cl_extent *cl, int flags, boolean_t defer_writes, boolean_t *first_pass,
218 off_t write_off, int write_cnt, off_t newEOF, int (*callback)(buf_t, void *), void *callback_arg, boolean_t vm_initiated);
219
220 static int cluster_align_phys_io(vnode_t vp, struct uio *uio, addr64_t usr_paddr, u_int32_t xsize, int flags, int (*)(buf_t, void *), void *callback_arg);
221
222 static int cluster_read_prefetch(vnode_t vp, off_t f_offset, u_int size, off_t filesize, int (*callback)(buf_t, void *), void *callback_arg, int bflag);
223 static void cluster_read_ahead(vnode_t vp, struct cl_extent *extent, off_t filesize, struct cl_readahead *ra,
224 int (*callback)(buf_t, void *), void *callback_arg, int bflag);
225
226 static int cluster_push_now(vnode_t vp, struct cl_extent *, off_t EOF, int flags, int (*)(buf_t, void *), void *callback_arg, boolean_t vm_ioitiated);
227
228 static int cluster_try_push(struct cl_writebehind *, vnode_t vp, off_t EOF, int push_flag, int flags, int (*)(buf_t, void *),
229 void *callback_arg, int *err, boolean_t vm_initiated);
230
231 static int sparse_cluster_switch(struct cl_writebehind *, vnode_t vp, off_t EOF, int (*)(buf_t, void *), void *callback_arg, boolean_t vm_initiated);
232 static int sparse_cluster_push(struct cl_writebehind *, void **cmapp, vnode_t vp, off_t EOF, int push_flag,
233 int io_flags, int (*)(buf_t, void *), void *callback_arg, boolean_t vm_initiated);
234 static int sparse_cluster_add(struct cl_writebehind *, void **cmapp, vnode_t vp, struct cl_extent *, off_t EOF,
235 int (*)(buf_t, void *), void *callback_arg, boolean_t vm_initiated);
236
237 static kern_return_t vfs_drt_mark_pages(void **cmapp, off_t offset, u_int length, u_int *setcountp);
238 static kern_return_t vfs_drt_get_cluster(void **cmapp, off_t *offsetp, u_int *lengthp);
239 static kern_return_t vfs_drt_control(void **cmapp, int op_type);
240 static kern_return_t vfs_get_scmap_push_behavior_internal(void **cmapp, int *push_flag);
241
242
243 /*
244 * For throttled IO to check whether
245 * a block is cached by the boot cache
246 * and thus it can avoid delaying the IO.
247 *
248 * bootcache_contains_block is initially
249 * NULL. The BootCache will set it while
250 * the cache is active and clear it when
251 * the cache is jettisoned.
252 *
253 * Returns 0 if the block is not
254 * contained in the cache, 1 if it is
255 * contained.
256 *
257 * The function pointer remains valid
258 * after the cache has been evicted even
259 * if bootcache_contains_block has been
260 * cleared.
261 *
262 * See rdar://9974130 The new throttling mechanism breaks the boot cache for throttled IOs
263 */
264 int (*bootcache_contains_block)(dev_t device, u_int64_t blkno) = NULL;
265
266
267 /*
268 * limit the internal I/O size so that we
269 * can represent it in a 32 bit int
270 */
271 #define MAX_IO_REQUEST_SIZE (1024 * 1024 * 512)
272 #define MAX_IO_CONTIG_SIZE MAX_UPL_SIZE_BYTES
273 #define MAX_VECTS 16
274 /*
275 * The MIN_DIRECT_WRITE_SIZE governs how much I/O should be issued before we consider
276 * allowing the caller to bypass the buffer cache. For small I/Os (less than 16k),
277 * we have not historically allowed the write to bypass the UBC.
278 */
279 #define MIN_DIRECT_WRITE_SIZE (16384)
280
281 #define WRITE_THROTTLE 6
282 #define WRITE_THROTTLE_SSD 2
283 #define WRITE_BEHIND 1
284 #define WRITE_BEHIND_SSD 1
285
286 #if !defined(XNU_TARGET_OS_OSX)
287 #define PREFETCH 1
288 #define PREFETCH_SSD 1
289 uint32_t speculative_prefetch_max = (2048 * 1024); /* maximum bytes in a specluative read-ahead */
290 uint32_t speculative_prefetch_max_iosize = (512 * 1024); /* maximum I/O size to use in a specluative read-ahead */
291 #else /* XNU_TARGET_OS_OSX */
292 #define PREFETCH 3
293 #define PREFETCH_SSD 2
294 uint32_t speculative_prefetch_max = (MAX_UPL_SIZE_BYTES * 3); /* maximum bytes in a specluative read-ahead */
295 uint32_t speculative_prefetch_max_iosize = (512 * 1024); /* maximum I/O size to use in a specluative read-ahead on SSDs*/
296 #endif /* ! XNU_TARGET_OS_OSX */
297
298 /* maximum bytes for read-ahead */
299 uint32_t prefetch_max = (1024 * 1024 * 1024);
300 /* maximum bytes for outstanding reads */
301 uint32_t overlapping_read_max = (1024 * 1024 * 1024);
302 /* maximum bytes for outstanding writes */
303 uint32_t overlapping_write_max = (1024 * 1024 * 1024);
304
305 #define IO_SCALE(vp, base) (vp->v_mount->mnt_ioscale * (base))
306 #define MAX_CLUSTER_SIZE(vp) (cluster_max_io_size(vp->v_mount, CL_WRITE))
307
308 int speculative_reads_disabled = 0;
309
310 /*
311 * throttle the number of async writes that
312 * can be outstanding on a single vnode
313 * before we issue a synchronous write
314 */
315 #define THROTTLE_MAXCNT 0
316
317 uint32_t throttle_max_iosize = (128 * 1024);
318
319 #define THROTTLE_MAX_IOSIZE (throttle_max_iosize)
320
321 SYSCTL_INT(_debug, OID_AUTO, lowpri_throttle_max_iosize, CTLFLAG_RW | CTLFLAG_LOCKED, &throttle_max_iosize, 0, "");
322
323 struct verify_buf {
324 TAILQ_ENTRY(verify_buf) vb_entry;
325 buf_t vb_cbp;
326 void* vb_callback_arg;
327 int32_t vb_whichq;
328 };
329
330 TAILQ_HEAD(, verify_buf) verify_free_head;
331 TAILQ_HEAD(, verify_buf) verify_work_head;
332
333 #define MAX_VERIFY_THREADS 4
334 #define MAX_REQUESTS_PER_THREAD 2
335
336 static struct verify_buf verify_bufs[MAX_VERIFY_THREADS * MAX_REQUESTS_PER_THREAD];
337 /*
338 * Each thread needs to check if the item at the head of the queue has a UPL
339 * pointer that is any of the threads are currently operating on.
340 * slot 0 is for the io completion thread to do the request inline if there are no free
341 * queue slots.
342 */
343 static int verify_in_flight = 0;
344
345 #if defined(XNU_TARGET_OS_IOS)
346 #define NUM_DEFAULT_THREADS 2
347 #elif defined(XNU_TARGET_OS_OSX)
348 #define NUM_DEFAULT_THREADS 4
349 #else
350 #define NUM_DEFAULT_THREADS 0
351 #endif
352
353 static TUNABLE(uint32_t, num_verify_threads, "num_verify_threads", NUM_DEFAULT_THREADS);
354 static uint32_t cluster_verify_threads = 0; /* will be launched as needed upto num_verify_threads */
355
356 #if __AMP__
357 static TUNABLE(uint32_t, ecore_verify_threads, "ecore_verify_threads", false);
358 #endif /* __AMP__ */
359
360 static void
cluster_verify_init(void)361 cluster_verify_init(void)
362 {
363 TAILQ_INIT(&verify_free_head);
364 TAILQ_INIT(&verify_work_head);
365
366 if (num_verify_threads > MAX_VERIFY_THREADS) {
367 num_verify_threads = MAX_VERIFY_THREADS;
368 }
369
370 for (int i = 0; i < num_verify_threads * MAX_REQUESTS_PER_THREAD; i++) {
371 TAILQ_INSERT_TAIL(&verify_free_head, &verify_bufs[i], vb_entry);
372 }
373 }
374
375 void
cluster_init(void)376 cluster_init(void)
377 {
378 for (int i = 0; i < CL_DIRECT_READ_LOCK_BUCKETS; ++i) {
379 LIST_INIT(&cl_direct_read_locks[i]);
380 }
381
382 cluster_verify_init();
383 }
384
385 uint32_t
cluster_max_io_size(mount_t mp,int type)386 cluster_max_io_size(mount_t mp, int type)
387 {
388 uint32_t max_io_size;
389 uint32_t segcnt;
390 uint32_t maxcnt;
391
392 switch (type) {
393 case CL_READ:
394 segcnt = mp->mnt_segreadcnt;
395 maxcnt = mp->mnt_maxreadcnt;
396 break;
397 case CL_WRITE:
398 segcnt = mp->mnt_segwritecnt;
399 maxcnt = mp->mnt_maxwritecnt;
400 break;
401 default:
402 segcnt = min(mp->mnt_segreadcnt, mp->mnt_segwritecnt);
403 maxcnt = min(mp->mnt_maxreadcnt, mp->mnt_maxwritecnt);
404 break;
405 }
406 if (segcnt > (MAX_UPL_SIZE_BYTES >> PAGE_SHIFT)) {
407 /*
408 * don't allow a size beyond the max UPL size we can create
409 */
410 segcnt = MAX_UPL_SIZE_BYTES >> PAGE_SHIFT;
411 }
412 max_io_size = min((segcnt * PAGE_SIZE), maxcnt);
413
414 if (max_io_size < MAX_UPL_TRANSFER_BYTES) {
415 /*
416 * don't allow a size smaller than the old fixed limit
417 */
418 max_io_size = MAX_UPL_TRANSFER_BYTES;
419 } else {
420 /*
421 * make sure the size specified is a multiple of PAGE_SIZE
422 */
423 max_io_size &= ~PAGE_MASK;
424 }
425 return max_io_size;
426 }
427
428 /*
429 * Returns max prefetch value. If the value overflows or exceeds the specified
430 * 'prefetch_limit', it will be capped at 'prefetch_limit' value.
431 */
432 static inline uint32_t
cluster_max_prefetch(vnode_t vp,uint32_t max_io_size,uint32_t prefetch_limit)433 cluster_max_prefetch(vnode_t vp, uint32_t max_io_size, uint32_t prefetch_limit)
434 {
435 bool is_ssd = disk_conditioner_mount_is_ssd(vp->v_mount);
436 uint32_t io_scale = IO_SCALE(vp, is_ssd ? PREFETCH_SSD : PREFETCH);
437 uint32_t prefetch = 0;
438
439 if (__improbable(os_mul_overflow(max_io_size, io_scale, &prefetch) ||
440 (prefetch > prefetch_limit))) {
441 prefetch = prefetch_limit;
442 }
443
444 return prefetch;
445 }
446
447 static inline uint32_t
calculate_max_throttle_size(vnode_t vp)448 calculate_max_throttle_size(vnode_t vp)
449 {
450 bool is_ssd = disk_conditioner_mount_is_ssd(vp->v_mount);
451 uint32_t io_scale = IO_SCALE(vp, is_ssd ? 2 : 1);
452
453 return MIN(io_scale * THROTTLE_MAX_IOSIZE, MAX_UPL_TRANSFER_BYTES);
454 }
455
456 static inline uint32_t
calculate_max_throttle_cnt(vnode_t vp)457 calculate_max_throttle_cnt(vnode_t vp)
458 {
459 bool is_ssd = disk_conditioner_mount_is_ssd(vp->v_mount);
460 uint32_t io_scale = IO_SCALE(vp, 1);
461
462 return is_ssd ? MIN(io_scale, 4) : THROTTLE_MAXCNT;
463 }
464
465 #define CLW_ALLOCATE 0x01
466 #define CLW_RETURNLOCKED 0x02
467 #define CLW_IONOCACHE 0x04
468 #define CLW_IOPASSIVE 0x08
469
470 /*
471 * if the read ahead context doesn't yet exist,
472 * allocate and initialize it...
473 * the vnode lock serializes multiple callers
474 * during the actual assignment... first one
475 * to grab the lock wins... the other callers
476 * will release the now unnecessary storage
477 *
478 * once the context is present, try to grab (but don't block on)
479 * the lock associated with it... if someone
480 * else currently owns it, than the read
481 * will run without read-ahead. this allows
482 * multiple readers to run in parallel and
483 * since there's only 1 read ahead context,
484 * there's no real loss in only allowing 1
485 * reader to have read-ahead enabled.
486 */
487 static struct cl_readahead *
cluster_get_rap(vnode_t vp)488 cluster_get_rap(vnode_t vp)
489 {
490 struct ubc_info *ubc;
491 struct cl_readahead *rap;
492
493 ubc = vp->v_ubcinfo;
494
495 if ((rap = ubc->cl_rahead) == NULL) {
496 rap = zalloc_flags(cl_rd_zone, Z_WAITOK | Z_ZERO);
497 rap->cl_lastr = -1;
498 lck_mtx_init(&rap->cl_lockr, &cl_mtx_grp, LCK_ATTR_NULL);
499
500 vnode_lock(vp);
501
502 if (ubc->cl_rahead == NULL) {
503 ubc->cl_rahead = rap;
504 } else {
505 lck_mtx_destroy(&rap->cl_lockr, &cl_mtx_grp);
506 zfree(cl_rd_zone, rap);
507 rap = ubc->cl_rahead;
508 }
509 vnode_unlock(vp);
510 }
511 if (lck_mtx_try_lock(&rap->cl_lockr) == TRUE) {
512 return rap;
513 }
514
515 return (struct cl_readahead *)NULL;
516 }
517
518
519 /*
520 * if the write behind context doesn't yet exist,
521 * and CLW_ALLOCATE is specified, allocate and initialize it...
522 * the vnode lock serializes multiple callers
523 * during the actual assignment... first one
524 * to grab the lock wins... the other callers
525 * will release the now unnecessary storage
526 *
527 * if CLW_RETURNLOCKED is set, grab (blocking if necessary)
528 * the lock associated with the write behind context before
529 * returning
530 */
531
532 static struct cl_writebehind *
cluster_get_wbp(vnode_t vp,int flags)533 cluster_get_wbp(vnode_t vp, int flags)
534 {
535 struct ubc_info *ubc;
536 struct cl_writebehind *wbp;
537
538 ubc = vp->v_ubcinfo;
539
540 if ((wbp = ubc->cl_wbehind) == NULL) {
541 if (!(flags & CLW_ALLOCATE)) {
542 return (struct cl_writebehind *)NULL;
543 }
544
545 wbp = zalloc_flags(cl_wr_zone, Z_WAITOK | Z_ZERO);
546
547 lck_mtx_init(&wbp->cl_lockw, &cl_mtx_grp, LCK_ATTR_NULL);
548
549 vnode_lock(vp);
550
551 if (ubc->cl_wbehind == NULL) {
552 ubc->cl_wbehind = wbp;
553 } else {
554 lck_mtx_destroy(&wbp->cl_lockw, &cl_mtx_grp);
555 zfree(cl_wr_zone, wbp);
556 wbp = ubc->cl_wbehind;
557 }
558 vnode_unlock(vp);
559 }
560 if (flags & CLW_RETURNLOCKED) {
561 lck_mtx_lock(&wbp->cl_lockw);
562 }
563
564 return wbp;
565 }
566
567
568 static void
cluster_syncup(vnode_t vp,off_t newEOF,int (* callback)(buf_t,void *),void * callback_arg,int flags)569 cluster_syncup(vnode_t vp, off_t newEOF, int (*callback)(buf_t, void *), void *callback_arg, int flags)
570 {
571 struct cl_writebehind *wbp;
572
573 if ((wbp = cluster_get_wbp(vp, 0)) != NULL) {
574 if (wbp->cl_number) {
575 lck_mtx_lock(&wbp->cl_lockw);
576
577 cluster_try_push(wbp, vp, newEOF, PUSH_ALL | flags, 0, callback, callback_arg, NULL, FALSE);
578
579 lck_mtx_unlock(&wbp->cl_lockw);
580 }
581 }
582 }
583
584
585 static int
cluster_io_present_in_BC(vnode_t vp,off_t f_offset)586 cluster_io_present_in_BC(vnode_t vp, off_t f_offset)
587 {
588 daddr64_t blkno;
589 size_t io_size;
590 int (*bootcache_check_fn)(dev_t device, u_int64_t blkno) = bootcache_contains_block;
591
592 if (bootcache_check_fn && vp->v_mount && vp->v_mount->mnt_devvp) {
593 if (VNOP_BLOCKMAP(vp, f_offset, PAGE_SIZE, &blkno, &io_size, NULL, VNODE_READ | VNODE_BLOCKMAP_NO_TRACK, NULL)) {
594 return 0;
595 }
596
597 if (io_size == 0) {
598 return 0;
599 }
600
601 if (bootcache_check_fn(vp->v_mount->mnt_devvp->v_rdev, blkno)) {
602 return 1;
603 }
604 }
605 return 0;
606 }
607
608
609 static int
cluster_is_throttled(vnode_t vp)610 cluster_is_throttled(vnode_t vp)
611 {
612 return throttle_io_will_be_throttled(-1, vp->v_mount);
613 }
614
615
616 static void
cluster_iostate_wait(struct clios * iostate,u_int target,const char * wait_name)617 cluster_iostate_wait(struct clios *iostate, u_int target, const char *wait_name)
618 {
619 lck_mtx_lock(&iostate->io_mtxp);
620
621 while ((iostate->io_issued - iostate->io_completed) > target) {
622 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 95)) | DBG_FUNC_START,
623 iostate->io_issued, iostate->io_completed, target, 0, 0);
624
625 iostate->io_wanted = 1;
626 msleep((caddr_t)&iostate->io_wanted, &iostate->io_mtxp, PRIBIO + 1, wait_name, NULL);
627
628 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 95)) | DBG_FUNC_END,
629 iostate->io_issued, iostate->io_completed, target, 0, 0);
630 }
631 lck_mtx_unlock(&iostate->io_mtxp);
632 }
633
634
635 static void
cluster_handle_associated_upl(struct clios * iostate,upl_t upl,upl_offset_t upl_offset,upl_size_t size,off_t f_offset)636 cluster_handle_associated_upl(struct clios *iostate, upl_t upl,
637 upl_offset_t upl_offset, upl_size_t size, off_t f_offset)
638 {
639 if (!size) {
640 return;
641 }
642
643 upl_t associated_upl = upl_associated_upl(upl);
644
645 if (!associated_upl) {
646 return;
647 }
648
649 /*
650 * The associated upl functions as a "range lock" for the file.
651 *
652 * The associated upl is created and is attached to to the upl in
653 * cluster_io when the direct io write is being started. Since the
654 * upl may be released in parts so the corresponding associated upl
655 * has to be released in parts as well.
656 *
657 * We have the f_offset, upl_offset and size and from that we have figure
658 * out the associated upl offset and length, we are interested in.
659 */
660 upl_offset_t assoc_upl_offset, assoc_upl_end;
661
662 /* ALIGNED UPL's */
663 if ((upl_offset & PAGE_MASK) == (f_offset & PAGE_MASK)) {
664 assoc_upl_offset = trunc_page_32(upl_offset);
665 assoc_upl_end = round_page_32(upl_offset + size);
666 goto do_commit;
667 }
668
669 /*
670 * HANDLE UNALIGNED UPLS
671 *
672 * ( See also cluster_io where the associated upl is created )
673 * While we create the upl in one go, we will be dumping the pages in
674 * the upl in "transaction sized chunks" relative to the upl. Except
675 * for the first transction, the upl_offset will always be page aligned.
676 * and when the upl's are not aligned the associated upl offset will not
677 * be page aligned and so we have to truncate and round up the starting
678 * and the end of the pages in question and see if they are shared with
679 * other transctions or not. If two transctions "share" a page in the
680 * associated upl, the first one to complete "marks" it and skips that
681 * page and the second one will include it in the "commit range"
682 *
683 * As an example, consider the case where 4 transctions are needed (this
684 * is the worst case).
685 *
686 * Transaction for 0-1 (size -> PAGE_SIZE - upl_offset)
687 *
688 * This covers the associated upl from a -> c. a->b is not shared but
689 * b-c is shared with the next transction so the first one to complete
690 * will only "mark" it.
691 *
692 * Transaction for 1-2 (size -> PAGE_SIZE)
693 *
694 * For transaction 1, assoc_upl_offset would be 0 (corresponding to the
695 * file offset a or b depending on what file offset the upl_offset
696 * corrssponds to ) and assoc_upl_end would correspond to the file
697 * offset c.
698 *
699 * (associated_upl - based on f_offset alignment)
700 * 0 a b c d e f
701 * <----|----|----|----|----|----|-----|---->
702 *
703 *
704 * (upl - based on user buffer address alignment)
705 * <__--|----|----|--__>
706 *
707 * 0 1 2 3
708 *
709 */
710 upl_size_t assoc_upl_size = upl_get_size(associated_upl);
711 #if 0
712 /* knock off the simple case first -> this transaction covers the entire UPL */
713 upl_offset_t upl_end = round_page_32(upl_offset + size);
714 upl_size_t upl_size = vector_upl_get_size(upl);
715
716 if ((trunc_page_32(upl_offset) == 0) && (upl_end == upl_size)) {
717 assoc_upl_offset = 0;
718 assoc_upl_end = assoc_upl_size;
719 goto do_commit;
720 }
721 #endif
722 off_t assoc_upl_start_f_offset = upl_adjusted_offset(associated_upl, PAGE_MASK);
723
724 assoc_upl_offset = (upl_offset_t)trunc_page_64(f_offset - assoc_upl_start_f_offset);
725 assoc_upl_end = round_page_64(f_offset + size) - assoc_upl_start_f_offset;
726
727 /*
728 * We can only sanity check the offset returned by upl_adjusted_offset
729 * for the first transaction for this UPL i.e. when (upl_offset < PAGE_SIZE)
730 */
731 assertf((upl_offset >= PAGE_SIZE) || ((assoc_upl_start_f_offset == trunc_page_64(f_offset)) && (assoc_upl_offset == 0)),
732 "upl_offset = %d, f_offset = %lld, size = %d, start_f_offset = %lld, assoc_upl_offset = %d",
733 upl_offset, f_offset, size, assoc_upl_start_f_offset, assoc_upl_offset);
734
735 assertf((upl_offset == assoc_upl_offset) || (upl_offset > assoc_upl_offset && ((upl_offset - assoc_upl_offset) <= PAGE_SIZE)) ||
736 (assoc_upl_offset > upl_offset && ((assoc_upl_offset - upl_offset) <= PAGE_SIZE)),
737 "abs(upl_offset - assoc_upl_offset) > PAGE_SIZE : "
738 "upl_offset = %d, f_offset = %lld, size = %d, start_f_offset = %lld, assoc_upl_offset = %d",
739 upl_offset, f_offset, size, assoc_upl_start_f_offset, assoc_upl_offset);
740
741 assertf(assoc_upl_end <= assoc_upl_size,
742 "upl_offset = %d, f_offset = %lld, size = %d, start_f_offset = %lld, assoc_upl_size = %d, assoc_upl_offset = %d, assoc_upl_end = %d",
743 upl_offset, f_offset, size, assoc_upl_start_f_offset, assoc_upl_size, assoc_upl_offset, assoc_upl_end);
744
745 assertf((assoc_upl_size > PAGE_SIZE) || (assoc_upl_offset == 0 && assoc_upl_end == PAGE_SIZE),
746 "upl_offset = %d, f_offset = %lld, size = %d, start_f_offset = %lld, assoc_upl_size = %d, assoc_upl_offset = %d, assoc_upl_end = %d",
747 upl_offset, f_offset, size, assoc_upl_start_f_offset, assoc_upl_size, assoc_upl_offset, assoc_upl_end);
748
749 if (assoc_upl_size == PAGE_SIZE) {
750 assoc_upl_offset = 0;
751 assoc_upl_end = PAGE_SIZE;
752 goto do_commit;
753 }
754
755 /*
756 * We have to check if the first and last pages of the associated UPL
757 * range could potentially be shared with other transactions and if the
758 * "sharing transactions" are both done. The first one sets the mark bit
759 * and the second one checks it and if set it includes that page in the
760 * pages to be "freed".
761 */
762 bool check_first_pg = (assoc_upl_offset != 0) || ((f_offset + size) < (assoc_upl_start_f_offset + PAGE_SIZE));
763 bool check_last_pg = (assoc_upl_end != assoc_upl_size) || (f_offset > ((assoc_upl_start_f_offset + assoc_upl_size) - PAGE_SIZE));
764
765 if (check_first_pg || check_last_pg) {
766 int first_pg = assoc_upl_offset >> PAGE_SHIFT;
767 int last_pg = trunc_page_32(assoc_upl_end - 1) >> PAGE_SHIFT;
768 upl_page_info_t *assoc_pl = UPL_GET_INTERNAL_PAGE_LIST(associated_upl);
769
770 lck_mtx_lock_spin(&iostate->io_mtxp);
771 if (check_first_pg && !upl_page_get_mark(assoc_pl, first_pg)) {
772 /*
773 * The first page isn't marked so let another transaction
774 * completion handle it.
775 */
776 upl_page_set_mark(assoc_pl, first_pg, true);
777 assoc_upl_offset += PAGE_SIZE;
778 }
779 if (check_last_pg && !upl_page_get_mark(assoc_pl, last_pg)) {
780 /*
781 * The last page isn't marked so mark the page and let another
782 * transaction completion handle it.
783 */
784 upl_page_set_mark(assoc_pl, last_pg, true);
785 assoc_upl_end -= PAGE_SIZE;
786 }
787 lck_mtx_unlock(&iostate->io_mtxp);
788 }
789
790 if (assoc_upl_end <= assoc_upl_offset) {
791 return;
792 }
793
794 do_commit:
795 size = assoc_upl_end - assoc_upl_offset;
796
797 boolean_t empty;
798
799 /*
800 * We can unlock these pages now and as this is for a
801 * direct/uncached write, we want to dump the pages too.
802 */
803 kern_return_t kr = upl_abort_range(associated_upl, assoc_upl_offset, size,
804 UPL_ABORT_DUMP_PAGES, &empty);
805
806 assert(!kr);
807
808 if (!kr && empty) {
809 upl_set_associated_upl(upl, NULL);
810 upl_deallocate(associated_upl);
811 }
812 }
813
814 static void
cluster_iodone_verify_continue(void)815 cluster_iodone_verify_continue(void)
816 {
817 lck_mtx_lock_spin(&cl_transaction_mtxp);
818 for (;;) {
819 struct verify_buf *vb = TAILQ_FIRST(&verify_work_head);
820
821 if (!vb) {
822 assert_wait(&verify_work_head, (THREAD_UNINT));
823 break;
824 }
825 buf_t cbp = vb->vb_cbp;
826 void* callback_arg = vb->vb_callback_arg;
827
828 TAILQ_REMOVE(&verify_work_head, vb, vb_entry);
829 vb->vb_cbp = NULL;
830 vb->vb_callback_arg = NULL;
831 vb->vb_whichq = 0;
832 TAILQ_INSERT_TAIL(&verify_free_head, vb, vb_entry);
833 lck_mtx_unlock(&cl_transaction_mtxp);
834
835 (void)cluster_iodone_finish(cbp, callback_arg);
836 cbp = NULL;
837 lck_mtx_lock_spin(&cl_transaction_mtxp);
838 }
839 lck_mtx_unlock(&cl_transaction_mtxp);
840 thread_block((thread_continue_t)cluster_iodone_verify_continue);
841 /* NOT REACHED */
842 }
843
844 static void
cluster_verify_thread(void)845 cluster_verify_thread(void)
846 {
847 thread_t self = current_thread();
848
849 thread_set_thread_name(self, "cluster_verify_thread");
850 #if __AMP__
851 if (ecore_verify_threads) {
852 thread_soft_bind_cluster_type(self, 'E');
853 }
854 #endif /* __AMP__ */
855 #if !defined(__x86_64__)
856 thread_group_join_io_storage();
857 #endif /* __x86_64__ */
858 cluster_iodone_verify_continue();
859 /* NOT REACHED */
860 }
861
862 static bool
enqueue_buf_for_verify(buf_t cbp,void * callback_arg)863 enqueue_buf_for_verify(buf_t cbp, void *callback_arg)
864 {
865 struct verify_buf *vb;
866
867 vb = TAILQ_FIRST(&verify_free_head);
868 if (vb) {
869 TAILQ_REMOVE(&verify_free_head, vb, vb_entry);
870 vb->vb_cbp = cbp;
871 vb->vb_callback_arg = callback_arg;
872 vb->vb_whichq = 1;
873 TAILQ_INSERT_TAIL(&verify_work_head, vb, vb_entry);
874 return true;
875 } else {
876 return false;
877 }
878 }
879
880 static int
cluster_ioerror(upl_t upl,int upl_offset,int abort_size,int error,int io_flags,vnode_t vp)881 cluster_ioerror(upl_t upl, int upl_offset, int abort_size, int error, int io_flags, vnode_t vp)
882 {
883 int upl_abort_code = 0;
884 int page_in = 0;
885 int page_out = 0;
886
887 if ((io_flags & (B_PHYS | B_CACHE)) == (B_PHYS | B_CACHE)) {
888 /*
889 * direct write of any flavor, or a direct read that wasn't aligned
890 */
891 ubc_upl_commit_range(upl, upl_offset, abort_size, UPL_COMMIT_FREE_ON_EMPTY);
892 } else {
893 if (io_flags & B_PAGEIO) {
894 if (io_flags & B_READ) {
895 page_in = 1;
896 } else {
897 page_out = 1;
898 }
899 }
900 if (io_flags & B_CACHE) {
901 /*
902 * leave pages in the cache unchanged on error
903 */
904 upl_abort_code = UPL_ABORT_FREE_ON_EMPTY;
905 } else if (((io_flags & B_READ) == 0) && ((error != ENXIO) || vnode_isswap(vp))) {
906 /*
907 * transient error on pageout/write path... leave pages unchanged
908 */
909 upl_abort_code = UPL_ABORT_FREE_ON_EMPTY;
910 } else if (page_in) {
911 upl_abort_code = UPL_ABORT_FREE_ON_EMPTY | UPL_ABORT_ERROR;
912 } else {
913 upl_abort_code = UPL_ABORT_FREE_ON_EMPTY | UPL_ABORT_DUMP_PAGES;
914 }
915
916 ubc_upl_abort_range(upl, upl_offset, abort_size, upl_abort_code);
917 }
918 return upl_abort_code;
919 }
920
921
922 static int
cluster_iodone(buf_t bp,void * callback_arg)923 cluster_iodone(buf_t bp, void *callback_arg)
924 {
925 buf_t cbp;
926 buf_t cbp_head;
927 int error = 0;
928 boolean_t transaction_complete = FALSE;
929 bool async;
930
931 __IGNORE_WCASTALIGN(cbp_head = (buf_t)(bp->b_trans_head));
932
933 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 20)) | DBG_FUNC_START,
934 cbp_head, bp->b_lblkno, bp->b_bcount, bp->b_flags, 0);
935
936 async = cluster_verify_threads &&
937 (os_atomic_load(&cbp_head->b_attr.ba_flags, acquire) & BA_ASYNC_VERIFY);
938
939 assert(!async || cbp_head->b_attr.ba_verify_ctx);
940
941 if (cbp_head->b_trans_next || !(cbp_head->b_flags & B_EOT)) {
942 lck_mtx_lock_spin(&cl_transaction_mtxp);
943
944 bp->b_flags |= B_TDONE;
945
946 for (cbp = cbp_head; cbp; cbp = cbp->b_trans_next) {
947 /*
948 * all I/O requests that are part of this transaction
949 * have to complete before we can process it
950 */
951 if (!(cbp->b_flags & B_TDONE)) {
952 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 20)) | DBG_FUNC_END,
953 cbp_head, cbp, cbp->b_bcount, cbp->b_flags, 0);
954
955 lck_mtx_unlock(&cl_transaction_mtxp);
956
957 return 0;
958 }
959
960 if (cbp->b_trans_next == CLUSTER_IO_WAITING) {
961 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 20)) | DBG_FUNC_END,
962 cbp_head, cbp, cbp->b_bcount, cbp->b_flags, 0);
963
964 lck_mtx_unlock(&cl_transaction_mtxp);
965 wakeup(cbp);
966
967 return 0;
968 }
969
970 if (cbp->b_flags & B_EOT) {
971 transaction_complete = TRUE;
972
973 if (async) {
974 async = enqueue_buf_for_verify(cbp_head, callback_arg);
975 }
976 }
977 }
978 lck_mtx_unlock(&cl_transaction_mtxp);
979
980 if (transaction_complete == FALSE) {
981 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 20)) | DBG_FUNC_END,
982 cbp_head, 0, 0, 0, 0);
983 return 0;
984 }
985 } else if (async) {
986 lck_mtx_lock_spin(&cl_transaction_mtxp);
987 async = enqueue_buf_for_verify(cbp_head, callback_arg);
988 lck_mtx_unlock(&cl_transaction_mtxp);
989 }
990
991 if (async) {
992 wakeup(&verify_work_head);
993 } else {
994 error = cluster_iodone_finish(cbp_head, callback_arg);
995 }
996
997 return error;
998 }
999
1000 static int
cluster_iodone_finish(buf_t cbp_head,void * callback_arg)1001 cluster_iodone_finish(buf_t cbp_head, void *callback_arg)
1002 {
1003 int b_flags;
1004 int error;
1005 int total_size;
1006 int total_resid;
1007 int upl_offset;
1008 int zero_offset;
1009 int pg_offset = 0;
1010 int commit_size = 0;
1011 int upl_flags = 0;
1012 int transaction_size = 0;
1013 upl_t upl;
1014 buf_t cbp;
1015 buf_t cbp_next;
1016 buf_t real_bp;
1017 vnode_t vp;
1018 struct clios *iostate;
1019 void *verify_ctx;
1020
1021 error = 0;
1022 total_size = 0;
1023 total_resid = 0;
1024
1025 cbp = cbp_head;
1026 vp = cbp->b_vp;
1027 upl_offset = cbp->b_uploffset;
1028 upl = cbp->b_upl;
1029 b_flags = cbp->b_flags;
1030 real_bp = cbp->b_real_bp;
1031 zero_offset = cbp->b_validend;
1032 iostate = (struct clios *)cbp->b_iostate;
1033
1034 if (real_bp) {
1035 real_bp->b_dev = cbp->b_dev;
1036 }
1037
1038 while (cbp) {
1039 if ((cbp->b_flags & B_ERROR) && error == 0) {
1040 error = cbp->b_error;
1041 }
1042
1043 total_resid += cbp->b_resid;
1044 total_size += cbp->b_bcount;
1045
1046 cbp_next = cbp->b_trans_next;
1047
1048 if (cbp_next == NULL) {
1049 /*
1050 * compute the overall size of the transaction
1051 * in case we created one that has 'holes' in it
1052 * 'total_size' represents the amount of I/O we
1053 * did, not the span of the transaction w/r to the UPL
1054 */
1055 transaction_size = cbp->b_uploffset + cbp->b_bcount - upl_offset;
1056 }
1057
1058 cbp = cbp_next;
1059 }
1060
1061 if (ISSET(b_flags, B_COMMIT_UPL)) {
1062 cluster_handle_associated_upl(iostate,
1063 cbp_head->b_upl,
1064 upl_offset,
1065 transaction_size,
1066 cbp_head->b_clfoffset);
1067 }
1068
1069 if (error == 0 && total_resid) {
1070 error = EIO;
1071 }
1072
1073 if (error == 0) {
1074 int (*cliodone_func)(buf_t, void *) = (int (*)(buf_t, void *))(cbp_head->b_cliodone);
1075
1076 if (cliodone_func != NULL) {
1077 cbp_head->b_bcount = transaction_size;
1078
1079 error = (*cliodone_func)(cbp_head, callback_arg);
1080 }
1081 }
1082 if (zero_offset) {
1083 cluster_zero(upl, zero_offset, PAGE_SIZE - (zero_offset & PAGE_MASK), real_bp);
1084 }
1085
1086 verify_ctx = cbp_head->b_attr.ba_verify_ctx;
1087 cbp_head->b_attr.ba_verify_ctx = NULL;
1088 if (verify_ctx) {
1089 vnode_verify_flags_t verify_flags = VNODE_VERIFY_CONTEXT_FREE;
1090 caddr_t verify_buf = NULL;
1091 off_t start_off = cbp_head->b_clfoffset;
1092 size_t verify_length = transaction_size;
1093 vm_offset_t vaddr;
1094
1095 if (!error) {
1096 /*
1097 * Map it in.
1098 *
1099 * ubc_upl_map_range unfortunately cannot handle concurrent map
1100 * requests for the same UPL and returns failures when it can't
1101 * map. The map exclusive mechanism enforces mutual exclusion
1102 * for concurrent requests.
1103 */
1104 os_atomic_inc(&verify_in_flight, relaxed);
1105 upl_set_map_exclusive(upl);
1106 error = ubc_upl_map_range(upl, upl_offset, round_page(transaction_size), VM_PROT_DEFAULT, &vaddr);
1107 if (error) {
1108 upl_clear_map_exclusive(upl);
1109 printf("ubc_upl_map_range returned error %d upl = %p, upl_offset = %d, size = %d",
1110 error, upl, (int)upl_offset, (int)round_page(transaction_size));
1111 error = EIO;
1112 if (os_atomic_dec_orig(&verify_in_flight, relaxed) == 0) {
1113 panic("verify_in_flight underflow");
1114 }
1115 } else {
1116 verify_buf = (caddr_t)vaddr;
1117 verify_flags |= VNODE_VERIFY_WITH_CONTEXT;
1118 }
1119 }
1120
1121 int verify_error = VNOP_VERIFY(vp, start_off, (uint8_t *)verify_buf, verify_length, 0, &verify_ctx, verify_flags, NULL);
1122 if (!error) {
1123 error = verify_error;
1124 }
1125
1126 if (verify_buf) {
1127 (void)ubc_upl_unmap_range(upl, upl_offset, round_page(transaction_size));
1128 upl_clear_map_exclusive(upl);
1129 verify_buf = NULL;
1130 if (os_atomic_dec_orig(&verify_in_flight, relaxed) == 0) {
1131 panic("verify_in_flight underflow");
1132 }
1133 }
1134 } else if (cbp_head->b_attr.ba_flags & BA_WILL_VERIFY) {
1135 error = EBADMSG;
1136 }
1137
1138 if (iostate) {
1139 int need_wakeup = 0;
1140
1141 /*
1142 * someone has issued multiple I/Os asynchrounsly
1143 * and is waiting for them to complete (streaming)
1144 */
1145 lck_mtx_lock_spin(&iostate->io_mtxp);
1146
1147 if (error && iostate->io_error == 0) {
1148 iostate->io_error = error;
1149 }
1150
1151 iostate->io_completed += total_size;
1152
1153 if (iostate->io_wanted) {
1154 /*
1155 * someone is waiting for the state of
1156 * this io stream to change
1157 */
1158 iostate->io_wanted = 0;
1159 need_wakeup = 1;
1160 }
1161 lck_mtx_unlock(&iostate->io_mtxp);
1162
1163 if (need_wakeup) {
1164 wakeup((caddr_t)&iostate->io_wanted);
1165 }
1166 }
1167
1168 if (b_flags & B_COMMIT_UPL) {
1169 pg_offset = upl_offset & PAGE_MASK;
1170 commit_size = (pg_offset + transaction_size + (PAGE_SIZE - 1)) & ~PAGE_MASK;
1171
1172 if (error) {
1173 upl_set_iodone_error(upl, error);
1174
1175 upl_flags = cluster_ioerror(upl, upl_offset - pg_offset, commit_size, error, b_flags, vp);
1176 } else {
1177 upl_flags = UPL_COMMIT_FREE_ON_EMPTY;
1178
1179 if ((b_flags & B_PHYS) && (b_flags & B_READ)) {
1180 upl_flags |= UPL_COMMIT_SET_DIRTY;
1181 }
1182
1183 if (b_flags & B_AGE) {
1184 upl_flags |= UPL_COMMIT_INACTIVATE;
1185 }
1186
1187 ubc_upl_commit_range(upl, upl_offset - pg_offset, commit_size, upl_flags);
1188 }
1189 }
1190
1191 cbp = cbp_head->b_trans_next;
1192 while (cbp) {
1193 cbp_next = cbp->b_trans_next;
1194
1195 if (cbp != cbp_head) {
1196 free_io_buf(cbp);
1197 }
1198
1199 cbp = cbp_next;
1200 }
1201 free_io_buf(cbp_head);
1202
1203 if (real_bp) {
1204 if (error) {
1205 real_bp->b_flags |= B_ERROR;
1206 real_bp->b_error = error;
1207 }
1208 real_bp->b_resid = total_resid;
1209
1210 buf_biodone(real_bp);
1211 }
1212 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 20)) | DBG_FUNC_END,
1213 upl, upl_offset - pg_offset, commit_size, (error << 24) | upl_flags, 0);
1214
1215 return error;
1216 }
1217
1218
1219 uint32_t
cluster_throttle_io_limit(vnode_t vp,uint32_t * limit)1220 cluster_throttle_io_limit(vnode_t vp, uint32_t *limit)
1221 {
1222 if (cluster_is_throttled(vp)) {
1223 *limit = calculate_max_throttle_size(vp);
1224 return 1;
1225 }
1226 return 0;
1227 }
1228
1229
1230 void
cluster_zero(upl_t upl,upl_offset_t upl_offset,int size,buf_t bp)1231 cluster_zero(upl_t upl, upl_offset_t upl_offset, int size, buf_t bp)
1232 {
1233 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 23)) | DBG_FUNC_START,
1234 upl_offset, size, bp, 0, 0);
1235
1236 if (bp == NULL || bp->b_datap == 0) {
1237 upl_page_info_t *pl;
1238 addr64_t zero_addr;
1239
1240 pl = ubc_upl_pageinfo(upl);
1241
1242 if (upl_device_page(pl) == TRUE) {
1243 zero_addr = ((addr64_t)upl_phys_page(pl, 0) << PAGE_SHIFT) + upl_offset;
1244
1245 bzero_phys_nc(zero_addr, size);
1246 } else {
1247 while (size) {
1248 int page_offset;
1249 int page_index;
1250 int zero_cnt;
1251
1252 page_index = upl_offset / PAGE_SIZE;
1253 page_offset = upl_offset & PAGE_MASK;
1254
1255 zero_addr = ((addr64_t)upl_phys_page(pl, page_index) << PAGE_SHIFT) + page_offset;
1256 zero_cnt = min(PAGE_SIZE - page_offset, size);
1257
1258 bzero_phys(zero_addr, zero_cnt);
1259
1260 size -= zero_cnt;
1261 upl_offset += zero_cnt;
1262 }
1263 }
1264 } else {
1265 bzero((caddr_t)((vm_offset_t)bp->b_datap + upl_offset), size);
1266 }
1267
1268 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 23)) | DBG_FUNC_END,
1269 upl_offset, size, 0, 0, 0);
1270 }
1271
1272
1273 static void
cluster_EOT(buf_t cbp_head,buf_t cbp_tail,int zero_offset,size_t verify_block_size)1274 cluster_EOT(buf_t cbp_head, buf_t cbp_tail, int zero_offset, size_t verify_block_size)
1275 {
1276 /*
1277 * We will assign a verification context to cbp_head.
1278 * This will be passed back to the filesystem when
1279 * verifying (in cluster_iodone).
1280 */
1281 if (verify_block_size) {
1282 off_t start_off = cbp_head->b_clfoffset;
1283 size_t length;
1284 void *verify_ctx = NULL;
1285 int error = 0;
1286 vnode_t vp = buf_vnode(cbp_head);
1287
1288 if (cbp_head == cbp_tail) {
1289 length = cbp_head->b_bcount;
1290 } else {
1291 length = (cbp_tail->b_clfoffset + cbp_tail->b_bcount) - start_off;
1292 }
1293
1294 /*
1295 * zero_offset is non zero for the transaction containing the EOF
1296 * (if the filesize is not page aligned). In that case we might
1297 * have the transaction size not be page/verify block size aligned
1298 */
1299 if ((zero_offset == 0) &&
1300 ((length < verify_block_size) || (length % verify_block_size)) != 0) {
1301 panic("%s length = %zu, verify_block_size = %zu",
1302 __FUNCTION__, length, verify_block_size);
1303 }
1304
1305 error = VNOP_VERIFY(vp, start_off, NULL, length,
1306 &verify_block_size, &verify_ctx, VNODE_VERIFY_CONTEXT_ALLOC, NULL);
1307
1308 assert(!(error && verify_ctx));
1309
1310 if (verify_ctx) {
1311 if (num_verify_threads && (os_atomic_load(&cluster_verify_threads, relaxed) == 0)) {
1312 if (os_atomic_inc_orig(&cluster_verify_threads, relaxed) == 0) {
1313 thread_t thread;
1314 int i;
1315
1316 for (i = 0; i < num_verify_threads && i < MAX_VERIFY_THREADS; i++) {
1317 kernel_thread_start((thread_continue_t)cluster_verify_thread, NULL, &thread);
1318 thread_deallocate(thread);
1319 }
1320 os_atomic_store(&cluster_verify_threads, i, relaxed);
1321 } else {
1322 os_atomic_dec(&cluster_verify_threads, relaxed);
1323 }
1324 }
1325 cbp_head->b_attr.ba_verify_ctx = verify_ctx;
1326 /*
1327 * At least one thread is busy (at the time we
1328 * checked), so we can let it get queued for
1329 * async processing. It's fine if we occasionally get
1330 * this wrong.
1331 */
1332 if (os_atomic_load(&verify_in_flight, relaxed)) {
1333 /* This flag and the setting of ba_verify_ctx needs to be ordered */
1334 os_atomic_or(&cbp_head->b_attr.ba_flags, BA_ASYNC_VERIFY, release);
1335 }
1336 }
1337 } else {
1338 cbp_head->b_attr.ba_verify_ctx = NULL;
1339 }
1340
1341 cbp_head->b_validend = zero_offset;
1342 cbp_tail->b_flags |= B_EOT;
1343 }
1344
1345 static void
cluster_wait_IO(buf_t cbp_head,int async)1346 cluster_wait_IO(buf_t cbp_head, int async)
1347 {
1348 buf_t cbp;
1349
1350 if (async) {
1351 /*
1352 * Async callback completion will not normally generate a
1353 * wakeup upon I/O completion. To get woken up, we set
1354 * b_trans_next (which is safe for us to modify) on the last
1355 * buffer to CLUSTER_IO_WAITING so that cluster_iodone knows
1356 * to wake us up when all buffers as part of this transaction
1357 * are completed. This is done under the umbrella of
1358 * cl_transaction_mtxp which is also taken in cluster_iodone.
1359 */
1360 bool done = true;
1361 buf_t last = NULL;
1362
1363 lck_mtx_lock_spin(&cl_transaction_mtxp);
1364
1365 for (cbp = cbp_head; cbp; last = cbp, cbp = cbp->b_trans_next) {
1366 if (!ISSET(cbp->b_flags, B_TDONE)) {
1367 done = false;
1368 }
1369 }
1370
1371 if (!done) {
1372 last->b_trans_next = CLUSTER_IO_WAITING;
1373
1374 DTRACE_IO1(wait__start, buf_t, last);
1375 do {
1376 msleep(last, &cl_transaction_mtxp, PSPIN | (PRIBIO + 1), "cluster_wait_IO", NULL);
1377
1378 /*
1379 * We should only have been woken up if all the
1380 * buffers are completed, but just in case...
1381 */
1382 done = true;
1383 for (cbp = cbp_head; cbp != CLUSTER_IO_WAITING; cbp = cbp->b_trans_next) {
1384 if (!ISSET(cbp->b_flags, B_TDONE)) {
1385 done = false;
1386 break;
1387 }
1388 }
1389 } while (!done);
1390 DTRACE_IO1(wait__done, buf_t, last);
1391
1392 last->b_trans_next = NULL;
1393 }
1394
1395 lck_mtx_unlock(&cl_transaction_mtxp);
1396 } else { // !async
1397 for (cbp = cbp_head; cbp; cbp = cbp->b_trans_next) {
1398 buf_biowait(cbp);
1399 }
1400 }
1401 }
1402
1403 static void
cluster_complete_transaction(buf_t * cbp_head,void * callback_arg,int * retval,int flags,int needwait)1404 cluster_complete_transaction(buf_t *cbp_head, void *callback_arg, int *retval, int flags, int needwait)
1405 {
1406 buf_t cbp;
1407 int error;
1408 boolean_t isswapout = FALSE;
1409
1410 /*
1411 * cluster_complete_transaction will
1412 * only be called if we've issued a complete chain in synchronous mode
1413 * or, we've already done a cluster_wait_IO on an incomplete chain
1414 */
1415 if (needwait) {
1416 for (cbp = *cbp_head; cbp; cbp = cbp->b_trans_next) {
1417 buf_biowait(cbp);
1418 }
1419 }
1420 /*
1421 * we've already waited on all of the I/Os in this transaction,
1422 * so mark all of the buf_t's in this transaction as B_TDONE
1423 * so that cluster_iodone sees the transaction as completed
1424 */
1425 for (cbp = *cbp_head; cbp; cbp = cbp->b_trans_next) {
1426 cbp->b_flags |= B_TDONE;
1427 cbp->b_attr.ba_flags &= ~BA_ASYNC_VERIFY;
1428 }
1429 cbp = *cbp_head;
1430
1431 if ((flags & (CL_ASYNC | CL_PAGEOUT)) == CL_PAGEOUT && vnode_isswap(cbp->b_vp)) {
1432 isswapout = TRUE;
1433 }
1434
1435 error = cluster_iodone(cbp, callback_arg);
1436
1437 if (!(flags & CL_ASYNC) && error && *retval == 0) {
1438 if (((flags & (CL_PAGEOUT | CL_KEEPCACHED)) != CL_PAGEOUT) || (error != ENXIO)) {
1439 *retval = error;
1440 } else if (isswapout == TRUE) {
1441 *retval = error;
1442 }
1443 }
1444 *cbp_head = (buf_t)NULL;
1445 }
1446
1447 uint64_t cluster_direct_write_wired = 0;
1448
1449 static int
cluster_io(vnode_t vp,upl_t upl,vm_offset_t upl_offset,off_t f_offset,int non_rounded_size,int flags,buf_t real_bp,struct clios * iostate,int (* callback)(buf_t,void *),void * callback_arg)1450 cluster_io(vnode_t vp, upl_t upl, vm_offset_t upl_offset, off_t f_offset, int non_rounded_size,
1451 int flags, buf_t real_bp, struct clios *iostate, int (*callback)(buf_t, void *), void *callback_arg)
1452 {
1453 buf_t cbp;
1454 u_int size;
1455 u_int io_size;
1456 int io_flags;
1457 int bmap_flags;
1458 int error = 0;
1459 int retval = 0;
1460 buf_t cbp_head = NULL;
1461 buf_t cbp_tail = NULL;
1462 int trans_count = 0;
1463 int max_trans_count;
1464 u_int pg_count;
1465 int pg_offset;
1466 u_int max_iosize;
1467 u_int max_vectors;
1468 int priv;
1469 int zero_offset = 0;
1470 int async_throttle = 0;
1471 mount_t mp;
1472 size_t verify_block_size = 0;
1473 vm_offset_t upl_end_offset;
1474 boolean_t need_EOT = FALSE;
1475
1476 /*
1477 * we currently don't support buffers larger than a page
1478 */
1479 if (real_bp && non_rounded_size > PAGE_SIZE) {
1480 panic("%s(): Called with real buffer of size %d bytes which "
1481 "is greater than the maximum allowed size of "
1482 "%d bytes (the system PAGE_SIZE).\n",
1483 __FUNCTION__, non_rounded_size, PAGE_SIZE);
1484 }
1485
1486 mp = vp->v_mount;
1487
1488 /*
1489 * we don't want to do any funny rounding of the size for IO requests
1490 * coming through the DIRECT or CONTIGUOUS paths... those pages don't
1491 * belong to us... we can't extend (nor do we need to) the I/O to fill
1492 * out a page
1493 */
1494 if (mp->mnt_devblocksize > 1 && !(flags & (CL_DEV_MEMORY | CL_DIRECT_IO))) {
1495 /*
1496 * round the requested size up so that this I/O ends on a
1497 * page boundary in case this is a 'write'... if the filesystem
1498 * has blocks allocated to back the page beyond the EOF, we want to
1499 * make sure to write out the zero's that are sitting beyond the EOF
1500 * so that in case the filesystem doesn't explicitly zero this area
1501 * if a hole is created via a lseek/write beyond the current EOF,
1502 * it will return zeros when it's read back from the disk. If the
1503 * physical allocation doesn't extend for the whole page, we'll
1504 * only write/read from the disk up to the end of this allocation
1505 * via the extent info returned from the VNOP_BLOCKMAP call.
1506 */
1507 pg_offset = upl_offset & PAGE_MASK;
1508
1509 size = (((non_rounded_size + pg_offset) + (PAGE_SIZE - 1)) & ~PAGE_MASK) - pg_offset;
1510 } else {
1511 /*
1512 * anyone advertising a blocksize of 1 byte probably
1513 * can't deal with us rounding up the request size
1514 * AFP is one such filesystem/device
1515 */
1516 size = non_rounded_size;
1517 }
1518 upl_end_offset = upl_offset + size;
1519
1520 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 22)) | DBG_FUNC_START, (int)f_offset, size, upl_offset, flags, 0);
1521
1522 /*
1523 * Set the maximum transaction size to the maximum desired number of
1524 * buffers.
1525 */
1526 max_trans_count = 8;
1527 if (flags & CL_DEV_MEMORY) {
1528 max_trans_count = 16;
1529 }
1530
1531 if (flags & CL_READ) {
1532 io_flags = B_READ;
1533 bmap_flags = VNODE_READ;
1534
1535 max_iosize = mp->mnt_maxreadcnt;
1536 max_vectors = mp->mnt_segreadcnt;
1537
1538 /* See if we can do cluster verification (pageins and aligned reads) */
1539 if ((flags & CL_PAGEIN || cluster_verify_threads) &&
1540 !(mp->mnt_kern_flag & MNTK_VIRTUALDEV) &&
1541 (VNOP_VERIFY(vp, f_offset, NULL, 0, &verify_block_size, NULL, VNODE_VERIFY_DEFAULT, NULL) == 0) &&
1542 verify_block_size) {
1543 if (verify_block_size != PAGE_SIZE) {
1544 verify_block_size = 0;
1545 }
1546 if (real_bp && verify_block_size) {
1547 panic("%s(): Called with real buffer and needs verification ",
1548 __FUNCTION__);
1549 }
1550 /*
1551 * For reads, only allow cluster verification if f_offset
1552 * and upl_offset are both page aligned. If they are not
1553 * page aligned, leave it to the filesystem to do verification
1554 * Furthermore, the size also has to be aligned to page size.
1555 * Strictly speaking the alignments need to be for verify_block_size
1556 * but since the only verify_block_size that is currently supported
1557 * is page size, we check against page alignment.
1558 */
1559 if (verify_block_size && !(flags & CL_PAGEIN) &&
1560 ((f_offset & PAGE_MASK) || (upl_offset & PAGE_MASK) || (non_rounded_size & PAGE_MASK))) {
1561 verify_block_size = 0;
1562 }
1563 }
1564 } else {
1565 io_flags = B_WRITE;
1566 bmap_flags = VNODE_WRITE;
1567
1568 max_iosize = mp->mnt_maxwritecnt;
1569 max_vectors = mp->mnt_segwritecnt;
1570 }
1571 if (verify_block_size) {
1572 bmap_flags |= VNODE_CLUSTER_VERIFY;
1573 }
1574 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 22)) | DBG_FUNC_NONE, max_iosize, max_vectors, mp->mnt_devblocksize, 0, 0);
1575
1576 /*
1577 * make sure the maximum iosize is a
1578 * multiple of the page size
1579 */
1580 max_iosize &= ~PAGE_MASK;
1581
1582 /*
1583 * Ensure the maximum iosize is sensible.
1584 */
1585 if (!max_iosize) {
1586 max_iosize = PAGE_SIZE;
1587 }
1588
1589 if (flags & CL_THROTTLE) {
1590 if (!(flags & CL_PAGEOUT) && cluster_is_throttled(vp)) {
1591 uint32_t max_throttle_size = calculate_max_throttle_size(vp);
1592
1593 if (max_iosize > max_throttle_size) {
1594 max_iosize = max_throttle_size;
1595 }
1596 async_throttle = calculate_max_throttle_cnt(vp);
1597 } else {
1598 if ((flags & CL_DEV_MEMORY)) {
1599 async_throttle = IO_SCALE(vp, VNODE_ASYNC_THROTTLE);
1600 } else {
1601 u_int max_cluster;
1602 u_int max_cluster_size;
1603 u_int scale;
1604
1605 if (vp->v_mount->mnt_minsaturationbytecount) {
1606 max_cluster_size = vp->v_mount->mnt_minsaturationbytecount;
1607
1608 scale = 1;
1609 } else {
1610 max_cluster_size = MAX_CLUSTER_SIZE(vp);
1611
1612 if (disk_conditioner_mount_is_ssd(vp->v_mount)) {
1613 scale = WRITE_THROTTLE_SSD;
1614 } else {
1615 scale = WRITE_THROTTLE;
1616 }
1617 }
1618 if (max_iosize > max_cluster_size) {
1619 max_cluster = max_cluster_size;
1620 } else {
1621 max_cluster = max_iosize;
1622 }
1623
1624 if (size < max_cluster) {
1625 max_cluster = size;
1626 }
1627
1628 if (flags & CL_CLOSE) {
1629 scale += MAX_CLUSTERS;
1630 }
1631
1632 async_throttle = min(IO_SCALE(vp, VNODE_ASYNC_THROTTLE), ((scale * max_cluster_size) / max_cluster) - 1);
1633 }
1634 }
1635 }
1636 if (flags & CL_AGE) {
1637 io_flags |= B_AGE;
1638 }
1639 if (flags & (CL_PAGEIN | CL_PAGEOUT)) {
1640 io_flags |= B_PAGEIO;
1641 }
1642 if (flags & (CL_IOSTREAMING)) {
1643 io_flags |= B_IOSTREAMING;
1644 }
1645 if (flags & CL_COMMIT) {
1646 io_flags |= B_COMMIT_UPL;
1647 }
1648 if (flags & CL_DIRECT_IO) {
1649 io_flags |= B_PHYS;
1650 }
1651 if (flags & (CL_PRESERVE | CL_KEEPCACHED)) {
1652 io_flags |= B_CACHE;
1653 }
1654 if (flags & CL_PASSIVE) {
1655 io_flags |= B_PASSIVE;
1656 }
1657 if (flags & CL_ENCRYPTED) {
1658 io_flags |= B_ENCRYPTED_IO;
1659 }
1660
1661 if (vp->v_flag & VSYSTEM) {
1662 io_flags |= B_META;
1663 }
1664
1665 if ((flags & CL_READ) && ((upl_offset + non_rounded_size) & PAGE_MASK) && (!(flags & CL_NOZERO))) {
1666 /*
1667 * then we are going to end up
1668 * with a page that we can't complete (the file size wasn't a multiple
1669 * of PAGE_SIZE and we're trying to read to the end of the file
1670 * so we'll go ahead and zero out the portion of the page we can't
1671 * read in from the file
1672 */
1673 zero_offset = (int)(upl_offset + non_rounded_size);
1674 } else if (!ISSET(flags, CL_READ) && ISSET(flags, CL_DIRECT_IO)) {
1675 assert(ISSET(flags, CL_COMMIT));
1676
1677 // For a direct/uncached write, we need to lock pages...
1678 upl_t cached_upl = NULL;
1679 upl_page_info_t *cached_pl;
1680
1681 assert(upl_offset < PAGE_SIZE);
1682
1683 /*
1684 *
1685 * f_offset = b
1686 * upl_offset = 8K
1687 *
1688 * (cached_upl - based on f_offset alignment)
1689 * 0 a b c
1690 * <----|----|----|----|----|----|-----|---->
1691 *
1692 *
1693 * (upl - based on user buffer address alignment)
1694 * <__--|----|----|--__>
1695 *
1696 * 0 1x 2x 3x
1697 *
1698 */
1699 const off_t cached_upl_f_offset = trunc_page_64(f_offset);
1700 const int cached_upl_size = round_page_32((f_offset - cached_upl_f_offset) + non_rounded_size);
1701 int num_retries = 0;
1702
1703 /*
1704 * Create a UPL to lock the pages in the cache whilst the
1705 * write is in progress.
1706 */
1707 create_cached_upl:
1708 ubc_create_upl_kernel(vp, cached_upl_f_offset, cached_upl_size, &cached_upl,
1709 &cached_pl, UPL_SET_LITE | UPL_WILL_MODIFY, VM_KERN_MEMORY_FILE);
1710 if (upl_has_wired_pages(cached_upl)) {
1711 /*
1712 * Pages in this UPL would contain stale data after our direct write
1713 * (which is intended to overwrite these pages on disk). The UPL is
1714 * just holding these pages "busy" to synchronize with any other I/O
1715 * or mmap() access and we have to dump these pages when the direct
1716 * write is done.
1717 * But we can't do that for wired pages, so let's release this UPL
1718 * and fall back to the "cached" path.
1719 */
1720 // printf("******* FBDP %s:%d vp %p offset 0x%llx size 0x%llx - switching from direct to cached write\n", __FUNCTION__, __LINE__, vp, cached_upl_f_offset, (uint64_t)cached_upl_size);
1721 ubc_upl_abort_range(cached_upl, 0, cached_upl_size, UPL_ABORT_FREE_ON_EMPTY);
1722 cached_upl = NULL;
1723 cached_pl = NULL;
1724 cluster_direct_write_wired++;
1725 return ENOTSUP;
1726 }
1727
1728 /*
1729 * If we are not overwriting the first and last pages completely
1730 * we need to write them out first if they are dirty. These pages
1731 * will be discarded after the write completes so we might lose
1732 * the writes for the parts that are not overwrrtten.
1733 */
1734 bool first_page_needs_sync = false;
1735 bool last_page_needs_sync = false;
1736
1737 if (cached_upl && (cached_upl_f_offset < f_offset) && upl_dirty_page(cached_pl, 0)) {
1738 first_page_needs_sync = true;
1739 }
1740
1741 if (cached_upl && (cached_upl_f_offset + cached_upl_size) > (f_offset + non_rounded_size)) {
1742 int last_page = (cached_upl_size / PAGE_SIZE) - 1;
1743
1744 if ((last_page != 0 || !first_page_needs_sync) && upl_dirty_page(cached_pl, last_page)) {
1745 last_page_needs_sync = true;
1746 }
1747 }
1748
1749 if (first_page_needs_sync || last_page_needs_sync) {
1750 ubc_upl_abort_range(cached_upl, 0, cached_upl_size, UPL_ABORT_FREE_ON_EMPTY);
1751 cached_upl = NULL;
1752 cached_pl = NULL;
1753 if (first_page_needs_sync) {
1754 ubc_msync(vp, cached_upl_f_offset, cached_upl_f_offset + PAGE_SIZE, NULL, UBC_PUSHALL | UBC_INVALIDATE | UBC_SYNC);
1755 }
1756 if (last_page_needs_sync) {
1757 off_t cached_upl_end_offset = cached_upl_f_offset + cached_upl_size;
1758
1759 ubc_msync(vp, cached_upl_end_offset - PAGE_SIZE, cached_upl_end_offset, NULL, UBC_PUSHALL | UBC_INVALIDATE | UBC_SYNC);
1760 }
1761 if (++num_retries < 16) {
1762 goto create_cached_upl;
1763 }
1764 printf("%s : Number of retries for syncing first or last page reached %d\n", __FUNCTION__, num_retries);
1765 assertf(num_retries < 16, "%s : Number of retries for syncing first or last page reached %d\n", __FUNCTION__, num_retries);
1766 }
1767
1768 /*
1769 * Attach this UPL to the other UPL so that we can find it
1770 * later.
1771 */
1772 upl_set_associated_upl(upl, cached_upl);
1773 assertf(!cached_upl ||
1774 (upl_adjusted_offset(cached_upl, PAGE_MASK) == cached_upl_f_offset),
1775 "upl_adjusted_offset(cached_upl, PAGE_MASK) = %lld, cached_upl_f_offset = %lld",
1776 upl_adjusted_offset(cached_upl, PAGE_MASK), cached_upl_f_offset);
1777 }
1778
1779 while (size) {
1780 daddr64_t blkno;
1781 daddr64_t lblkno;
1782 size_t io_size_tmp;
1783 u_int io_size_wanted;
1784
1785 if (size > max_iosize) {
1786 io_size = max_iosize;
1787 } else {
1788 io_size = size;
1789 }
1790
1791 io_size_wanted = io_size;
1792 io_size_tmp = (size_t)io_size;
1793
1794 if ((error = VNOP_BLOCKMAP(vp, f_offset, io_size, &blkno, &io_size_tmp, NULL, bmap_flags, NULL))) {
1795 break;
1796 }
1797
1798 if (io_size_tmp > io_size_wanted) {
1799 io_size = io_size_wanted;
1800 } else {
1801 io_size = (u_int)io_size_tmp;
1802 }
1803
1804 if (real_bp && (real_bp->b_blkno == real_bp->b_lblkno)) {
1805 real_bp->b_blkno = blkno;
1806 }
1807
1808 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 24)) | DBG_FUNC_NONE,
1809 (int)f_offset, (int)(blkno >> 32), (int)blkno, io_size, 0);
1810
1811 if (io_size == 0) {
1812 /*
1813 * vnop_blockmap didn't return an error... however, it did
1814 * return an extent size of 0 which means we can't
1815 * make forward progress on this I/O... a hole in the
1816 * file would be returned as a blkno of -1 with a non-zero io_size
1817 * a real extent is returned with a blkno != -1 and a non-zero io_size
1818 */
1819 error = EINVAL;
1820 break;
1821 }
1822 if (!(flags & CL_READ) && blkno == -1) {
1823 off_t e_offset;
1824 int pageout_flags;
1825
1826 if (upl_get_internal_vectorupl(upl)) {
1827 panic("Vector UPLs should not take this code-path");
1828 }
1829 /*
1830 * we're writing into a 'hole'
1831 */
1832 if (flags & CL_PAGEOUT) {
1833 /*
1834 * if we got here via cluster_pageout
1835 * then just error the request and return
1836 * the 'hole' should already have been covered
1837 */
1838 error = EINVAL;
1839 break;
1840 }
1841 /*
1842 * we can get here if the cluster code happens to
1843 * pick up a page that was dirtied via mmap vs
1844 * a 'write' and the page targets a 'hole'...
1845 * i.e. the writes to the cluster were sparse
1846 * and the file was being written for the first time
1847 *
1848 * we can also get here if the filesystem supports
1849 * 'holes' that are less than PAGE_SIZE.... because
1850 * we can't know if the range in the page that covers
1851 * the 'hole' has been dirtied via an mmap or not,
1852 * we have to assume the worst and try to push the
1853 * entire page to storage.
1854 *
1855 * Try paging out the page individually before
1856 * giving up entirely and dumping it (the pageout
1857 * path will insure that the zero extent accounting
1858 * has been taken care of before we get back into cluster_io)
1859 *
1860 * go direct to vnode_pageout so that we don't have to
1861 * unbusy the page from the UPL... we used to do this
1862 * so that we could call ubc_msync, but that results
1863 * in a potential deadlock if someone else races us to acquire
1864 * that page and wins and in addition needs one of the pages
1865 * we're continuing to hold in the UPL
1866 */
1867 pageout_flags = UPL_MSYNC | UPL_VNODE_PAGER | UPL_NESTED_PAGEOUT;
1868
1869 if (!(flags & CL_ASYNC)) {
1870 pageout_flags |= UPL_IOSYNC;
1871 }
1872 if (!(flags & CL_COMMIT)) {
1873 pageout_flags |= UPL_NOCOMMIT;
1874 }
1875
1876 if (cbp_head) {
1877 buf_t prev_cbp;
1878 uint32_t bytes_in_last_page;
1879
1880 /*
1881 * first we have to wait for the the current outstanding I/Os
1882 * to complete... EOT hasn't been set yet on this transaction
1883 * so the pages won't be released
1884 */
1885 cluster_wait_IO(cbp_head, (flags & CL_ASYNC));
1886
1887 bytes_in_last_page = cbp_head->b_uploffset & PAGE_MASK;
1888 for (cbp = cbp_head; cbp; cbp = cbp->b_trans_next) {
1889 bytes_in_last_page += cbp->b_bcount;
1890 }
1891 bytes_in_last_page &= PAGE_MASK;
1892
1893 while (bytes_in_last_page) {
1894 /*
1895 * we've got a transcation that
1896 * includes the page we're about to push out through vnode_pageout...
1897 * find the bp's in the list which intersect this page and either
1898 * remove them entirely from the transaction (there could be multiple bp's), or
1899 * round it's iosize down to the page boundary (there can only be one)...
1900 *
1901 * find the last bp in the list and act on it
1902 */
1903 for (prev_cbp = cbp = cbp_head; cbp->b_trans_next; cbp = cbp->b_trans_next) {
1904 prev_cbp = cbp;
1905 }
1906
1907 if (bytes_in_last_page >= cbp->b_bcount) {
1908 /*
1909 * this buf no longer has any I/O associated with it
1910 */
1911 bytes_in_last_page -= cbp->b_bcount;
1912 cbp->b_bcount = 0;
1913
1914 free_io_buf(cbp);
1915
1916 if (cbp == cbp_head) {
1917 assert(bytes_in_last_page == 0);
1918 /*
1919 * the buf we just freed was the only buf in
1920 * this transaction... so there's no I/O to do
1921 */
1922 cbp_head = NULL;
1923 cbp_tail = NULL;
1924 } else {
1925 /*
1926 * remove the buf we just freed from
1927 * the transaction list
1928 */
1929 prev_cbp->b_trans_next = NULL;
1930 cbp_tail = prev_cbp;
1931 }
1932 } else {
1933 /*
1934 * this is the last bp that has I/O
1935 * intersecting the page of interest
1936 * only some of the I/O is in the intersection
1937 * so clip the size but keep it in the transaction list
1938 */
1939 cbp->b_bcount -= bytes_in_last_page;
1940 cbp_tail = cbp;
1941 bytes_in_last_page = 0;
1942 }
1943 }
1944 if (cbp_head) {
1945 /*
1946 * there was more to the current transaction
1947 * than just the page we are pushing out via vnode_pageout...
1948 * mark it as finished and complete it... we've already
1949 * waited for the I/Os to complete above in the call to cluster_wait_IO
1950 */
1951 cluster_EOT(cbp_head, cbp_tail, 0, 0);
1952
1953 cluster_complete_transaction(&cbp_head, callback_arg, &retval, flags, 0);
1954
1955 trans_count = 0;
1956 }
1957 }
1958 if (vnode_pageout(vp, upl, (upl_offset_t)trunc_page(upl_offset), trunc_page_64(f_offset), PAGE_SIZE, pageout_flags, NULL) != PAGER_SUCCESS) {
1959 error = EINVAL;
1960 }
1961 e_offset = round_page_64(f_offset + 1);
1962 io_size = (u_int)(e_offset - f_offset);
1963
1964 f_offset += io_size;
1965 upl_offset += io_size;
1966
1967 if (size >= io_size) {
1968 size -= io_size;
1969 } else {
1970 size = 0;
1971 }
1972 /*
1973 * keep track of how much of the original request
1974 * that we've actually completed... non_rounded_size
1975 * may go negative due to us rounding the request
1976 * to a page size multiple (i.e. size > non_rounded_size)
1977 */
1978 non_rounded_size -= io_size;
1979
1980 if (non_rounded_size <= 0) {
1981 /*
1982 * we've transferred all of the data in the original
1983 * request, but we were unable to complete the tail
1984 * of the last page because the file didn't have
1985 * an allocation to back that portion... this is ok.
1986 */
1987 size = 0;
1988 }
1989 if (error) {
1990 if (size == 0) {
1991 flags &= ~CL_COMMIT;
1992 }
1993 break;
1994 }
1995 continue;
1996 }
1997
1998 lblkno = (daddr64_t)(f_offset / CLUSTER_IO_BLOCK_SIZE);
1999
2000 /*
2001 * we have now figured out how much I/O we can do - this is in 'io_size'
2002 * pg_offset is the starting point in the first page for the I/O
2003 * pg_count is the number of full and partial pages that 'io_size' encompasses
2004 */
2005 pg_offset = upl_offset & PAGE_MASK;
2006
2007 if (flags & CL_DEV_MEMORY) {
2008 /*
2009 * treat physical requests as one 'giant' page
2010 */
2011 pg_count = 1;
2012 } else {
2013 pg_count = (io_size + pg_offset + (PAGE_SIZE - 1)) / PAGE_SIZE;
2014 }
2015
2016 if ((flags & CL_READ) && blkno == -1) {
2017 vm_offset_t commit_offset;
2018 int bytes_to_zero;
2019 int complete_transaction_now = 0;
2020
2021 /*
2022 * if we're reading and blkno == -1, then we've got a
2023 * 'hole' in the file that we need to deal with by zeroing
2024 * out the affected area in the upl
2025 */
2026 if (io_size >= (u_int)non_rounded_size) {
2027 /*
2028 * if this upl contains the EOF and it is not a multiple of PAGE_SIZE
2029 * than 'zero_offset' will be non-zero
2030 * if the 'hole' returned by vnop_blockmap extends all the way to the eof
2031 * (indicated by the io_size finishing off the I/O request for this UPL)
2032 * than we're not going to issue an I/O for the
2033 * last page in this upl... we need to zero both the hole and the tail
2034 * of the page beyond the EOF, since the delayed zero-fill won't kick in
2035 */
2036 bytes_to_zero = non_rounded_size;
2037 if (!(flags & CL_NOZERO)) {
2038 bytes_to_zero = (int)((((upl_offset + io_size) + (PAGE_SIZE - 1)) & ~PAGE_MASK) - upl_offset);
2039 }
2040
2041 zero_offset = 0;
2042 } else {
2043 bytes_to_zero = io_size;
2044 }
2045
2046 pg_count = 0;
2047
2048 cluster_zero(upl, (upl_offset_t)upl_offset, bytes_to_zero, real_bp);
2049
2050 if (cbp_head) {
2051 int pg_resid;
2052
2053 /*
2054 * if there is a current I/O chain pending
2055 * then the first page of the group we just zero'd
2056 * will be handled by the I/O completion if the zero
2057 * fill started in the middle of the page
2058 */
2059 commit_offset = (upl_offset + (PAGE_SIZE - 1)) & ~PAGE_MASK;
2060
2061 pg_resid = (int)(commit_offset - upl_offset);
2062
2063 if (bytes_to_zero >= pg_resid) {
2064 /*
2065 * the last page of the current I/O
2066 * has been completed...
2067 * compute the number of fully zero'd
2068 * pages that are beyond it
2069 * plus the last page if its partial
2070 * and we have no more I/O to issue...
2071 * otherwise a partial page is left
2072 * to begin the next I/O
2073 */
2074 if ((int)io_size >= non_rounded_size) {
2075 pg_count = (bytes_to_zero - pg_resid + (PAGE_SIZE - 1)) / PAGE_SIZE;
2076 } else {
2077 pg_count = (bytes_to_zero - pg_resid) / PAGE_SIZE;
2078 }
2079
2080 complete_transaction_now = 1;
2081 }
2082 } else {
2083 /*
2084 * no pending I/O to deal with
2085 * so, commit all of the fully zero'd pages
2086 * plus the last page if its partial
2087 * and we have no more I/O to issue...
2088 * otherwise a partial page is left
2089 * to begin the next I/O
2090 */
2091 if ((int)io_size >= non_rounded_size) {
2092 pg_count = (pg_offset + bytes_to_zero + (PAGE_SIZE - 1)) / PAGE_SIZE;
2093 } else {
2094 pg_count = (pg_offset + bytes_to_zero) / PAGE_SIZE;
2095 }
2096
2097 commit_offset = upl_offset & ~PAGE_MASK;
2098 }
2099
2100 // Associated UPL is currently only used in the direct write path
2101 assert(!upl_associated_upl(upl));
2102
2103 if ((flags & CL_COMMIT) && pg_count) {
2104 ubc_upl_commit_range(upl, (upl_offset_t)commit_offset,
2105 pg_count * PAGE_SIZE,
2106 UPL_COMMIT_CLEAR_DIRTY | UPL_COMMIT_FREE_ON_EMPTY);
2107 }
2108 upl_offset += io_size;
2109 f_offset += io_size;
2110 size -= io_size;
2111
2112 /*
2113 * keep track of how much of the original request
2114 * that we've actually completed... non_rounded_size
2115 * may go negative due to us rounding the request
2116 * to a page size multiple (i.e. size > non_rounded_size)
2117 */
2118 non_rounded_size -= io_size;
2119
2120 if (non_rounded_size <= 0) {
2121 /*
2122 * we've transferred all of the data in the original
2123 * request, but we were unable to complete the tail
2124 * of the last page because the file didn't have
2125 * an allocation to back that portion... this is ok.
2126 */
2127 size = 0;
2128 }
2129 if (cbp_head && (complete_transaction_now || size == 0)) {
2130 cluster_wait_IO(cbp_head, (flags & CL_ASYNC));
2131
2132 cluster_EOT(cbp_head, cbp_tail, size == 0 ? zero_offset : 0, verify_block_size);
2133
2134 cluster_complete_transaction(&cbp_head, callback_arg, &retval, flags, 0);
2135
2136 trans_count = 0;
2137 }
2138 continue;
2139 }
2140 if (pg_count > max_vectors) {
2141 if (((pg_count - max_vectors) * PAGE_SIZE) > io_size) {
2142 io_size = PAGE_SIZE - pg_offset;
2143 pg_count = 1;
2144 } else {
2145 io_size -= (pg_count - max_vectors) * PAGE_SIZE;
2146 pg_count = max_vectors;
2147 }
2148 }
2149 /*
2150 * If the transaction is going to reach the maximum number of
2151 * desired elements, truncate the i/o to the nearest page so
2152 * that the actual i/o is initiated after this buffer is
2153 * created and added to the i/o chain.
2154 *
2155 * I/O directed to physically contiguous memory
2156 * doesn't have a requirement to make sure we 'fill' a page
2157 */
2158 if (!(flags & CL_DEV_MEMORY) && trans_count >= max_trans_count &&
2159 ((upl_offset + io_size) & PAGE_MASK)) {
2160 vm_offset_t aligned_ofs;
2161
2162 aligned_ofs = (upl_offset + io_size) & ~PAGE_MASK;
2163 /*
2164 * If the io_size does not actually finish off even a
2165 * single page we have to keep adding buffers to the
2166 * transaction despite having reached the desired limit.
2167 *
2168 * Eventually we get here with the page being finished
2169 * off (and exceeded) and then we truncate the size of
2170 * this i/o request so that it is page aligned so that
2171 * we can finally issue the i/o on the transaction.
2172 */
2173 if (aligned_ofs > upl_offset) {
2174 io_size = (u_int)(aligned_ofs - upl_offset);
2175 pg_count--;
2176 }
2177 }
2178
2179 if (!(mp->mnt_kern_flag & MNTK_VIRTUALDEV)) {
2180 /*
2181 * if we're not targeting a virtual device i.e. a disk image
2182 * it's safe to dip into the reserve pool since real devices
2183 * can complete this I/O request without requiring additional
2184 * bufs from the alloc_io_buf pool
2185 */
2186 priv = 1;
2187 } else if ((flags & CL_ASYNC) && !(flags & CL_PAGEOUT) && !cbp_head) {
2188 /*
2189 * Throttle the speculative IO
2190 *
2191 * We can only throttle this if it is the first iobuf
2192 * for the transaction. alloc_io_buf implements
2193 * additional restrictions for diskimages anyway.
2194 */
2195 priv = 0;
2196 } else {
2197 priv = 1;
2198 }
2199
2200 cbp = alloc_io_buf(vp, priv);
2201
2202 if (flags & CL_PAGEOUT) {
2203 u_int i;
2204
2205 /*
2206 * since blocks are in offsets of CLUSTER_IO_BLOCK_SIZE, scale
2207 * iteration to (PAGE_SIZE * pg_count) of blks.
2208 */
2209 for (i = 0; i < (PAGE_SIZE * pg_count) / CLUSTER_IO_BLOCK_SIZE; i++) {
2210 if (buf_invalblkno(vp, lblkno + i, 0) == EBUSY) {
2211 panic("BUSY bp found in cluster_io");
2212 }
2213 }
2214 }
2215 if (flags & CL_ASYNC) {
2216 if (buf_setcallback(cbp, (void *)cluster_iodone, callback_arg)) {
2217 panic("buf_setcallback failed");
2218 }
2219 }
2220 cbp->b_cliodone = (void *)callback;
2221 cbp->b_flags |= io_flags;
2222 if (flags & CL_NOCACHE) {
2223 cbp->b_attr.ba_flags |= BA_NOCACHE;
2224 }
2225 if (verify_block_size) {
2226 cbp->b_attr.ba_flags |= BA_WILL_VERIFY;
2227 }
2228
2229 cbp->b_lblkno = lblkno;
2230 cbp->b_clfoffset = f_offset;
2231 cbp->b_blkno = blkno;
2232 cbp->b_bcount = io_size;
2233
2234 if (buf_setupl(cbp, upl, (uint32_t)upl_offset)) {
2235 panic("buf_setupl failed");
2236 }
2237 #if CONFIG_IOSCHED
2238 upl_set_blkno(upl, upl_offset, io_size, blkno);
2239 #endif
2240 cbp->b_trans_next = (buf_t)NULL;
2241
2242 if ((cbp->b_iostate = (void *)iostate)) {
2243 /*
2244 * caller wants to track the state of this
2245 * io... bump the amount issued against this stream
2246 */
2247 iostate->io_issued += io_size;
2248 }
2249
2250 if (flags & CL_READ) {
2251 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 26)) | DBG_FUNC_NONE,
2252 (int)cbp->b_lblkno, (int)cbp->b_blkno, upl_offset, io_size, 0);
2253 } else {
2254 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 27)) | DBG_FUNC_NONE,
2255 (int)cbp->b_lblkno, (int)cbp->b_blkno, upl_offset, io_size, 0);
2256 }
2257
2258 if (cbp_head) {
2259 cbp_tail->b_trans_next = cbp;
2260 cbp_tail = cbp;
2261 } else {
2262 cbp_head = cbp;
2263 cbp_tail = cbp;
2264
2265 if ((cbp_head->b_real_bp = real_bp)) {
2266 real_bp = (buf_t)NULL;
2267 }
2268 }
2269 *(buf_t *)(&cbp->b_trans_head) = cbp_head;
2270
2271 trans_count++;
2272
2273 upl_offset += io_size;
2274 f_offset += io_size;
2275 size -= io_size;
2276 /*
2277 * keep track of how much of the original request
2278 * that we've actually completed... non_rounded_size
2279 * may go negative due to us rounding the request
2280 * to a page size multiple (i.e. size > non_rounded_size)
2281 */
2282 non_rounded_size -= io_size;
2283
2284 if (non_rounded_size <= 0) {
2285 /*
2286 * we've transferred all of the data in the original
2287 * request, but we were unable to complete the tail
2288 * of the last page because the file didn't have
2289 * an allocation to back that portion... this is ok.
2290 */
2291 size = 0;
2292 }
2293 if (size == 0) {
2294 /*
2295 * we have no more I/O to issue, so go
2296 * finish the final transaction
2297 */
2298 need_EOT = TRUE;
2299 } else if (((flags & CL_DEV_MEMORY) || (upl_offset & PAGE_MASK) == 0) &&
2300 ((flags & CL_ASYNC) || trans_count > max_trans_count)) {
2301 /*
2302 * I/O directed to physically contiguous memory...
2303 * which doesn't have a requirement to make sure we 'fill' a page
2304 * or...
2305 * the current I/O we've prepared fully
2306 * completes the last page in this request
2307 * and ...
2308 * it's either an ASYNC request or
2309 * we've already accumulated more than 8 I/O's into
2310 * this transaction so mark it as complete so that
2311 * it can finish asynchronously or via the cluster_complete_transaction
2312 * below if the request is synchronous
2313 */
2314 need_EOT = TRUE;
2315 }
2316 if (need_EOT == TRUE) {
2317 cluster_EOT(cbp_head, cbp_tail, size == 0 ? zero_offset : 0, verify_block_size);
2318 }
2319
2320 if (flags & CL_THROTTLE) {
2321 (void)vnode_waitforwrites(vp, async_throttle, 0, 0, "cluster_io");
2322 }
2323
2324 if (!(io_flags & B_READ)) {
2325 vnode_startwrite(vp);
2326 }
2327
2328 if (flags & CL_RAW_ENCRYPTED) {
2329 /*
2330 * User requested raw encrypted bytes.
2331 * Twiddle the bit in the ba_flags for the buffer
2332 */
2333 cbp->b_attr.ba_flags |= BA_RAW_ENCRYPTED_IO;
2334 }
2335
2336 (void) VNOP_STRATEGY(cbp);
2337
2338 if (need_EOT == TRUE) {
2339 if (!(flags & CL_ASYNC)) {
2340 cluster_complete_transaction(&cbp_head, callback_arg, &retval, flags, 1);
2341 }
2342
2343 need_EOT = FALSE;
2344 trans_count = 0;
2345 cbp_head = NULL;
2346 }
2347 }
2348 if (error) {
2349 int abort_size;
2350
2351 io_size = 0;
2352
2353 if (cbp_head) {
2354 /*
2355 * Wait until all of the outstanding I/O
2356 * for this partial transaction has completed
2357 */
2358 cluster_wait_IO(cbp_head, (flags & CL_ASYNC));
2359
2360 /*
2361 * Rewind the upl offset to the beginning of the
2362 * transaction.
2363 */
2364 upl_offset = cbp_head->b_uploffset;
2365 }
2366
2367 if (ISSET(flags, CL_COMMIT)) {
2368 cluster_handle_associated_upl(iostate, upl,
2369 (upl_offset_t)upl_offset,
2370 (upl_size_t)(upl_end_offset - upl_offset),
2371 cbp_head ? cbp_head->b_clfoffset : f_offset);
2372 }
2373
2374 // Free all the IO buffers in this transaction
2375 for (cbp = cbp_head; cbp;) {
2376 buf_t cbp_next;
2377
2378 size += cbp->b_bcount;
2379 io_size += cbp->b_bcount;
2380
2381 cbp_next = cbp->b_trans_next;
2382 free_io_buf(cbp);
2383 cbp = cbp_next;
2384 }
2385
2386 if (iostate) {
2387 int need_wakeup = 0;
2388
2389 /*
2390 * update the error condition for this stream
2391 * since we never really issued the io
2392 * just go ahead and adjust it back
2393 */
2394 lck_mtx_lock_spin(&iostate->io_mtxp);
2395
2396 if (iostate->io_error == 0) {
2397 iostate->io_error = error;
2398 }
2399 iostate->io_issued -= io_size;
2400
2401 if (iostate->io_wanted) {
2402 /*
2403 * someone is waiting for the state of
2404 * this io stream to change
2405 */
2406 iostate->io_wanted = 0;
2407 need_wakeup = 1;
2408 }
2409 lck_mtx_unlock(&iostate->io_mtxp);
2410
2411 if (need_wakeup) {
2412 wakeup((caddr_t)&iostate->io_wanted);
2413 }
2414 }
2415
2416 if (flags & CL_COMMIT) {
2417 int upl_flags;
2418
2419 pg_offset = upl_offset & PAGE_MASK;
2420 abort_size = (int)((upl_end_offset - upl_offset + PAGE_MASK) & ~PAGE_MASK);
2421
2422 upl_flags = cluster_ioerror(upl, (int)(upl_offset - pg_offset),
2423 abort_size, error, io_flags, vp);
2424
2425 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 28)) | DBG_FUNC_NONE,
2426 upl, upl_offset - pg_offset, abort_size, (error << 24) | upl_flags, 0);
2427 }
2428 if (retval == 0) {
2429 retval = error;
2430 }
2431 } else if (cbp_head) {
2432 panic("%s(): cbp_head is not NULL.", __FUNCTION__);
2433 }
2434
2435 if (real_bp) {
2436 /*
2437 * can get here if we either encountered an error
2438 * or we completely zero-filled the request and
2439 * no I/O was issued
2440 */
2441 if (error) {
2442 real_bp->b_flags |= B_ERROR;
2443 real_bp->b_error = error;
2444 }
2445 buf_biodone(real_bp);
2446 }
2447 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 22)) | DBG_FUNC_END, (int)f_offset, size, upl_offset, retval, 0);
2448
2449 return retval;
2450 }
2451
2452 #define reset_vector_run_state() \
2453 issueVectorUPL = vector_upl_offset = vector_upl_index = vector_upl_iosize = vector_upl_size = 0;
2454
2455 static int
vector_cluster_io(vnode_t vp,upl_t vector_upl,vm_offset_t vector_upl_offset,off_t v_upl_uio_offset,int vector_upl_iosize,int io_flag,buf_t real_bp,struct clios * iostate,int (* callback)(buf_t,void *),void * callback_arg)2456 vector_cluster_io(vnode_t vp, upl_t vector_upl, vm_offset_t vector_upl_offset, off_t v_upl_uio_offset, int vector_upl_iosize,
2457 int io_flag, buf_t real_bp, struct clios *iostate, int (*callback)(buf_t, void *), void *callback_arg)
2458 {
2459 vector_upl_set_pagelist(vector_upl);
2460
2461 if (io_flag & CL_READ) {
2462 if (vector_upl_offset == 0 && ((vector_upl_iosize & PAGE_MASK) == 0)) {
2463 io_flag &= ~CL_PRESERVE; /*don't zero fill*/
2464 } else {
2465 io_flag |= CL_PRESERVE; /*zero fill*/
2466 }
2467 }
2468 return cluster_io(vp, vector_upl, vector_upl_offset, v_upl_uio_offset, vector_upl_iosize, io_flag, real_bp, iostate, callback, callback_arg);
2469 }
2470
2471 static int
cluster_read_prefetch(vnode_t vp,off_t f_offset,u_int size,off_t filesize,int (* callback)(buf_t,void *),void * callback_arg,int bflag)2472 cluster_read_prefetch(vnode_t vp, off_t f_offset, u_int size, off_t filesize, int (*callback)(buf_t, void *), void *callback_arg, int bflag)
2473 {
2474 int pages_in_prefetch;
2475
2476 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 49)) | DBG_FUNC_START,
2477 (int)f_offset, size, (int)filesize, 0, 0);
2478
2479 if (f_offset >= filesize) {
2480 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 49)) | DBG_FUNC_END,
2481 (int)f_offset, 0, 0, 0, 0);
2482 return 0;
2483 }
2484 if ((off_t)size > (filesize - f_offset)) {
2485 size = (u_int)(filesize - f_offset);
2486 }
2487 pages_in_prefetch = (size + (PAGE_SIZE - 1)) / PAGE_SIZE;
2488
2489 advisory_read_ext(vp, filesize, f_offset, size, callback, callback_arg, bflag);
2490
2491 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 49)) | DBG_FUNC_END,
2492 (int)f_offset + size, pages_in_prefetch, 0, 1, 0);
2493
2494 return pages_in_prefetch;
2495 }
2496
2497
2498
2499 static void
cluster_read_ahead(vnode_t vp,struct cl_extent * extent,off_t filesize,struct cl_readahead * rap,int (* callback)(buf_t,void *),void * callback_arg,int bflag)2500 cluster_read_ahead(vnode_t vp, struct cl_extent *extent, off_t filesize, struct cl_readahead *rap, int (*callback)(buf_t, void *), void *callback_arg,
2501 int bflag)
2502 {
2503 daddr64_t r_addr;
2504 off_t f_offset;
2505 int size_of_prefetch;
2506 u_int max_prefetch;
2507
2508
2509 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 48)) | DBG_FUNC_START,
2510 (int)extent->b_addr, (int)extent->e_addr, (int)rap->cl_lastr, 0, 0);
2511
2512 if (extent->b_addr == rap->cl_lastr && extent->b_addr == extent->e_addr) {
2513 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 48)) | DBG_FUNC_END,
2514 rap->cl_ralen, (int)rap->cl_maxra, (int)rap->cl_lastr, 0, 0);
2515 return;
2516 }
2517 if (rap->cl_lastr == -1 || (extent->b_addr != rap->cl_lastr && extent->b_addr != (rap->cl_lastr + 1))) {
2518 rap->cl_ralen = 0;
2519 rap->cl_maxra = 0;
2520
2521 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 48)) | DBG_FUNC_END,
2522 rap->cl_ralen, (int)rap->cl_maxra, (int)rap->cl_lastr, 1, 0);
2523
2524 return;
2525 }
2526
2527 max_prefetch = cluster_max_prefetch(vp,
2528 cluster_max_io_size(vp->v_mount, CL_READ), speculative_prefetch_max);
2529
2530 if (max_prefetch <= PAGE_SIZE) {
2531 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 48)) | DBG_FUNC_END,
2532 rap->cl_ralen, (int)rap->cl_maxra, (int)rap->cl_lastr, 6, 0);
2533 return;
2534 }
2535 if (extent->e_addr < rap->cl_maxra && rap->cl_ralen >= 4) {
2536 if ((rap->cl_maxra - extent->e_addr) > (rap->cl_ralen / 4)) {
2537 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 48)) | DBG_FUNC_END,
2538 rap->cl_ralen, (int)rap->cl_maxra, (int)rap->cl_lastr, 2, 0);
2539 return;
2540 }
2541 }
2542 r_addr = MAX(extent->e_addr, rap->cl_maxra) + 1;
2543 f_offset = (off_t)(r_addr * PAGE_SIZE_64);
2544
2545 size_of_prefetch = 0;
2546
2547 ubc_range_op(vp, f_offset, f_offset + PAGE_SIZE_64, UPL_ROP_PRESENT, &size_of_prefetch);
2548
2549 if (size_of_prefetch) {
2550 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 48)) | DBG_FUNC_END,
2551 rap->cl_ralen, (int)rap->cl_maxra, (int)rap->cl_lastr, 3, 0);
2552 return;
2553 }
2554 if (f_offset < filesize) {
2555 daddr64_t read_size;
2556
2557 rap->cl_ralen = rap->cl_ralen ? min(max_prefetch / PAGE_SIZE, rap->cl_ralen << 1) : 1;
2558
2559 read_size = (extent->e_addr + 1) - extent->b_addr;
2560
2561 if (read_size > rap->cl_ralen) {
2562 if (read_size > max_prefetch / PAGE_SIZE) {
2563 rap->cl_ralen = max_prefetch / PAGE_SIZE;
2564 } else {
2565 rap->cl_ralen = (int)read_size;
2566 }
2567 }
2568 size_of_prefetch = cluster_read_prefetch(vp, f_offset, rap->cl_ralen * PAGE_SIZE, filesize, callback, callback_arg, bflag);
2569
2570 if (size_of_prefetch) {
2571 rap->cl_maxra = (r_addr + size_of_prefetch) - 1;
2572 }
2573 }
2574 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 48)) | DBG_FUNC_END,
2575 rap->cl_ralen, (int)rap->cl_maxra, (int)rap->cl_lastr, 4, 0);
2576 }
2577
2578
2579 int
cluster_pageout(vnode_t vp,upl_t upl,upl_offset_t upl_offset,off_t f_offset,int size,off_t filesize,int flags)2580 cluster_pageout(vnode_t vp, upl_t upl, upl_offset_t upl_offset, off_t f_offset,
2581 int size, off_t filesize, int flags)
2582 {
2583 return cluster_pageout_ext(vp, upl, upl_offset, f_offset, size, filesize, flags, NULL, NULL);
2584 }
2585
2586
2587 int
cluster_pageout_ext(vnode_t vp,upl_t upl,upl_offset_t upl_offset,off_t f_offset,int size,off_t filesize,int flags,int (* callback)(buf_t,void *),void * callback_arg)2588 cluster_pageout_ext(vnode_t vp, upl_t upl, upl_offset_t upl_offset, off_t f_offset,
2589 int size, off_t filesize, int flags, int (*callback)(buf_t, void *), void *callback_arg)
2590 {
2591 int io_size;
2592 int rounded_size;
2593 off_t max_size;
2594 int local_flags;
2595
2596 local_flags = CL_PAGEOUT | CL_THROTTLE;
2597
2598 if ((flags & UPL_IOSYNC) == 0) {
2599 local_flags |= CL_ASYNC;
2600 }
2601 if ((flags & UPL_NOCOMMIT) == 0) {
2602 local_flags |= CL_COMMIT;
2603 }
2604 if ((flags & UPL_KEEPCACHED)) {
2605 local_flags |= CL_KEEPCACHED;
2606 }
2607 if (flags & UPL_PAGING_ENCRYPTED) {
2608 local_flags |= CL_ENCRYPTED;
2609 }
2610
2611
2612 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 52)) | DBG_FUNC_NONE,
2613 (int)f_offset, size, (int)filesize, local_flags, 0);
2614
2615 /*
2616 * If they didn't specify any I/O, then we are done...
2617 * we can't issue an abort because we don't know how
2618 * big the upl really is
2619 */
2620 if (size <= 0) {
2621 return EINVAL;
2622 }
2623
2624 if (vp->v_mount->mnt_flag & MNT_RDONLY) {
2625 if (local_flags & CL_COMMIT) {
2626 ubc_upl_abort_range(upl, upl_offset, size, UPL_ABORT_FREE_ON_EMPTY);
2627 }
2628 return EROFS;
2629 }
2630 /*
2631 * can't page-in from a negative offset
2632 * or if we're starting beyond the EOF
2633 * or if the file offset isn't page aligned
2634 * or the size requested isn't a multiple of PAGE_SIZE
2635 */
2636 if (f_offset < 0 || f_offset >= filesize ||
2637 (f_offset & PAGE_MASK_64) || (size & PAGE_MASK)) {
2638 if (local_flags & CL_COMMIT) {
2639 ubc_upl_abort_range(upl, upl_offset, size, UPL_ABORT_FREE_ON_EMPTY);
2640 }
2641 return EINVAL;
2642 }
2643 max_size = filesize - f_offset;
2644
2645 if (size < max_size) {
2646 io_size = size;
2647 } else {
2648 io_size = (int)max_size;
2649 }
2650
2651 rounded_size = (io_size + (PAGE_SIZE - 1)) & ~PAGE_MASK;
2652
2653 if (size > rounded_size) {
2654 if (local_flags & CL_COMMIT) {
2655 ubc_upl_abort_range(upl, upl_offset + rounded_size, size - rounded_size,
2656 UPL_ABORT_FREE_ON_EMPTY);
2657 }
2658 }
2659 return cluster_io(vp, upl, upl_offset, f_offset, io_size,
2660 local_flags, (buf_t)NULL, (struct clios *)NULL, callback, callback_arg);
2661 }
2662
2663
2664 int
cluster_pagein(vnode_t vp,upl_t upl,upl_offset_t upl_offset,off_t f_offset,int size,off_t filesize,int flags)2665 cluster_pagein(vnode_t vp, upl_t upl, upl_offset_t upl_offset, off_t f_offset,
2666 int size, off_t filesize, int flags)
2667 {
2668 return cluster_pagein_ext(vp, upl, upl_offset, f_offset, size, filesize, flags, NULL, NULL);
2669 }
2670
2671
2672 int
cluster_pagein_ext(vnode_t vp,upl_t upl,upl_offset_t upl_offset,off_t f_offset,int size,off_t filesize,int flags,int (* callback)(buf_t,void *),void * callback_arg)2673 cluster_pagein_ext(vnode_t vp, upl_t upl, upl_offset_t upl_offset, off_t f_offset,
2674 int size, off_t filesize, int flags, int (*callback)(buf_t, void *), void *callback_arg)
2675 {
2676 u_int io_size;
2677 int rounded_size;
2678 off_t max_size;
2679 int retval;
2680 int local_flags = 0;
2681
2682 if (upl == NULL || size < 0) {
2683 panic("cluster_pagein: NULL upl passed in");
2684 }
2685
2686 if ((flags & UPL_IOSYNC) == 0) {
2687 local_flags |= CL_ASYNC;
2688 }
2689 if ((flags & UPL_NOCOMMIT) == 0) {
2690 local_flags |= CL_COMMIT;
2691 }
2692 if (flags & UPL_IOSTREAMING) {
2693 local_flags |= CL_IOSTREAMING;
2694 }
2695 if (flags & UPL_PAGING_ENCRYPTED) {
2696 local_flags |= CL_ENCRYPTED;
2697 }
2698
2699
2700 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 56)) | DBG_FUNC_NONE,
2701 (int)f_offset, size, (int)filesize, local_flags, 0);
2702
2703 /*
2704 * can't page-in from a negative offset
2705 * or if we're starting beyond the EOF
2706 * or if the file offset isn't page aligned
2707 * or the size requested isn't a multiple of PAGE_SIZE
2708 */
2709 if (f_offset < 0 || f_offset >= filesize ||
2710 (f_offset & PAGE_MASK_64) || (size & PAGE_MASK) || (upl_offset & PAGE_MASK)) {
2711 if (local_flags & CL_COMMIT) {
2712 ubc_upl_abort_range(upl, upl_offset, size, UPL_ABORT_FREE_ON_EMPTY | UPL_ABORT_ERROR);
2713 }
2714
2715 if (f_offset >= filesize) {
2716 ktriage_record(thread_tid(current_thread()), KDBG_TRIAGE_EVENTID(KDBG_TRIAGE_SUBSYS_CLUSTER, KDBG_TRIAGE_RESERVED, KDBG_TRIAGE_CL_PGIN_PAST_EOF), 0 /* arg */);
2717 }
2718
2719 return EINVAL;
2720 }
2721 max_size = filesize - f_offset;
2722
2723 if (size < max_size) {
2724 io_size = size;
2725 } else {
2726 io_size = (int)max_size;
2727 }
2728
2729 rounded_size = (io_size + (PAGE_SIZE - 1)) & ~PAGE_MASK;
2730
2731 if (size > rounded_size && (local_flags & CL_COMMIT)) {
2732 ubc_upl_abort_range(upl, upl_offset + rounded_size,
2733 size - rounded_size, UPL_ABORT_FREE_ON_EMPTY | UPL_ABORT_ERROR);
2734 }
2735
2736 retval = cluster_io(vp, upl, upl_offset, f_offset, io_size,
2737 local_flags | CL_READ | CL_PAGEIN, (buf_t)NULL, (struct clios *)NULL, callback, callback_arg);
2738
2739 return retval;
2740 }
2741
2742
2743 int
cluster_bp(buf_t bp)2744 cluster_bp(buf_t bp)
2745 {
2746 return cluster_bp_ext(bp, NULL, NULL);
2747 }
2748
2749
2750 int
cluster_bp_ext(buf_t bp,int (* callback)(buf_t,void *),void * callback_arg)2751 cluster_bp_ext(buf_t bp, int (*callback)(buf_t, void *), void *callback_arg)
2752 {
2753 off_t f_offset;
2754 int flags;
2755
2756 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 19)) | DBG_FUNC_START,
2757 bp, (int)bp->b_lblkno, bp->b_bcount, bp->b_flags, 0);
2758
2759 if (bp->b_flags & B_READ) {
2760 flags = CL_ASYNC | CL_READ;
2761 } else {
2762 flags = CL_ASYNC;
2763 }
2764 if (bp->b_flags & B_PASSIVE) {
2765 flags |= CL_PASSIVE;
2766 }
2767
2768 f_offset = ubc_blktooff(bp->b_vp, bp->b_lblkno);
2769
2770 return cluster_io(bp->b_vp, bp->b_upl, 0, f_offset, bp->b_bcount, flags, bp, (struct clios *)NULL, callback, callback_arg);
2771 }
2772
2773
2774
2775 int
cluster_write(vnode_t vp,struct uio * uio,off_t oldEOF,off_t newEOF,off_t headOff,off_t tailOff,int xflags)2776 cluster_write(vnode_t vp, struct uio *uio, off_t oldEOF, off_t newEOF, off_t headOff, off_t tailOff, int xflags)
2777 {
2778 return cluster_write_ext(vp, uio, oldEOF, newEOF, headOff, tailOff, xflags, NULL, NULL);
2779 }
2780
2781
2782 int
cluster_write_ext(vnode_t vp,struct uio * uio,off_t oldEOF,off_t newEOF,off_t headOff,off_t tailOff,int xflags,int (* callback)(buf_t,void *),void * callback_arg)2783 cluster_write_ext(vnode_t vp, struct uio *uio, off_t oldEOF, off_t newEOF, off_t headOff, off_t tailOff,
2784 int xflags, int (*callback)(buf_t, void *), void *callback_arg)
2785 {
2786 user_ssize_t cur_resid;
2787 int retval = 0;
2788 int flags;
2789 int zflags;
2790 int bflag;
2791 int write_type = IO_COPY;
2792 u_int32_t write_length = 0, saved_write_length;
2793 uint32_t min_direct_size = MIN_DIRECT_WRITE_SIZE;
2794
2795 flags = xflags;
2796
2797 if (flags & IO_PASSIVE) {
2798 bflag = CL_PASSIVE;
2799 } else {
2800 bflag = 0;
2801 }
2802
2803 if (vp->v_flag & VNOCACHE_DATA) {
2804 flags |= IO_NOCACHE;
2805 bflag |= CL_NOCACHE;
2806 }
2807 if (uio == NULL) {
2808 /*
2809 * no user data...
2810 * this call is being made to zero-fill some range in the file
2811 */
2812 retval = cluster_write_copy(vp, NULL, (u_int32_t)0, oldEOF, newEOF, headOff, tailOff, flags, callback, callback_arg);
2813
2814 return retval;
2815 }
2816 /*
2817 * do a write through the cache if one of the following is true....
2818 * NOCACHE is not true or NODIRECT is true
2819 * the uio request doesn't target USERSPACE
2820 * otherwise, find out if we want the direct or contig variant for
2821 * the first vector in the uio request
2822 */
2823 if (((flags & (IO_NOCACHE | IO_NODIRECT)) == IO_NOCACHE) && UIO_SEG_IS_USER_SPACE(uio->uio_segflg)) {
2824 if (flags & IO_NOCACHE_SWRITE) {
2825 uint32_t fs_bsize = vp->v_mount->mnt_vfsstat.f_bsize;
2826
2827 if (fs_bsize && (fs_bsize < MIN_DIRECT_WRITE_SIZE) &&
2828 ((fs_bsize & (fs_bsize - 1)) == 0)) {
2829 min_direct_size = fs_bsize;
2830 }
2831 }
2832 retval = cluster_io_type(uio, &write_type, &write_length, min_direct_size);
2833 }
2834
2835 if ((flags & (IO_TAILZEROFILL | IO_HEADZEROFILL)) && write_type == IO_DIRECT) {
2836 /*
2837 * must go through the cached variant in this case
2838 */
2839 write_type = IO_COPY;
2840 }
2841
2842 while ((cur_resid = uio_resid(uio)) && uio->uio_offset < newEOF && retval == 0) {
2843 switch (write_type) {
2844 case IO_COPY:
2845 /*
2846 * make sure the uio_resid isn't too big...
2847 * internally, we want to handle all of the I/O in
2848 * chunk sizes that fit in a 32 bit int
2849 */
2850 if (cur_resid > (user_ssize_t)(MAX_IO_REQUEST_SIZE)) {
2851 /*
2852 * we're going to have to call cluster_write_copy
2853 * more than once...
2854 *
2855 * only want the last call to cluster_write_copy to
2856 * have the IO_TAILZEROFILL flag set and only the
2857 * first call should have IO_HEADZEROFILL
2858 */
2859 zflags = flags & ~IO_TAILZEROFILL;
2860 flags &= ~IO_HEADZEROFILL;
2861
2862 write_length = MAX_IO_REQUEST_SIZE;
2863 } else {
2864 /*
2865 * last call to cluster_write_copy
2866 */
2867 zflags = flags;
2868
2869 write_length = (u_int32_t)cur_resid;
2870 }
2871 retval = cluster_write_copy(vp, uio, write_length, oldEOF, newEOF, headOff, tailOff, zflags, callback, callback_arg);
2872 break;
2873
2874 case IO_CONTIG:
2875 zflags = flags & ~(IO_TAILZEROFILL | IO_HEADZEROFILL);
2876
2877 if (flags & IO_HEADZEROFILL) {
2878 /*
2879 * only do this once per request
2880 */
2881 flags &= ~IO_HEADZEROFILL;
2882
2883 retval = cluster_write_copy(vp, (struct uio *)0, (u_int32_t)0, (off_t)0, uio->uio_offset,
2884 headOff, (off_t)0, zflags | IO_HEADZEROFILL | IO_SYNC, callback, callback_arg);
2885 if (retval) {
2886 break;
2887 }
2888 }
2889 retval = cluster_write_contig(vp, uio, newEOF, &write_type, &write_length, callback, callback_arg, bflag);
2890
2891 if (retval == 0 && (flags & IO_TAILZEROFILL) && uio_resid(uio) == 0) {
2892 /*
2893 * we're done with the data from the user specified buffer(s)
2894 * and we've been requested to zero fill at the tail
2895 * treat this as an IO_HEADZEROFILL which doesn't require a uio
2896 * by rearranging the args and passing in IO_HEADZEROFILL
2897 */
2898
2899 /*
2900 * Update the oldEOF to reflect the current EOF. If the UPL page
2901 * to zero-fill is not valid (when F_NOCACHE is set), the
2902 * cluster_write_copy() will perform RMW on the UPL page when
2903 * the oldEOF is not aligned on page boundary due to unaligned
2904 * write.
2905 */
2906 if (uio->uio_offset > oldEOF) {
2907 oldEOF = uio->uio_offset;
2908 }
2909 retval = cluster_write_copy(vp, (struct uio *)0, (u_int32_t)0, (off_t)oldEOF, tailOff, uio->uio_offset,
2910 (off_t)0, zflags | IO_HEADZEROFILL | IO_SYNC, callback, callback_arg);
2911 }
2912 break;
2913
2914 case IO_DIRECT:
2915 /*
2916 * cluster_write_direct is never called with IO_TAILZEROFILL || IO_HEADZEROFILL
2917 */
2918 saved_write_length = write_length;
2919 retval = cluster_write_direct(vp, uio, oldEOF, newEOF, &write_type, &write_length, flags, callback, callback_arg, min_direct_size);
2920 if (retval == ENOTSUP) {
2921 /* direct I/O didn't work; retry with cached I/O */
2922 // printf("******* FBDP %s:%d ENOTSUP cnt %d resid 0x%llx offset 0x%llx write_length 0x%x -> 0x%x\n", __FUNCTION__, __LINE__, uio_iovcnt(uio), (uint64_t) uio_resid(uio), uio_offset(uio), write_length, saved_write_length);
2923 write_length = saved_write_length;
2924 write_type = IO_COPY;
2925 retval = 0;
2926 }
2927 break;
2928
2929 case IO_UNKNOWN:
2930 retval = cluster_io_type(uio, &write_type, &write_length, min_direct_size);
2931 break;
2932 }
2933 /*
2934 * in case we end up calling cluster_write_copy (from cluster_write_direct)
2935 * multiple times to service a multi-vector request that is not aligned properly
2936 * we need to update the oldEOF so that we
2937 * don't zero-fill the head of a page if we've successfully written
2938 * data to that area... 'cluster_write_copy' will zero-fill the head of a
2939 * page that is beyond the oldEOF if the write is unaligned... we only
2940 * want that to happen for the very first page of the cluster_write,
2941 * NOT the first page of each vector making up a multi-vector write.
2942 */
2943 if (uio->uio_offset > oldEOF) {
2944 oldEOF = uio->uio_offset;
2945 }
2946 }
2947 return retval;
2948 }
2949
2950
2951 static int
cluster_write_direct(vnode_t vp,struct uio * uio,off_t oldEOF,off_t newEOF,int * write_type,u_int32_t * write_length,int flags,int (* callback)(buf_t,void *),void * callback_arg,uint32_t min_io_size)2952 cluster_write_direct(vnode_t vp, struct uio *uio, off_t oldEOF, off_t newEOF, int *write_type, u_int32_t *write_length,
2953 int flags, int (*callback)(buf_t, void *), void *callback_arg, uint32_t min_io_size)
2954 {
2955 upl_t upl = NULL;
2956 upl_page_info_t *pl;
2957 vm_offset_t upl_offset;
2958 vm_offset_t vector_upl_offset = 0;
2959 u_int32_t io_req_size;
2960 u_int32_t offset_in_file;
2961 u_int32_t offset_in_iovbase;
2962 u_int32_t io_size;
2963 int io_flag = 0;
2964 upl_size_t upl_size = 0, vector_upl_size = 0;
2965 vm_size_t upl_needed_size;
2966 mach_msg_type_number_t pages_in_pl = 0;
2967 upl_control_flags_t upl_flags;
2968 kern_return_t kret = KERN_SUCCESS;
2969 mach_msg_type_number_t i = 0;
2970 int force_data_sync;
2971 int retval = 0;
2972 int first_IO = 1;
2973 struct clios iostate;
2974 user_addr_t iov_base;
2975 u_int32_t mem_alignment_mask;
2976 u_int32_t devblocksize;
2977 u_int32_t max_io_size;
2978 u_int32_t max_upl_size;
2979 u_int32_t max_vector_size;
2980 u_int32_t bytes_outstanding_limit;
2981 boolean_t io_throttled = FALSE;
2982
2983 u_int32_t vector_upl_iosize = 0;
2984 int issueVectorUPL = 0, useVectorUPL = (uio->uio_iovcnt > 1);
2985 off_t v_upl_uio_offset = 0;
2986 int vector_upl_index = 0;
2987 upl_t vector_upl = NULL;
2988 uio_t snapshot_uio = NULL;
2989
2990 uint32_t io_align_mask;
2991
2992 /*
2993 * When we enter this routine, we know
2994 * -- the resid will not exceed iov_len
2995 */
2996 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 75)) | DBG_FUNC_START,
2997 (int)uio->uio_offset, *write_length, (int)newEOF, 0, 0);
2998
2999 assert(vm_map_page_shift(current_map()) >= PAGE_SHIFT);
3000
3001 max_upl_size = cluster_max_io_size(vp->v_mount, CL_WRITE);
3002
3003 io_flag = CL_ASYNC | CL_PRESERVE | CL_COMMIT | CL_THROTTLE | CL_DIRECT_IO;
3004
3005 if (flags & IO_PASSIVE) {
3006 io_flag |= CL_PASSIVE;
3007 }
3008
3009 if (flags & IO_NOCACHE) {
3010 io_flag |= CL_NOCACHE;
3011 }
3012
3013 if (flags & IO_SKIP_ENCRYPTION) {
3014 io_flag |= CL_ENCRYPTED;
3015 }
3016
3017 iostate.io_completed = 0;
3018 iostate.io_issued = 0;
3019 iostate.io_error = 0;
3020 iostate.io_wanted = 0;
3021
3022 lck_mtx_init(&iostate.io_mtxp, &cl_mtx_grp, LCK_ATTR_NULL);
3023
3024 mem_alignment_mask = (u_int32_t)vp->v_mount->mnt_alignmentmask;
3025 devblocksize = (u_int32_t)vp->v_mount->mnt_devblocksize;
3026
3027 if (devblocksize == 1) {
3028 /*
3029 * the AFP client advertises a devblocksize of 1
3030 * however, its BLOCKMAP routine maps to physical
3031 * blocks that are PAGE_SIZE in size...
3032 * therefore we can't ask for I/Os that aren't page aligned
3033 * or aren't multiples of PAGE_SIZE in size
3034 * by setting devblocksize to PAGE_SIZE, we re-instate
3035 * the old behavior we had before the mem_alignment_mask
3036 * changes went in...
3037 */
3038 devblocksize = PAGE_SIZE;
3039 }
3040
3041 io_align_mask = PAGE_MASK;
3042 if (min_io_size < MIN_DIRECT_WRITE_SIZE) {
3043 /* The process has opted into fs blocksize direct io writes */
3044 assert((min_io_size & (min_io_size - 1)) == 0);
3045 io_align_mask = min_io_size - 1;
3046 io_flag |= CL_DIRECT_IO_FSBLKSZ;
3047 }
3048
3049 if (uio_iovcnt(uio) > 1) {
3050 /* vector uio -> take a snapshot so we can rollback if needed */
3051 if (snapshot_uio) {
3052 uio_free(snapshot_uio);
3053 snapshot_uio = NULL;
3054 }
3055 snapshot_uio = uio_duplicate(uio);
3056 }
3057
3058 next_dwrite:
3059 io_req_size = *write_length;
3060 iov_base = uio_curriovbase(uio);
3061
3062 offset_in_file = (u_int32_t)(uio->uio_offset & io_align_mask);
3063 offset_in_iovbase = (u_int32_t)(iov_base & mem_alignment_mask);
3064
3065 if (offset_in_file || offset_in_iovbase) {
3066 /*
3067 * one of the 2 important offsets is misaligned
3068 * so fire an I/O through the cache for this entire vector
3069 */
3070 goto wait_for_dwrites;
3071 }
3072 if (iov_base & (devblocksize - 1)) {
3073 /*
3074 * the offset in memory must be on a device block boundary
3075 * so that we can guarantee that we can generate an
3076 * I/O that ends on a page boundary in cluster_io
3077 */
3078 goto wait_for_dwrites;
3079 }
3080
3081 task_update_logical_writes(current_task(), (io_req_size & ~PAGE_MASK), TASK_WRITE_IMMEDIATE, vp);
3082 while ((io_req_size >= PAGE_SIZE || io_req_size >= min_io_size) && uio->uio_offset < newEOF && retval == 0) {
3083 int throttle_type;
3084
3085 if ((throttle_type = cluster_is_throttled(vp))) {
3086 uint32_t max_throttle_size = calculate_max_throttle_size(vp);
3087
3088 /*
3089 * we're in the throttle window, at the very least
3090 * we want to limit the size of the I/O we're about
3091 * to issue
3092 */
3093 if ((flags & IO_RETURN_ON_THROTTLE) && throttle_type == THROTTLE_NOW) {
3094 /*
3095 * we're in the throttle window and at least 1 I/O
3096 * has already been issued by a throttleable thread
3097 * in this window, so return with EAGAIN to indicate
3098 * to the FS issuing the cluster_write call that it
3099 * should now throttle after dropping any locks
3100 */
3101 throttle_info_update_by_mount(vp->v_mount);
3102
3103 io_throttled = TRUE;
3104 goto wait_for_dwrites;
3105 }
3106 max_vector_size = max_throttle_size;
3107 max_io_size = max_throttle_size;
3108 } else {
3109 max_vector_size = MAX_VECTOR_UPL_SIZE;
3110 max_io_size = max_upl_size;
3111 }
3112
3113 if (first_IO) {
3114 cluster_syncup(vp, newEOF, callback, callback_arg, callback ? PUSH_SYNC : 0);
3115 first_IO = 0;
3116 }
3117 io_size = io_req_size & ~io_align_mask;
3118 iov_base = uio_curriovbase(uio);
3119
3120 if (io_size > max_io_size) {
3121 io_size = max_io_size;
3122 }
3123
3124 if (useVectorUPL && (iov_base & PAGE_MASK)) {
3125 /*
3126 * We have an iov_base that's not page-aligned.
3127 * Issue all I/O's that have been collected within
3128 * this Vectored UPL.
3129 */
3130 if (vector_upl_index) {
3131 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);
3132 if (retval == ENOTSUP) {
3133 goto enotsup;
3134 }
3135 reset_vector_run_state();
3136 }
3137
3138 /*
3139 * After this point, if we are using the Vector UPL path and the base is
3140 * not page-aligned then the UPL with that base will be the first in the vector UPL.
3141 */
3142 }
3143
3144 upl_offset = (vm_offset_t)((u_int32_t)iov_base & PAGE_MASK);
3145 upl_needed_size = (upl_offset + io_size + (PAGE_SIZE - 1)) & ~PAGE_MASK;
3146
3147 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 76)) | DBG_FUNC_START,
3148 (int)upl_offset, upl_needed_size, (int)iov_base, io_size, 0);
3149
3150 vm_map_t map = UIO_SEG_IS_USER_SPACE(uio->uio_segflg) ? current_map() : kernel_map;
3151 for (force_data_sync = 0; force_data_sync < 3; force_data_sync++) {
3152 pages_in_pl = 0;
3153 upl_size = (upl_size_t)upl_needed_size;
3154 upl_flags = UPL_FILE_IO | UPL_COPYOUT_FROM | UPL_NO_SYNC |
3155 UPL_CLEAN_IN_PLACE | UPL_SET_INTERNAL | UPL_SET_LITE | UPL_SET_IO_WIRE;
3156
3157 kret = vm_map_get_upl(map,
3158 (vm_map_offset_t)(iov_base & ~((user_addr_t)PAGE_MASK)),
3159 &upl_size,
3160 &upl,
3161 NULL,
3162 &pages_in_pl,
3163 &upl_flags,
3164 VM_KERN_MEMORY_FILE,
3165 force_data_sync);
3166
3167 if (kret != KERN_SUCCESS) {
3168 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 76)) | DBG_FUNC_END,
3169 0, 0, 0, kret, 0);
3170 /*
3171 * failed to get pagelist
3172 *
3173 * we may have already spun some portion of this request
3174 * off as async requests... we need to wait for the I/O
3175 * to complete before returning
3176 */
3177 goto wait_for_dwrites;
3178 }
3179 pl = UPL_GET_INTERNAL_PAGE_LIST(upl);
3180 pages_in_pl = upl_size / PAGE_SIZE;
3181
3182 for (i = 0; i < pages_in_pl; i++) {
3183 if (!upl_valid_page(pl, i)) {
3184 break;
3185 }
3186 }
3187 if (i == pages_in_pl) {
3188 break;
3189 }
3190
3191 /*
3192 * didn't get all the pages back that we
3193 * needed... release this upl and try again
3194 */
3195 ubc_upl_abort(upl, 0);
3196 }
3197 if (force_data_sync >= 3) {
3198 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 76)) | DBG_FUNC_END,
3199 i, pages_in_pl, upl_size, kret, 0);
3200 /*
3201 * for some reason, we couldn't acquire a hold on all
3202 * the pages needed in the user's address space
3203 *
3204 * we may have already spun some portion of this request
3205 * off as async requests... we need to wait for the I/O
3206 * to complete before returning
3207 */
3208 goto wait_for_dwrites;
3209 }
3210
3211 /*
3212 * Consider the possibility that upl_size wasn't satisfied.
3213 */
3214 if (upl_size < upl_needed_size) {
3215 if (upl_size && upl_offset == 0) {
3216 io_size = upl_size;
3217 } else {
3218 io_size = 0;
3219 }
3220 }
3221 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 76)) | DBG_FUNC_END,
3222 (int)upl_offset, upl_size, (int)iov_base, io_size, 0);
3223
3224 if (io_size == 0) {
3225 ubc_upl_abort(upl, 0);
3226 upl = NULL;
3227 /*
3228 * we may have already spun some portion of this request
3229 * off as async requests... we need to wait for the I/O
3230 * to complete before returning
3231 */
3232 goto wait_for_dwrites;
3233 }
3234
3235 if (useVectorUPL) {
3236 vm_offset_t end_off = ((iov_base + io_size) & PAGE_MASK);
3237 if (end_off) {
3238 issueVectorUPL = 1;
3239 }
3240 /*
3241 * After this point, if we are using a vector UPL, then
3242 * either all the UPL elements end on a page boundary OR
3243 * this UPL is the last element because it does not end
3244 * on a page boundary.
3245 */
3246 }
3247
3248 /*
3249 * we want push out these writes asynchronously so that we can overlap
3250 * the preparation of the next I/O
3251 * if there are already too many outstanding writes
3252 * wait until some complete before issuing the next
3253 */
3254 if (vp->v_mount->mnt_minsaturationbytecount) {
3255 bytes_outstanding_limit = vp->v_mount->mnt_minsaturationbytecount;
3256 } else {
3257 if (__improbable(os_mul_overflow(max_upl_size, IO_SCALE(vp, 2),
3258 &bytes_outstanding_limit) ||
3259 (bytes_outstanding_limit > overlapping_write_max))) {
3260 bytes_outstanding_limit = overlapping_write_max;
3261 }
3262 }
3263
3264 cluster_iostate_wait(&iostate, bytes_outstanding_limit, "cluster_write_direct");
3265
3266 if (iostate.io_error) {
3267 /*
3268 * one of the earlier writes we issued ran into a hard error
3269 * don't issue any more writes, cleanup the UPL
3270 * that was just created but not used, then
3271 * go wait for all writes that are part of this stream
3272 * to complete before returning the error to the caller
3273 */
3274 ubc_upl_abort(upl, 0);
3275 upl = NULL;
3276
3277 goto wait_for_dwrites;
3278 }
3279
3280 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 77)) | DBG_FUNC_START,
3281 (int)upl_offset, (int)uio->uio_offset, io_size, io_flag, 0);
3282
3283 if (!useVectorUPL) {
3284 retval = cluster_io(vp, upl, upl_offset, uio->uio_offset,
3285 io_size, io_flag, (buf_t)NULL, &iostate, callback, callback_arg);
3286 } else {
3287 if (!vector_upl_index) {
3288 vector_upl = vector_upl_create(upl_offset, uio->uio_iovcnt);
3289 v_upl_uio_offset = uio->uio_offset;
3290 vector_upl_offset = upl_offset;
3291 }
3292
3293 vector_upl_set_subupl(vector_upl, upl, upl_size);
3294 vector_upl_set_iostate(vector_upl, upl, vector_upl_size, upl_size);
3295 vector_upl_index++;
3296 vector_upl_iosize += io_size;
3297 vector_upl_size += upl_size;
3298
3299 if (issueVectorUPL || vector_upl_index == vector_upl_max_upls(vector_upl) || vector_upl_size >= max_vector_size) {
3300 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);
3301 if (retval != ENOTSUP) {
3302 reset_vector_run_state();
3303 }
3304 }
3305 }
3306 if (retval == ENOTSUP) {
3307 enotsup:
3308 /*
3309 * Can't do direct I/O. Try again with cached I/O.
3310 */
3311 // printf("******* FBDP %s:%d ENOTSUP io_size 0%x resid 0x%llx\n", __FUNCTION__, __LINE__, io_size, uio_resid(uio));
3312 io_size = 0;
3313 if (snapshot_uio) {
3314 int restore_error;
3315
3316 /*
3317 * We've been collecting UPLs for this vector UPL and
3318 * moving the uio along. We need to undo that so that
3319 * the I/O can continue where it actually stopped...
3320 */
3321 restore_error = uio_restore(uio, snapshot_uio);
3322 assert(!restore_error);
3323 uio_free(snapshot_uio);
3324 snapshot_uio = NULL;
3325 }
3326 if (vector_upl_index) {
3327 ubc_upl_abort(vector_upl, 0);
3328 vector_upl = NULL;
3329 } else {
3330 ubc_upl_abort(upl, 0);
3331 upl = NULL;
3332 }
3333 goto wait_for_dwrites;
3334 }
3335
3336 /*
3337 * update the uio structure to
3338 * reflect the I/O that we just issued
3339 */
3340 uio_update(uio, (user_size_t)io_size);
3341
3342 /*
3343 * in case we end up calling through to cluster_write_copy to finish
3344 * the tail of this request, we need to update the oldEOF so that we
3345 * don't zero-fill the head of a page if we've successfully written
3346 * data to that area... 'cluster_write_copy' will zero-fill the head of a
3347 * page that is beyond the oldEOF if the write is unaligned... we only
3348 * want that to happen for the very first page of the cluster_write,
3349 * NOT the first page of each vector making up a multi-vector write.
3350 */
3351 if (uio->uio_offset > oldEOF) {
3352 oldEOF = uio->uio_offset;
3353 }
3354
3355 io_req_size -= io_size;
3356
3357 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 77)) | DBG_FUNC_END,
3358 (int)upl_offset, (int)uio->uio_offset, io_req_size, retval, 0);
3359 } /* end while */
3360
3361 if (retval == 0 && iostate.io_error == 0 && io_req_size == 0) {
3362 retval = cluster_io_type(uio, write_type, write_length, min_io_size);
3363
3364 if (retval == 0 && *write_type == IO_DIRECT) {
3365 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 75)) | DBG_FUNC_NONE,
3366 (int)uio->uio_offset, *write_length, (int)newEOF, 0, 0);
3367
3368 goto next_dwrite;
3369 }
3370 }
3371
3372 wait_for_dwrites:
3373
3374 if (retval == 0 && iostate.io_error == 0 && useVectorUPL && vector_upl_index) {
3375 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);
3376 reset_vector_run_state();
3377 }
3378 /*
3379 * make sure all async writes issued as part of this stream
3380 * have completed before we return
3381 */
3382 cluster_iostate_wait(&iostate, 0, "cluster_write_direct");
3383
3384 if (iostate.io_error) {
3385 retval = iostate.io_error;
3386 }
3387
3388 lck_mtx_destroy(&iostate.io_mtxp, &cl_mtx_grp);
3389
3390 if (io_throttled == TRUE && retval == 0) {
3391 retval = EAGAIN;
3392 }
3393
3394 if (io_req_size && retval == 0) {
3395 /*
3396 * we couldn't handle the tail of this request in DIRECT mode
3397 * so fire it through the copy path
3398 *
3399 * note that flags will never have IO_HEADZEROFILL or IO_TAILZEROFILL set
3400 * so we can just pass 0 in for the headOff and tailOff
3401 */
3402 if (uio->uio_offset > oldEOF) {
3403 oldEOF = uio->uio_offset;
3404 }
3405
3406 retval = cluster_write_copy(vp, uio, io_req_size, oldEOF, newEOF, (off_t)0, (off_t)0, flags, callback, callback_arg);
3407
3408 *write_type = IO_UNKNOWN;
3409 }
3410
3411 if (snapshot_uio) {
3412 uio_free(snapshot_uio);
3413 snapshot_uio = NULL;
3414 }
3415
3416 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 75)) | DBG_FUNC_END,
3417 (int)uio->uio_offset, io_req_size, retval, 4, 0);
3418
3419 return retval;
3420 }
3421
3422
3423 static int
cluster_write_contig(vnode_t vp,struct uio * uio,off_t newEOF,int * write_type,u_int32_t * write_length,int (* callback)(buf_t,void *),void * callback_arg,int bflag)3424 cluster_write_contig(vnode_t vp, struct uio *uio, off_t newEOF, int *write_type, u_int32_t *write_length,
3425 int (*callback)(buf_t, void *), void *callback_arg, int bflag)
3426 {
3427 upl_page_info_t *pl;
3428 addr64_t src_paddr = 0;
3429 upl_t upl[MAX_VECTS];
3430 vm_offset_t upl_offset;
3431 u_int32_t tail_size = 0;
3432 u_int32_t io_size;
3433 u_int32_t xsize;
3434 upl_size_t upl_size;
3435 vm_size_t upl_needed_size;
3436 mach_msg_type_number_t pages_in_pl;
3437 upl_control_flags_t upl_flags;
3438 kern_return_t kret;
3439 struct clios iostate;
3440 int error = 0;
3441 int cur_upl = 0;
3442 int num_upl = 0;
3443 int n;
3444 user_addr_t iov_base;
3445 u_int32_t devblocksize;
3446 u_int32_t mem_alignment_mask;
3447
3448 /*
3449 * When we enter this routine, we know
3450 * -- the io_req_size will not exceed iov_len
3451 * -- the target address is physically contiguous
3452 */
3453 cluster_syncup(vp, newEOF, callback, callback_arg, callback ? PUSH_SYNC : 0);
3454
3455 devblocksize = (u_int32_t)vp->v_mount->mnt_devblocksize;
3456 mem_alignment_mask = (u_int32_t)vp->v_mount->mnt_alignmentmask;
3457
3458 iostate.io_completed = 0;
3459 iostate.io_issued = 0;
3460 iostate.io_error = 0;
3461 iostate.io_wanted = 0;
3462
3463 lck_mtx_init(&iostate.io_mtxp, &cl_mtx_grp, LCK_ATTR_NULL);
3464
3465 next_cwrite:
3466 io_size = *write_length;
3467
3468 iov_base = uio_curriovbase(uio);
3469
3470 upl_offset = (vm_offset_t)((u_int32_t)iov_base & PAGE_MASK);
3471 upl_needed_size = upl_offset + io_size;
3472
3473 pages_in_pl = 0;
3474 upl_size = (upl_size_t)upl_needed_size;
3475 upl_flags = UPL_FILE_IO | UPL_COPYOUT_FROM | UPL_NO_SYNC |
3476 UPL_CLEAN_IN_PLACE | UPL_SET_INTERNAL | UPL_SET_LITE | UPL_SET_IO_WIRE;
3477
3478 vm_map_t map = UIO_SEG_IS_USER_SPACE(uio->uio_segflg) ? current_map() : kernel_map;
3479 kret = vm_map_get_upl(map,
3480 vm_map_trunc_page(iov_base, vm_map_page_mask(map)),
3481 &upl_size, &upl[cur_upl], NULL, &pages_in_pl, &upl_flags, VM_KERN_MEMORY_FILE, 0);
3482
3483 if (kret != KERN_SUCCESS) {
3484 /*
3485 * failed to get pagelist
3486 */
3487 error = EINVAL;
3488 goto wait_for_cwrites;
3489 }
3490 num_upl++;
3491
3492 /*
3493 * Consider the possibility that upl_size wasn't satisfied.
3494 */
3495 if (upl_size < upl_needed_size) {
3496 /*
3497 * This is a failure in the physical memory case.
3498 */
3499 error = EINVAL;
3500 goto wait_for_cwrites;
3501 }
3502 pl = ubc_upl_pageinfo(upl[cur_upl]);
3503
3504 src_paddr = ((addr64_t)upl_phys_page(pl, 0) << PAGE_SHIFT) + (addr64_t)upl_offset;
3505
3506 while (((uio->uio_offset & (devblocksize - 1)) || io_size < devblocksize) && io_size) {
3507 u_int32_t head_size;
3508
3509 head_size = devblocksize - (u_int32_t)(uio->uio_offset & (devblocksize - 1));
3510
3511 if (head_size > io_size) {
3512 head_size = io_size;
3513 }
3514
3515 error = cluster_align_phys_io(vp, uio, src_paddr, head_size, 0, callback, callback_arg);
3516
3517 if (error) {
3518 goto wait_for_cwrites;
3519 }
3520
3521 upl_offset += head_size;
3522 src_paddr += head_size;
3523 io_size -= head_size;
3524
3525 iov_base += head_size;
3526 }
3527 if ((u_int32_t)iov_base & mem_alignment_mask) {
3528 /*
3529 * request doesn't set up on a memory boundary
3530 * the underlying DMA engine can handle...
3531 * return an error instead of going through
3532 * the slow copy path since the intent of this
3533 * path is direct I/O from device memory
3534 */
3535 error = EINVAL;
3536 goto wait_for_cwrites;
3537 }
3538
3539 tail_size = io_size & (devblocksize - 1);
3540 io_size -= tail_size;
3541
3542 while (io_size && error == 0) {
3543 if (io_size > MAX_IO_CONTIG_SIZE) {
3544 xsize = MAX_IO_CONTIG_SIZE;
3545 } else {
3546 xsize = io_size;
3547 }
3548 /*
3549 * request asynchronously so that we can overlap
3550 * the preparation of the next I/O... we'll do
3551 * the commit after all the I/O has completed
3552 * since its all issued against the same UPL
3553 * if there are already too many outstanding writes
3554 * wait until some have completed before issuing the next
3555 */
3556 cluster_iostate_wait(&iostate, MAX_IO_CONTIG_SIZE * IO_SCALE(vp, 2), "cluster_write_contig");
3557
3558 if (iostate.io_error) {
3559 /*
3560 * one of the earlier writes we issued ran into a hard error
3561 * don't issue any more writes...
3562 * go wait for all writes that are part of this stream
3563 * to complete before returning the error to the caller
3564 */
3565 goto wait_for_cwrites;
3566 }
3567 /*
3568 * issue an asynchronous write to cluster_io
3569 */
3570 error = cluster_io(vp, upl[cur_upl], upl_offset, uio->uio_offset,
3571 xsize, CL_DEV_MEMORY | CL_ASYNC | bflag, (buf_t)NULL, (struct clios *)&iostate, callback, callback_arg);
3572
3573 if (error == 0) {
3574 /*
3575 * The cluster_io write completed successfully,
3576 * update the uio structure
3577 */
3578 uio_update(uio, (user_size_t)xsize);
3579
3580 upl_offset += xsize;
3581 src_paddr += xsize;
3582 io_size -= xsize;
3583 }
3584 }
3585 if (error == 0 && iostate.io_error == 0 && tail_size == 0 && num_upl < MAX_VECTS) {
3586 error = cluster_io_type(uio, write_type, write_length, 0);
3587
3588 if (error == 0 && *write_type == IO_CONTIG) {
3589 cur_upl++;
3590 goto next_cwrite;
3591 }
3592 } else {
3593 *write_type = IO_UNKNOWN;
3594 }
3595
3596 wait_for_cwrites:
3597 /*
3598 * make sure all async writes that are part of this stream
3599 * have completed before we proceed
3600 */
3601 cluster_iostate_wait(&iostate, 0, "cluster_write_contig");
3602
3603 if (iostate.io_error) {
3604 error = iostate.io_error;
3605 }
3606
3607 lck_mtx_destroy(&iostate.io_mtxp, &cl_mtx_grp);
3608
3609 if (error == 0 && tail_size) {
3610 error = cluster_align_phys_io(vp, uio, src_paddr, tail_size, 0, callback, callback_arg);
3611 }
3612
3613 for (n = 0; n < num_upl; n++) {
3614 /*
3615 * just release our hold on each physically contiguous
3616 * region without changing any state
3617 */
3618 ubc_upl_abort(upl[n], 0);
3619 }
3620
3621 return error;
3622 }
3623
3624
3625 /*
3626 * need to avoid a race between an msync of a range of pages dirtied via mmap
3627 * vs a filesystem such as HFS deciding to write a 'hole' to disk via cluster_write's
3628 * zerofill mechanism before it has seen the VNOP_PAGEOUTs for the pages being msync'd
3629 *
3630 * we should never force-zero-fill pages that are already valid in the cache...
3631 * the entire page contains valid data (either from disk, zero-filled or dirtied
3632 * via an mmap) so we can only do damage by trying to zero-fill
3633 *
3634 */
3635 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)3636 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)
3637 {
3638 int zero_pg_index;
3639 boolean_t need_cluster_zero = TRUE;
3640
3641 if ((flags & (IO_NOZEROVALID | IO_NOZERODIRTY))) {
3642 bytes_to_zero = min(bytes_to_zero, PAGE_SIZE - (int)(zero_off & PAGE_MASK_64));
3643 zero_pg_index = (int)((zero_off - upl_f_offset) / PAGE_SIZE_64);
3644
3645 if (upl_valid_page(pl, zero_pg_index)) {
3646 /*
3647 * never force zero valid pages - dirty or clean
3648 * we'll leave these in the UPL for cluster_write_copy to deal with
3649 */
3650 need_cluster_zero = FALSE;
3651 }
3652 }
3653 if (need_cluster_zero == TRUE) {
3654 cluster_zero(upl, io_offset, bytes_to_zero, NULL);
3655 }
3656
3657 return bytes_to_zero;
3658 }
3659
3660
3661 void
cluster_update_state(vnode_t vp,vm_object_offset_t s_offset,vm_object_offset_t e_offset,boolean_t vm_initiated)3662 cluster_update_state(vnode_t vp, vm_object_offset_t s_offset, vm_object_offset_t e_offset, boolean_t vm_initiated)
3663 {
3664 struct cl_extent cl;
3665 boolean_t first_pass = TRUE;
3666
3667 assert(s_offset < e_offset);
3668 assert((s_offset & PAGE_MASK_64) == 0);
3669 assert((e_offset & PAGE_MASK_64) == 0);
3670
3671 cl.b_addr = (daddr64_t)(s_offset / PAGE_SIZE_64);
3672 cl.e_addr = (daddr64_t)(e_offset / PAGE_SIZE_64);
3673
3674 cluster_update_state_internal(vp, &cl, 0, TRUE, &first_pass, s_offset, (int)(e_offset - s_offset),
3675 vp->v_un.vu_ubcinfo->ui_size, NULL, NULL, vm_initiated);
3676 }
3677
3678
3679 static void
cluster_update_state_internal(vnode_t vp,struct cl_extent * cl,int flags,boolean_t defer_writes,boolean_t * first_pass,off_t write_off,int write_cnt,off_t newEOF,int (* callback)(buf_t,void *),void * callback_arg,boolean_t vm_initiated)3680 cluster_update_state_internal(vnode_t vp, struct cl_extent *cl, int flags, boolean_t defer_writes,
3681 boolean_t *first_pass, off_t write_off, int write_cnt, off_t newEOF,
3682 int (*callback)(buf_t, void *), void *callback_arg, boolean_t vm_initiated)
3683 {
3684 struct cl_writebehind *wbp;
3685 int cl_index;
3686 int ret_cluster_try_push;
3687 u_int max_cluster_pgcount;
3688
3689
3690 max_cluster_pgcount = MAX_CLUSTER_SIZE(vp) / PAGE_SIZE;
3691
3692 /*
3693 * take the lock to protect our accesses
3694 * of the writebehind and sparse cluster state
3695 */
3696 wbp = cluster_get_wbp(vp, CLW_ALLOCATE | CLW_RETURNLOCKED);
3697
3698 if (wbp->cl_scmap) {
3699 if (!(flags & IO_NOCACHE)) {
3700 /*
3701 * we've fallen into the sparse
3702 * cluster method of delaying dirty pages
3703 */
3704 sparse_cluster_add(wbp, &(wbp->cl_scmap), vp, cl, newEOF, callback, callback_arg, vm_initiated);
3705
3706 lck_mtx_unlock(&wbp->cl_lockw);
3707 return;
3708 }
3709 /*
3710 * must have done cached writes that fell into
3711 * the sparse cluster mechanism... we've switched
3712 * to uncached writes on the file, so go ahead
3713 * and push whatever's in the sparse map
3714 * and switch back to normal clustering
3715 */
3716 wbp->cl_number = 0;
3717
3718 sparse_cluster_push(wbp, &(wbp->cl_scmap), vp, newEOF, PUSH_ALL, 0, callback, callback_arg, vm_initiated);
3719 /*
3720 * no clusters of either type present at this point
3721 * so just go directly to start_new_cluster since
3722 * we know we need to delay this I/O since we've
3723 * already released the pages back into the cache
3724 * to avoid the deadlock with sparse_cluster_push
3725 */
3726 goto start_new_cluster;
3727 }
3728 if (*first_pass == TRUE) {
3729 if (write_off == wbp->cl_last_write) {
3730 wbp->cl_seq_written += write_cnt;
3731 } else {
3732 wbp->cl_seq_written = write_cnt;
3733 }
3734
3735 wbp->cl_last_write = write_off + write_cnt;
3736
3737 *first_pass = FALSE;
3738 }
3739 if (wbp->cl_number == 0) {
3740 /*
3741 * no clusters currently present
3742 */
3743 goto start_new_cluster;
3744 }
3745
3746 for (cl_index = 0; cl_index < wbp->cl_number; cl_index++) {
3747 /*
3748 * check each cluster that we currently hold
3749 * try to merge some or all of this write into
3750 * one or more of the existing clusters... if
3751 * any portion of the write remains, start a
3752 * new cluster
3753 */
3754 if (cl->b_addr >= wbp->cl_clusters[cl_index].b_addr) {
3755 /*
3756 * the current write starts at or after the current cluster
3757 */
3758 if (cl->e_addr <= (wbp->cl_clusters[cl_index].b_addr + max_cluster_pgcount)) {
3759 /*
3760 * we have a write that fits entirely
3761 * within the existing cluster limits
3762 */
3763 if (cl->e_addr > wbp->cl_clusters[cl_index].e_addr) {
3764 /*
3765 * update our idea of where the cluster ends
3766 */
3767 wbp->cl_clusters[cl_index].e_addr = cl->e_addr;
3768 }
3769 break;
3770 }
3771 if (cl->b_addr < (wbp->cl_clusters[cl_index].b_addr + max_cluster_pgcount)) {
3772 /*
3773 * we have a write that starts in the middle of the current cluster
3774 * but extends beyond the cluster's limit... we know this because
3775 * of the previous checks
3776 * we'll extend the current cluster to the max
3777 * and update the b_addr for the current write to reflect that
3778 * the head of it was absorbed into this cluster...
3779 * note that we'll always have a leftover tail in this case since
3780 * full absorbtion would have occurred in the clause above
3781 */
3782 wbp->cl_clusters[cl_index].e_addr = wbp->cl_clusters[cl_index].b_addr + max_cluster_pgcount;
3783
3784 cl->b_addr = wbp->cl_clusters[cl_index].e_addr;
3785 }
3786 /*
3787 * we come here for the case where the current write starts
3788 * beyond the limit of the existing cluster or we have a leftover
3789 * tail after a partial absorbtion
3790 *
3791 * in either case, we'll check the remaining clusters before
3792 * starting a new one
3793 */
3794 } else {
3795 /*
3796 * the current write starts in front of the cluster we're currently considering
3797 */
3798 if ((wbp->cl_clusters[cl_index].e_addr - cl->b_addr) <= max_cluster_pgcount) {
3799 /*
3800 * we can just merge the new request into
3801 * this cluster and leave it in the cache
3802 * since the resulting cluster is still
3803 * less than the maximum allowable size
3804 */
3805 wbp->cl_clusters[cl_index].b_addr = cl->b_addr;
3806
3807 if (cl->e_addr > wbp->cl_clusters[cl_index].e_addr) {
3808 /*
3809 * the current write completely
3810 * envelops the existing cluster and since
3811 * each write is limited to at most max_cluster_pgcount pages
3812 * we can just use the start and last blocknos of the write
3813 * to generate the cluster limits
3814 */
3815 wbp->cl_clusters[cl_index].e_addr = cl->e_addr;
3816 }
3817 break;
3818 }
3819 /*
3820 * if we were to combine this write with the current cluster
3821 * we would exceed the cluster size limit.... so,
3822 * let's see if there's any overlap of the new I/O with
3823 * the cluster we're currently considering... in fact, we'll
3824 * stretch the cluster out to it's full limit and see if we
3825 * get an intersection with the current write
3826 *
3827 */
3828 if (cl->e_addr > wbp->cl_clusters[cl_index].e_addr - max_cluster_pgcount) {
3829 /*
3830 * the current write extends into the proposed cluster
3831 * clip the length of the current write after first combining it's
3832 * tail with the newly shaped cluster
3833 */
3834 wbp->cl_clusters[cl_index].b_addr = wbp->cl_clusters[cl_index].e_addr - max_cluster_pgcount;
3835
3836 cl->e_addr = wbp->cl_clusters[cl_index].b_addr;
3837 }
3838 /*
3839 * if we get here, there was no way to merge
3840 * any portion of this write with this cluster
3841 * or we could only merge part of it which
3842 * will leave a tail...
3843 * we'll check the remaining clusters before starting a new one
3844 */
3845 }
3846 }
3847 if (cl_index < wbp->cl_number) {
3848 /*
3849 * we found an existing cluster(s) that we
3850 * could entirely merge this I/O into
3851 */
3852 goto delay_io;
3853 }
3854
3855 if (defer_writes == FALSE &&
3856 wbp->cl_number == MAX_CLUSTERS &&
3857 wbp->cl_seq_written >= (MAX_CLUSTERS * (max_cluster_pgcount * PAGE_SIZE))) {
3858 uint32_t n;
3859
3860 if (vp->v_mount->mnt_minsaturationbytecount) {
3861 n = vp->v_mount->mnt_minsaturationbytecount / MAX_CLUSTER_SIZE(vp);
3862
3863 if (n > MAX_CLUSTERS) {
3864 n = MAX_CLUSTERS;
3865 }
3866 } else {
3867 n = 0;
3868 }
3869
3870 if (n == 0) {
3871 if (disk_conditioner_mount_is_ssd(vp->v_mount)) {
3872 n = WRITE_BEHIND_SSD;
3873 } else {
3874 n = WRITE_BEHIND;
3875 }
3876 }
3877 while (n--) {
3878 cluster_try_push(wbp, vp, newEOF, 0, 0, callback, callback_arg, NULL, vm_initiated);
3879 }
3880 }
3881 if (wbp->cl_number < MAX_CLUSTERS) {
3882 /*
3883 * we didn't find an existing cluster to
3884 * merge into, but there's room to start
3885 * a new one
3886 */
3887 goto start_new_cluster;
3888 }
3889 /*
3890 * no exisitng cluster to merge with and no
3891 * room to start a new one... we'll try
3892 * pushing one of the existing ones... if none of
3893 * them are able to be pushed, we'll switch
3894 * to the sparse cluster mechanism
3895 * cluster_try_push updates cl_number to the
3896 * number of remaining clusters... and
3897 * returns the number of currently unused clusters
3898 */
3899 ret_cluster_try_push = 0;
3900
3901 /*
3902 * if writes are not deferred, call cluster push immediately
3903 */
3904 if (defer_writes == FALSE) {
3905 ret_cluster_try_push = cluster_try_push(wbp, vp, newEOF, (flags & IO_NOCACHE) ? 0 : PUSH_DELAY, 0, callback, callback_arg, NULL, vm_initiated);
3906 }
3907 /*
3908 * execute following regardless of writes being deferred or not
3909 */
3910 if (ret_cluster_try_push == 0) {
3911 /*
3912 * no more room in the normal cluster mechanism
3913 * so let's switch to the more expansive but expensive
3914 * sparse mechanism....
3915 */
3916 sparse_cluster_switch(wbp, vp, newEOF, callback, callback_arg, vm_initiated);
3917 sparse_cluster_add(wbp, &(wbp->cl_scmap), vp, cl, newEOF, callback, callback_arg, vm_initiated);
3918
3919 lck_mtx_unlock(&wbp->cl_lockw);
3920 return;
3921 }
3922 start_new_cluster:
3923 wbp->cl_clusters[wbp->cl_number].b_addr = cl->b_addr;
3924 wbp->cl_clusters[wbp->cl_number].e_addr = cl->e_addr;
3925
3926 wbp->cl_clusters[wbp->cl_number].io_flags = 0;
3927
3928 if (flags & IO_NOCACHE) {
3929 wbp->cl_clusters[wbp->cl_number].io_flags |= CLW_IONOCACHE;
3930 }
3931
3932 if (flags & IO_PASSIVE) {
3933 wbp->cl_clusters[wbp->cl_number].io_flags |= CLW_IOPASSIVE;
3934 }
3935
3936 wbp->cl_number++;
3937 delay_io:
3938 lck_mtx_unlock(&wbp->cl_lockw);
3939 return;
3940 }
3941
3942
3943 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)3944 cluster_write_copy(vnode_t vp, struct uio *uio, u_int32_t io_req_size, off_t oldEOF, off_t newEOF, off_t headOff,
3945 off_t tailOff, int flags, int (*callback)(buf_t, void *), void *callback_arg)
3946 {
3947 upl_page_info_t *pl;
3948 upl_t upl;
3949 vm_offset_t upl_offset = 0;
3950 vm_size_t upl_size;
3951 off_t upl_f_offset;
3952 int pages_in_upl;
3953 int start_offset;
3954 int xfer_resid;
3955 int io_size;
3956 int io_offset;
3957 int bytes_to_zero;
3958 int bytes_to_move;
3959 kern_return_t kret;
3960 int retval = 0;
3961 int io_resid;
3962 long long total_size;
3963 long long zero_cnt;
3964 off_t zero_off;
3965 long long zero_cnt1;
3966 off_t zero_off1;
3967 off_t write_off = 0;
3968 int write_cnt = 0;
3969 boolean_t first_pass = FALSE;
3970 struct cl_extent cl;
3971 int bflag;
3972 u_int max_io_size;
3973
3974 if (uio) {
3975 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 40)) | DBG_FUNC_START,
3976 (int)uio->uio_offset, io_req_size, (int)oldEOF, (int)newEOF, 0);
3977
3978 io_resid = io_req_size;
3979 } else {
3980 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 40)) | DBG_FUNC_START,
3981 0, 0, (int)oldEOF, (int)newEOF, 0);
3982
3983 io_resid = 0;
3984 }
3985 if (flags & IO_PASSIVE) {
3986 bflag = CL_PASSIVE;
3987 } else {
3988 bflag = 0;
3989 }
3990 if (flags & IO_NOCACHE) {
3991 bflag |= CL_NOCACHE;
3992 }
3993
3994 if (flags & IO_SKIP_ENCRYPTION) {
3995 bflag |= CL_ENCRYPTED;
3996 }
3997
3998 zero_cnt = 0;
3999 zero_cnt1 = 0;
4000 zero_off = 0;
4001 zero_off1 = 0;
4002
4003 max_io_size = cluster_max_io_size(vp->v_mount, CL_WRITE);
4004
4005 if (flags & IO_HEADZEROFILL) {
4006 /*
4007 * some filesystems (HFS is one) don't support unallocated holes within a file...
4008 * so we zero fill the intervening space between the old EOF and the offset
4009 * where the next chunk of real data begins.... ftruncate will also use this
4010 * routine to zero fill to the new EOF when growing a file... in this case, the
4011 * uio structure will not be provided
4012 */
4013 if (uio) {
4014 if (headOff < uio->uio_offset) {
4015 zero_cnt = uio->uio_offset - headOff;
4016 zero_off = headOff;
4017 }
4018 } else if (headOff < newEOF) {
4019 zero_cnt = newEOF - headOff;
4020 zero_off = headOff;
4021 }
4022 } else {
4023 if (uio && uio->uio_offset > oldEOF) {
4024 zero_off = uio->uio_offset & ~PAGE_MASK_64;
4025
4026 if (zero_off >= oldEOF) {
4027 zero_cnt = uio->uio_offset - zero_off;
4028
4029 flags |= IO_HEADZEROFILL;
4030 }
4031 }
4032 }
4033 if (flags & IO_TAILZEROFILL) {
4034 if (uio) {
4035 zero_off1 = uio->uio_offset + io_req_size;
4036
4037 if (zero_off1 < tailOff) {
4038 zero_cnt1 = tailOff - zero_off1;
4039 }
4040 }
4041 } else {
4042 if (uio && newEOF > oldEOF) {
4043 zero_off1 = uio->uio_offset + io_req_size;
4044
4045 if (zero_off1 == newEOF && (zero_off1 & PAGE_MASK_64)) {
4046 zero_cnt1 = PAGE_SIZE_64 - (zero_off1 & PAGE_MASK_64);
4047
4048 flags |= IO_TAILZEROFILL;
4049 }
4050 }
4051 }
4052 if (zero_cnt == 0 && uio == (struct uio *) 0) {
4053 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 40)) | DBG_FUNC_END,
4054 retval, 0, 0, 0, 0);
4055 return 0;
4056 }
4057 if (uio) {
4058 write_off = uio->uio_offset;
4059 write_cnt = (int)uio_resid(uio);
4060 /*
4061 * delay updating the sequential write info
4062 * in the control block until we've obtained
4063 * the lock for it
4064 */
4065 first_pass = TRUE;
4066 }
4067 while ((total_size = (io_resid + zero_cnt + zero_cnt1)) && retval == 0) {
4068 /*
4069 * for this iteration of the loop, figure out where our starting point is
4070 */
4071 if (zero_cnt) {
4072 start_offset = (int)(zero_off & PAGE_MASK_64);
4073 upl_f_offset = zero_off - start_offset;
4074 } else if (io_resid) {
4075 start_offset = (int)(uio->uio_offset & PAGE_MASK_64);
4076 upl_f_offset = uio->uio_offset - start_offset;
4077 } else {
4078 start_offset = (int)(zero_off1 & PAGE_MASK_64);
4079 upl_f_offset = zero_off1 - start_offset;
4080 }
4081 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 46)) | DBG_FUNC_NONE,
4082 (int)zero_off, (int)zero_cnt, (int)zero_off1, (int)zero_cnt1, 0);
4083
4084 if (total_size > max_io_size) {
4085 total_size = max_io_size;
4086 }
4087
4088 cl.b_addr = (daddr64_t)(upl_f_offset / PAGE_SIZE_64);
4089
4090 if (uio && ((flags & (IO_SYNC | IO_HEADZEROFILL | IO_TAILZEROFILL)) == 0)) {
4091 /*
4092 * assumption... total_size <= io_resid
4093 * because IO_HEADZEROFILL and IO_TAILZEROFILL not set
4094 */
4095 if ((start_offset + total_size) > max_io_size) {
4096 total_size = max_io_size - start_offset;
4097 }
4098 xfer_resid = (int)total_size;
4099
4100 retval = cluster_copy_ubc_data_internal(vp, uio, &xfer_resid, 1, 1);
4101
4102 if (retval) {
4103 break;
4104 }
4105
4106 io_resid -= (total_size - xfer_resid);
4107 total_size = xfer_resid;
4108 start_offset = (int)(uio->uio_offset & PAGE_MASK_64);
4109 upl_f_offset = uio->uio_offset - start_offset;
4110
4111 if (total_size == 0) {
4112 if (start_offset) {
4113 /*
4114 * the write did not finish on a page boundary
4115 * which will leave upl_f_offset pointing to the
4116 * beginning of the last page written instead of
4117 * the page beyond it... bump it in this case
4118 * so that the cluster code records the last page
4119 * written as dirty
4120 */
4121 upl_f_offset += PAGE_SIZE_64;
4122 }
4123 upl_size = 0;
4124
4125 goto check_cluster;
4126 }
4127 }
4128 /*
4129 * compute the size of the upl needed to encompass
4130 * the requested write... limit each call to cluster_io
4131 * to the maximum UPL size... cluster_io will clip if
4132 * this exceeds the maximum io_size for the device,
4133 * make sure to account for
4134 * a starting offset that's not page aligned
4135 */
4136 upl_size = (start_offset + total_size + (PAGE_SIZE - 1)) & ~PAGE_MASK;
4137
4138 if (upl_size > max_io_size) {
4139 upl_size = max_io_size;
4140 }
4141
4142 pages_in_upl = (int)(upl_size / PAGE_SIZE);
4143 io_size = (int)(upl_size - start_offset);
4144
4145 if ((long long)io_size > total_size) {
4146 io_size = (int)total_size;
4147 }
4148
4149 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 41)) | DBG_FUNC_START, upl_size, io_size, total_size, 0, 0);
4150
4151
4152 /*
4153 * Gather the pages from the buffer cache.
4154 * The UPL_WILL_MODIFY flag lets the UPL subsystem know
4155 * that we intend to modify these pages.
4156 */
4157 kret = ubc_create_upl_kernel(vp,
4158 upl_f_offset,
4159 (int)upl_size,
4160 &upl,
4161 &pl,
4162 UPL_SET_LITE | ((uio != NULL && (uio->uio_flags & UIO_FLAGS_IS_COMPRESSED_FILE)) ? 0 : UPL_WILL_MODIFY),
4163 VM_KERN_MEMORY_FILE);
4164 if (kret != KERN_SUCCESS) {
4165 panic("cluster_write_copy: failed to get pagelist");
4166 }
4167
4168 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 41)) | DBG_FUNC_END,
4169 upl, (int)upl_f_offset, start_offset, 0, 0);
4170
4171 if (start_offset && upl_f_offset < oldEOF && !upl_valid_page(pl, 0)) {
4172 int read_size;
4173
4174 /*
4175 * we're starting in the middle of the first page of the upl
4176 * and the page isn't currently valid, so we're going to have
4177 * to read it in first... this is a synchronous operation
4178 */
4179 read_size = PAGE_SIZE;
4180
4181 if ((upl_f_offset + read_size) > oldEOF) {
4182 read_size = (int)(oldEOF - upl_f_offset);
4183 }
4184
4185 retval = cluster_io(vp, upl, 0, upl_f_offset, read_size,
4186 CL_READ | bflag, (buf_t)NULL, (struct clios *)NULL, callback, callback_arg);
4187 if (retval) {
4188 /*
4189 * we had an error during the read which causes us to abort
4190 * the current cluster_write request... before we do, we need
4191 * to release the rest of the pages in the upl without modifying
4192 * there state and mark the failed page in error
4193 */
4194 ubc_upl_abort_range(upl, 0, PAGE_SIZE, UPL_ABORT_DUMP_PAGES | UPL_ABORT_FREE_ON_EMPTY);
4195
4196 if (upl_size > PAGE_SIZE) {
4197 ubc_upl_abort_range(upl, 0, (upl_size_t)upl_size,
4198 UPL_ABORT_FREE_ON_EMPTY);
4199 }
4200
4201 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 45)) | DBG_FUNC_NONE,
4202 upl, 0, 0, retval, 0);
4203 break;
4204 }
4205 }
4206 if ((start_offset == 0 || upl_size > PAGE_SIZE) && ((start_offset + io_size) & PAGE_MASK)) {
4207 /*
4208 * the last offset we're writing to in this upl does not end on a page
4209 * boundary... if it's not beyond the old EOF, then we'll also need to
4210 * pre-read this page in if it isn't already valid
4211 */
4212 upl_offset = upl_size - PAGE_SIZE;
4213
4214 if ((upl_f_offset + start_offset + io_size) < oldEOF &&
4215 !upl_valid_page(pl, (int)(upl_offset / PAGE_SIZE))) {
4216 int read_size;
4217
4218 read_size = PAGE_SIZE;
4219
4220 if ((off_t)(upl_f_offset + upl_offset + read_size) > oldEOF) {
4221 read_size = (int)(oldEOF - (upl_f_offset + upl_offset));
4222 }
4223
4224 retval = cluster_io(vp, upl, upl_offset, upl_f_offset + upl_offset, read_size,
4225 CL_READ | bflag, (buf_t)NULL, (struct clios *)NULL, callback, callback_arg);
4226 if (retval) {
4227 /*
4228 * we had an error during the read which causes us to abort
4229 * the current cluster_write request... before we do, we
4230 * need to release the rest of the pages in the upl without
4231 * modifying there state and mark the failed page in error
4232 */
4233 ubc_upl_abort_range(upl, (upl_offset_t)upl_offset, PAGE_SIZE, UPL_ABORT_DUMP_PAGES | UPL_ABORT_FREE_ON_EMPTY);
4234
4235 if (upl_size > PAGE_SIZE) {
4236 ubc_upl_abort_range(upl, 0, (upl_size_t)upl_size, UPL_ABORT_FREE_ON_EMPTY);
4237 }
4238
4239 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 45)) | DBG_FUNC_NONE,
4240 upl, 0, 0, retval, 0);
4241 break;
4242 }
4243 }
4244 }
4245 xfer_resid = io_size;
4246 io_offset = start_offset;
4247
4248 while (zero_cnt && xfer_resid) {
4249 if (zero_cnt < (long long)xfer_resid) {
4250 bytes_to_zero = (int)zero_cnt;
4251 } else {
4252 bytes_to_zero = xfer_resid;
4253 }
4254
4255 bytes_to_zero = cluster_zero_range(upl, pl, flags, io_offset, zero_off, upl_f_offset, bytes_to_zero);
4256
4257 xfer_resid -= bytes_to_zero;
4258 zero_cnt -= bytes_to_zero;
4259 zero_off += bytes_to_zero;
4260 io_offset += bytes_to_zero;
4261 }
4262 if (xfer_resid && io_resid) {
4263 u_int32_t io_requested;
4264
4265 bytes_to_move = min(io_resid, xfer_resid);
4266 io_requested = bytes_to_move;
4267
4268 retval = cluster_copy_upl_data(uio, upl, io_offset, (int *)&io_requested);
4269
4270 if (retval) {
4271 ubc_upl_abort_range(upl, 0, (upl_size_t)upl_size, UPL_ABORT_FREE_ON_EMPTY);
4272
4273 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 45)) | DBG_FUNC_NONE,
4274 upl, 0, 0, retval, 0);
4275 } else {
4276 io_resid -= bytes_to_move;
4277 xfer_resid -= bytes_to_move;
4278 io_offset += bytes_to_move;
4279 }
4280 }
4281 while (xfer_resid && zero_cnt1 && retval == 0) {
4282 if (zero_cnt1 < (long long)xfer_resid) {
4283 bytes_to_zero = (int)zero_cnt1;
4284 } else {
4285 bytes_to_zero = xfer_resid;
4286 }
4287
4288 bytes_to_zero = cluster_zero_range(upl, pl, flags, io_offset, zero_off1, upl_f_offset, bytes_to_zero);
4289
4290 xfer_resid -= bytes_to_zero;
4291 zero_cnt1 -= bytes_to_zero;
4292 zero_off1 += bytes_to_zero;
4293 io_offset += bytes_to_zero;
4294 }
4295 if (retval == 0) {
4296 int do_zeroing = 1;
4297
4298 io_size += start_offset;
4299
4300 /* Force more restrictive zeroing behavior only on APFS */
4301 if ((vnode_tag(vp) == VT_APFS) && (newEOF < oldEOF)) {
4302 do_zeroing = 0;
4303 }
4304
4305 if (do_zeroing && (upl_f_offset + io_size) >= newEOF && (u_int)io_size < upl_size) {
4306 /*
4307 * if we're extending the file with this write
4308 * we'll zero fill the rest of the page so that
4309 * if the file gets extended again in such a way as to leave a
4310 * hole starting at this EOF, we'll have zero's in the correct spot
4311 */
4312 cluster_zero(upl, io_size, (int)(upl_size - io_size), NULL);
4313 }
4314 /*
4315 * release the upl now if we hold one since...
4316 * 1) pages in it may be present in the sparse cluster map
4317 * and may span 2 separate buckets there... if they do and
4318 * we happen to have to flush a bucket to make room and it intersects
4319 * this upl, a deadlock may result on page BUSY
4320 * 2) we're delaying the I/O... from this point forward we're just updating
4321 * the cluster state... no need to hold the pages, so commit them
4322 * 3) IO_SYNC is set...
4323 * because we had to ask for a UPL that provides currenty non-present pages, the
4324 * UPL has been automatically set to clear the dirty flags (both software and hardware)
4325 * upon committing it... this is not the behavior we want since it's possible for
4326 * pages currently present as part of a mapped file to be dirtied while the I/O is in flight.
4327 * we'll pick these pages back up later with the correct behavior specified.
4328 * 4) we don't want to hold pages busy in a UPL and then block on the cluster lock... if a flush
4329 * of this vnode is in progress, we will deadlock if the pages being flushed intersect the pages
4330 * we hold since the flushing context is holding the cluster lock.
4331 */
4332 ubc_upl_commit_range(upl, 0, (upl_size_t)upl_size,
4333 UPL_COMMIT_SET_DIRTY | UPL_COMMIT_INACTIVATE | UPL_COMMIT_FREE_ON_EMPTY);
4334 check_cluster:
4335 /*
4336 * calculate the last logical block number
4337 * that this delayed I/O encompassed
4338 */
4339 cl.e_addr = (daddr64_t)((upl_f_offset + (off_t)upl_size) / PAGE_SIZE_64);
4340
4341 if (flags & IO_SYNC) {
4342 /*
4343 * if the IO_SYNC flag is set than we need to bypass
4344 * any clustering and immediately issue the I/O
4345 *
4346 * we don't hold the lock at this point
4347 *
4348 * we've already dropped the current upl, so pick it back up with COPYOUT_FROM set
4349 * so that we correctly deal with a change in state of the hardware modify bit...
4350 * we do this via cluster_push_now... by passing along the IO_SYNC flag, we force
4351 * cluster_push_now to wait until all the I/Os have completed... cluster_push_now is also
4352 * responsible for generating the correct sized I/O(s)
4353 */
4354 retval = cluster_push_now(vp, &cl, newEOF, flags, callback, callback_arg, FALSE);
4355 } else {
4356 boolean_t defer_writes = FALSE;
4357
4358 if (vfs_flags(vp->v_mount) & MNT_DEFWRITE) {
4359 defer_writes = TRUE;
4360 }
4361
4362 cluster_update_state_internal(vp, &cl, flags, defer_writes, &first_pass,
4363 write_off, write_cnt, newEOF, callback, callback_arg, FALSE);
4364 }
4365 }
4366 }
4367 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 40)) | DBG_FUNC_END, retval, 0, io_resid, 0, 0);
4368
4369 return retval;
4370 }
4371
4372
4373
4374 int
cluster_read(vnode_t vp,struct uio * uio,off_t filesize,int xflags)4375 cluster_read(vnode_t vp, struct uio *uio, off_t filesize, int xflags)
4376 {
4377 return cluster_read_ext(vp, uio, filesize, xflags, NULL, NULL);
4378 }
4379
4380
4381 int
cluster_read_ext(vnode_t vp,struct uio * uio,off_t filesize,int xflags,int (* callback)(buf_t,void *),void * callback_arg)4382 cluster_read_ext(vnode_t vp, struct uio *uio, off_t filesize, int xflags, int (*callback)(buf_t, void *), void *callback_arg)
4383 {
4384 int retval = 0;
4385 int flags;
4386 user_ssize_t cur_resid;
4387 u_int32_t io_size;
4388 u_int32_t read_length = 0;
4389 int read_type = IO_COPY;
4390 bool check_io_type;
4391
4392 flags = xflags;
4393
4394 if (vp->v_flag & VNOCACHE_DATA) {
4395 flags |= IO_NOCACHE;
4396 }
4397 if ((vp->v_flag & VRAOFF) || speculative_reads_disabled) {
4398 flags |= IO_RAOFF;
4399 }
4400
4401 if (flags & IO_SKIP_ENCRYPTION) {
4402 flags |= IO_ENCRYPTED;
4403 }
4404
4405 /*
4406 * do a read through the cache if one of the following is true....
4407 * NOCACHE is not true
4408 * the uio request doesn't target USERSPACE (unless IO_NOCACHE_SYSSPACE is also set)
4409 * Alternatively, if IO_ENCRYPTED is set, then we want to bypass the cache as well.
4410 * Reading encrypted data from a CP filesystem should never result in the data touching
4411 * the UBC.
4412 *
4413 * otherwise, find out if we want the direct or contig variant for
4414 * the first vector in the uio request
4415 */
4416 check_io_type = false;
4417 if (flags & IO_NOCACHE) {
4418 if (UIO_SEG_IS_USER_SPACE(uio->uio_segflg)) {
4419 /*
4420 * no-cache to user-space: ok to consider IO_DIRECT.
4421 */
4422 check_io_type = true;
4423 } else if (uio->uio_segflg == UIO_SYSSPACE &&
4424 (flags & IO_NOCACHE_SYSSPACE)) {
4425 /*
4426 * no-cache to kernel-space but w/ IO_NOCACHE_SYSSPACE:
4427 * ok to consider IO_DIRECT.
4428 * The caller should make sure to target kernel buffer
4429 * that is backed by regular anonymous memory (i.e.
4430 * not backed by the kernel object or an external
4431 * memory manager like device memory or a file).
4432 */
4433 check_io_type = true;
4434 }
4435 } else if (flags & IO_ENCRYPTED) {
4436 check_io_type = true;
4437 }
4438 if (check_io_type) {
4439 retval = cluster_io_type(uio, &read_type, &read_length, 0);
4440 }
4441
4442 while ((cur_resid = uio_resid(uio)) && uio->uio_offset < filesize && retval == 0) {
4443 switch (read_type) {
4444 case IO_COPY:
4445 /*
4446 * make sure the uio_resid isn't too big...
4447 * internally, we want to handle all of the I/O in
4448 * chunk sizes that fit in a 32 bit int
4449 */
4450 if (cur_resid > (user_ssize_t)(MAX_IO_REQUEST_SIZE)) {
4451 io_size = MAX_IO_REQUEST_SIZE;
4452 } else {
4453 io_size = (u_int32_t)cur_resid;
4454 }
4455
4456 retval = cluster_read_copy(vp, uio, io_size, filesize, flags, callback, callback_arg);
4457 break;
4458
4459 case IO_DIRECT:
4460 retval = cluster_read_direct(vp, uio, filesize, &read_type, &read_length, flags, callback, callback_arg);
4461 break;
4462
4463 case IO_CONTIG:
4464 retval = cluster_read_contig(vp, uio, filesize, &read_type, &read_length, callback, callback_arg, flags);
4465 break;
4466
4467 case IO_UNKNOWN:
4468 retval = cluster_io_type(uio, &read_type, &read_length, 0);
4469 break;
4470 }
4471 }
4472 return retval;
4473 }
4474
4475
4476
4477 static void
cluster_read_upl_release(upl_t upl,int start_pg,int last_pg,int take_reference)4478 cluster_read_upl_release(upl_t upl, int start_pg, int last_pg, int take_reference)
4479 {
4480 int range;
4481 int abort_flags = UPL_ABORT_FREE_ON_EMPTY;
4482
4483 if ((range = last_pg - start_pg)) {
4484 if (take_reference) {
4485 abort_flags |= UPL_ABORT_REFERENCE;
4486 }
4487
4488 ubc_upl_abort_range(upl, start_pg * PAGE_SIZE, range * PAGE_SIZE, abort_flags);
4489 }
4490 }
4491
4492
4493 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)4494 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)
4495 {
4496 upl_page_info_t *pl;
4497 upl_t upl = NULL;
4498 vm_offset_t upl_offset;
4499 u_int32_t upl_size;
4500 off_t upl_f_offset;
4501 int start_offset;
4502 int start_pg;
4503 int last_pg;
4504 int uio_last = 0;
4505 int pages_in_upl;
4506 off_t max_size;
4507 off_t last_ioread_offset;
4508 off_t last_request_offset;
4509 kern_return_t kret;
4510 int error = 0;
4511 int retval = 0;
4512 u_int32_t size_of_prefetch;
4513 u_int32_t xsize;
4514 u_int32_t io_size;
4515 u_int32_t max_rd_size;
4516 u_int32_t max_io_size;
4517 u_int32_t max_prefetch;
4518 u_int rd_ahead_enabled = 1;
4519 u_int prefetch_enabled = 1;
4520 struct cl_readahead * rap;
4521 struct clios iostate;
4522 struct cl_extent extent;
4523 int bflag;
4524 int take_reference = 1;
4525 int policy = IOPOL_DEFAULT;
4526 boolean_t iolock_inited = FALSE;
4527
4528 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 32)) | DBG_FUNC_START,
4529 (int)uio->uio_offset, io_req_size, (int)filesize, flags, 0);
4530
4531 if (flags & IO_ENCRYPTED) {
4532 panic("encrypted blocks will hit UBC!");
4533 }
4534
4535 policy = throttle_get_io_policy(NULL);
4536
4537 if (policy == THROTTLE_LEVEL_TIER3 || policy == THROTTLE_LEVEL_TIER2 || (flags & IO_NOCACHE)) {
4538 take_reference = 0;
4539 }
4540
4541 if (flags & IO_PASSIVE) {
4542 bflag = CL_PASSIVE;
4543 } else {
4544 bflag = 0;
4545 }
4546
4547 if (flags & IO_NOCACHE) {
4548 bflag |= CL_NOCACHE;
4549 }
4550
4551 if (flags & IO_SKIP_ENCRYPTION) {
4552 bflag |= CL_ENCRYPTED;
4553 }
4554
4555 max_io_size = cluster_max_io_size(vp->v_mount, CL_READ);
4556 max_prefetch = cluster_max_prefetch(vp, max_io_size, prefetch_max);
4557 max_rd_size = max_prefetch;
4558
4559 last_request_offset = uio->uio_offset + io_req_size;
4560
4561 if (last_request_offset > filesize) {
4562 last_request_offset = filesize;
4563 }
4564
4565 if ((flags & (IO_RAOFF | IO_NOCACHE)) || ((last_request_offset & ~PAGE_MASK_64) == (uio->uio_offset & ~PAGE_MASK_64))) {
4566 rd_ahead_enabled = 0;
4567 rap = NULL;
4568 } else {
4569 if (cluster_is_throttled(vp)) {
4570 /*
4571 * we're in the throttle window, at the very least
4572 * we want to limit the size of the I/O we're about
4573 * to issue
4574 */
4575 rd_ahead_enabled = 0;
4576 prefetch_enabled = 0;
4577
4578 max_rd_size = calculate_max_throttle_size(vp);
4579 }
4580 if ((rap = cluster_get_rap(vp)) == NULL) {
4581 rd_ahead_enabled = 0;
4582 } else {
4583 extent.b_addr = uio->uio_offset / PAGE_SIZE_64;
4584 extent.e_addr = (last_request_offset - 1) / PAGE_SIZE_64;
4585 }
4586 }
4587 if (rap != NULL && rap->cl_ralen && (rap->cl_lastr == extent.b_addr || (rap->cl_lastr + 1) == extent.b_addr)) {
4588 /*
4589 * determine if we already have a read-ahead in the pipe courtesy of the
4590 * last read systemcall that was issued...
4591 * if so, pick up it's extent to determine where we should start
4592 * with respect to any read-ahead that might be necessary to
4593 * garner all the data needed to complete this read systemcall
4594 */
4595 last_ioread_offset = (rap->cl_maxra * PAGE_SIZE_64) + PAGE_SIZE_64;
4596
4597 if (last_ioread_offset < uio->uio_offset) {
4598 last_ioread_offset = (off_t)0;
4599 } else if (last_ioread_offset > last_request_offset) {
4600 last_ioread_offset = last_request_offset;
4601 }
4602 } else {
4603 last_ioread_offset = (off_t)0;
4604 }
4605
4606 while (io_req_size && uio->uio_offset < filesize && retval == 0) {
4607 max_size = filesize - uio->uio_offset;
4608 bool leftover_upl_aborted = false;
4609
4610 if ((off_t)(io_req_size) < max_size) {
4611 io_size = io_req_size;
4612 } else {
4613 io_size = (u_int32_t)max_size;
4614 }
4615
4616 if (!(flags & IO_NOCACHE)) {
4617 while (io_size) {
4618 u_int32_t io_resid;
4619 u_int32_t io_requested;
4620
4621 /*
4622 * if we keep finding the pages we need already in the cache, then
4623 * don't bother to call cluster_read_prefetch since it costs CPU cycles
4624 * to determine that we have all the pages we need... once we miss in
4625 * the cache and have issued an I/O, than we'll assume that we're likely
4626 * to continue to miss in the cache and it's to our advantage to try and prefetch
4627 */
4628 if (last_request_offset && last_ioread_offset && (size_of_prefetch = (u_int32_t)(last_request_offset - last_ioread_offset))) {
4629 if ((last_ioread_offset - uio->uio_offset) <= max_rd_size && prefetch_enabled) {
4630 /*
4631 * we've already issued I/O for this request and
4632 * there's still work to do and
4633 * our prefetch stream is running dry, so issue a
4634 * pre-fetch I/O... the I/O latency will overlap
4635 * with the copying of the data
4636 */
4637 if (size_of_prefetch > max_rd_size) {
4638 size_of_prefetch = max_rd_size;
4639 }
4640
4641 size_of_prefetch = cluster_read_prefetch(vp, last_ioread_offset, size_of_prefetch, filesize, callback, callback_arg, bflag);
4642
4643 last_ioread_offset += (off_t)(size_of_prefetch * PAGE_SIZE);
4644
4645 if (last_ioread_offset > last_request_offset) {
4646 last_ioread_offset = last_request_offset;
4647 }
4648 }
4649 }
4650 /*
4651 * limit the size of the copy we're about to do so that
4652 * we can notice that our I/O pipe is running dry and
4653 * get the next I/O issued before it does go dry
4654 */
4655 if (last_ioread_offset && io_size > (max_io_size / 4)) {
4656 io_resid = (max_io_size / 4);
4657 } else {
4658 io_resid = io_size;
4659 }
4660
4661 io_requested = io_resid;
4662
4663 retval = cluster_copy_ubc_data_internal(vp, uio, (int *)&io_resid, 0, take_reference);
4664
4665 xsize = io_requested - io_resid;
4666
4667 io_size -= xsize;
4668 io_req_size -= xsize;
4669
4670 if (retval || io_resid) {
4671 /*
4672 * if we run into a real error or
4673 * a page that is not in the cache
4674 * we need to leave streaming mode
4675 */
4676 break;
4677 }
4678
4679 if (rd_ahead_enabled && (io_size == 0 || last_ioread_offset == last_request_offset)) {
4680 /*
4681 * we're already finished the I/O for this read request
4682 * let's see if we should do a read-ahead
4683 */
4684 cluster_read_ahead(vp, &extent, filesize, rap, callback, callback_arg, bflag);
4685 }
4686 }
4687 if (retval) {
4688 break;
4689 }
4690 if (io_size == 0) {
4691 if (rap != NULL) {
4692 if (extent.e_addr < rap->cl_lastr) {
4693 rap->cl_maxra = 0;
4694 }
4695 rap->cl_lastr = extent.e_addr;
4696 }
4697 break;
4698 }
4699 /*
4700 * recompute max_size since cluster_copy_ubc_data_internal
4701 * may have advanced uio->uio_offset
4702 */
4703 max_size = filesize - uio->uio_offset;
4704 }
4705
4706 iostate.io_completed = 0;
4707 iostate.io_issued = 0;
4708 iostate.io_error = 0;
4709 iostate.io_wanted = 0;
4710
4711 if ((flags & IO_RETURN_ON_THROTTLE)) {
4712 if (cluster_is_throttled(vp) == THROTTLE_NOW) {
4713 if (!cluster_io_present_in_BC(vp, uio->uio_offset)) {
4714 /*
4715 * we're in the throttle window and at least 1 I/O
4716 * has already been issued by a throttleable thread
4717 * in this window, so return with EAGAIN to indicate
4718 * to the FS issuing the cluster_read call that it
4719 * should now throttle after dropping any locks
4720 */
4721 throttle_info_update_by_mount(vp->v_mount);
4722
4723 retval = EAGAIN;
4724 break;
4725 }
4726 }
4727 }
4728
4729 /*
4730 * compute the size of the upl needed to encompass
4731 * the requested read... limit each call to cluster_io
4732 * to the maximum UPL size... cluster_io will clip if
4733 * this exceeds the maximum io_size for the device,
4734 * make sure to account for
4735 * a starting offset that's not page aligned
4736 */
4737 start_offset = (int)(uio->uio_offset & PAGE_MASK_64);
4738 upl_f_offset = uio->uio_offset - (off_t)start_offset;
4739
4740 if (io_size > max_rd_size) {
4741 io_size = max_rd_size;
4742 }
4743
4744 upl_size = (start_offset + io_size + (PAGE_SIZE - 1)) & ~PAGE_MASK;
4745
4746 if (flags & IO_NOCACHE) {
4747 if (upl_size > max_io_size) {
4748 upl_size = max_io_size;
4749 }
4750 } else {
4751 if (upl_size > max_io_size / 4) {
4752 upl_size = max_io_size / 4;
4753 upl_size &= ~PAGE_MASK;
4754
4755 if (upl_size == 0) {
4756 upl_size = PAGE_SIZE;
4757 }
4758 }
4759 }
4760 pages_in_upl = upl_size / PAGE_SIZE;
4761
4762 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 33)) | DBG_FUNC_START,
4763 upl, (int)upl_f_offset, upl_size, start_offset, 0);
4764
4765 kret = ubc_create_upl_kernel(vp,
4766 upl_f_offset,
4767 upl_size,
4768 &upl,
4769 &pl,
4770 UPL_FILE_IO | UPL_SET_LITE,
4771 VM_KERN_MEMORY_FILE);
4772 if (kret != KERN_SUCCESS) {
4773 panic("cluster_read_copy: failed to get pagelist");
4774 }
4775
4776 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 33)) | DBG_FUNC_END,
4777 upl, (int)upl_f_offset, upl_size, start_offset, 0);
4778
4779 /*
4780 * scan from the beginning of the upl looking for the first
4781 * non-valid page.... this will become the first page in
4782 * the request we're going to make to 'cluster_io'... if all
4783 * of the pages are valid, we won't call through to 'cluster_io'
4784 */
4785 for (start_pg = 0; start_pg < pages_in_upl; start_pg++) {
4786 if (!upl_valid_page(pl, start_pg)) {
4787 break;
4788 }
4789 }
4790
4791 /*
4792 * scan from the starting invalid page looking for a valid
4793 * page before the end of the upl is reached, if we
4794 * find one, then it will be the last page of the request to
4795 * 'cluster_io'
4796 */
4797 for (last_pg = start_pg; last_pg < pages_in_upl; last_pg++) {
4798 if (upl_valid_page(pl, last_pg)) {
4799 break;
4800 }
4801 }
4802
4803 if (start_pg < last_pg) {
4804 /*
4805 * we found a range of 'invalid' pages that must be filled
4806 * if the last page in this range is the last page of the file
4807 * we may have to clip the size of it to keep from reading past
4808 * the end of the last physical block associated with the file
4809 */
4810 if (iolock_inited == FALSE) {
4811 lck_mtx_init(&iostate.io_mtxp, &cl_mtx_grp, LCK_ATTR_NULL);
4812
4813 iolock_inited = TRUE;
4814 }
4815 upl_offset = start_pg * PAGE_SIZE;
4816 io_size = (last_pg - start_pg) * PAGE_SIZE;
4817
4818 if ((off_t)(upl_f_offset + upl_offset + io_size) > filesize) {
4819 io_size = (u_int32_t)(filesize - (upl_f_offset + upl_offset));
4820 }
4821
4822 /*
4823 * Find out if this needs verification, we'll have to manage the UPL
4824 * diffrently if so. Note that this call only lets us know if
4825 * verification is enabled on this mount point, the actual verification
4826 * is performed in the File system.
4827 */
4828 size_t verify_block_size = 0;
4829 if ((VNOP_VERIFY(vp, start_offset, NULL, 0, &verify_block_size, NULL, VNODE_VERIFY_DEFAULT, NULL) == 0) /* && verify_block_size */) {
4830 for (uio_last = last_pg; uio_last < pages_in_upl; uio_last++) {
4831 if (!upl_valid_page(pl, uio_last)) {
4832 break;
4833 }
4834 }
4835 if (uio_last < pages_in_upl) {
4836 /*
4837 * there were some invalid pages beyond the valid pages
4838 * that we didn't issue an I/O for, just release them
4839 * unchanged now, so that any prefetch/readahed can
4840 * include them
4841 */
4842 ubc_upl_abort_range(upl, uio_last * PAGE_SIZE,
4843 (pages_in_upl - uio_last) * PAGE_SIZE, UPL_ABORT_FREE_ON_EMPTY);
4844 leftover_upl_aborted = true;
4845 }
4846 }
4847
4848 /*
4849 * issue an asynchronous read to cluster_io
4850 */
4851
4852 error = cluster_io(vp, upl, upl_offset, upl_f_offset + upl_offset,
4853 io_size, CL_READ | CL_ASYNC | bflag, (buf_t)NULL, &iostate, callback, callback_arg);
4854
4855 if (rap) {
4856 if (extent.e_addr < rap->cl_maxra) {
4857 /*
4858 * we've just issued a read for a block that should have been
4859 * in the cache courtesy of the read-ahead engine... something
4860 * has gone wrong with the pipeline, so reset the read-ahead
4861 * logic which will cause us to restart from scratch
4862 */
4863 rap->cl_maxra = 0;
4864 }
4865 }
4866 }
4867 if (error == 0) {
4868 /*
4869 * if the read completed successfully, or there was no I/O request
4870 * issued, than copy the data into user land via 'cluster_upl_copy_data'
4871 * we'll first add on any 'valid'
4872 * pages that were present in the upl when we acquired it.
4873 */
4874 u_int val_size;
4875
4876 if (!leftover_upl_aborted) {
4877 for (uio_last = last_pg; uio_last < pages_in_upl; uio_last++) {
4878 if (!upl_valid_page(pl, uio_last)) {
4879 break;
4880 }
4881 }
4882 if (uio_last < pages_in_upl) {
4883 /*
4884 * there were some invalid pages beyond the valid pages
4885 * that we didn't issue an I/O for, just release them
4886 * unchanged now, so that any prefetch/readahed can
4887 * include them
4888 */
4889 ubc_upl_abort_range(upl, uio_last * PAGE_SIZE,
4890 (pages_in_upl - uio_last) * PAGE_SIZE, UPL_ABORT_FREE_ON_EMPTY);
4891 }
4892 }
4893
4894 /*
4895 * compute size to transfer this round, if io_req_size is
4896 * still non-zero after this attempt, we'll loop around and
4897 * set up for another I/O.
4898 */
4899 val_size = (uio_last * PAGE_SIZE) - start_offset;
4900
4901 if (val_size > max_size) {
4902 val_size = (u_int)max_size;
4903 }
4904
4905 if (val_size > io_req_size) {
4906 val_size = io_req_size;
4907 }
4908
4909 if ((uio->uio_offset + val_size) > last_ioread_offset) {
4910 last_ioread_offset = uio->uio_offset + val_size;
4911 }
4912
4913 if ((size_of_prefetch = (u_int32_t)(last_request_offset - last_ioread_offset)) && prefetch_enabled) {
4914 if ((last_ioread_offset - (uio->uio_offset + val_size)) <= upl_size) {
4915 /*
4916 * if there's still I/O left to do for this request, and...
4917 * we're not in hard throttle mode, and...
4918 * we're close to using up the previous prefetch, then issue a
4919 * new pre-fetch I/O... the I/O latency will overlap
4920 * with the copying of the data
4921 */
4922 if (size_of_prefetch > max_rd_size) {
4923 size_of_prefetch = max_rd_size;
4924 }
4925
4926 size_of_prefetch = cluster_read_prefetch(vp, last_ioread_offset, size_of_prefetch, filesize, callback, callback_arg, bflag);
4927
4928 last_ioread_offset += (off_t)(size_of_prefetch * PAGE_SIZE);
4929
4930 if (last_ioread_offset > last_request_offset) {
4931 last_ioread_offset = last_request_offset;
4932 }
4933 }
4934 } else if ((uio->uio_offset + val_size) == last_request_offset) {
4935 /*
4936 * this transfer will finish this request, so...
4937 * let's try to read ahead if we're in
4938 * a sequential access pattern and we haven't
4939 * explicitly disabled it
4940 */
4941 if (rd_ahead_enabled) {
4942 cluster_read_ahead(vp, &extent, filesize, rap, callback, callback_arg, bflag);
4943 }
4944
4945 if (rap != NULL) {
4946 if (extent.e_addr < rap->cl_lastr) {
4947 rap->cl_maxra = 0;
4948 }
4949 rap->cl_lastr = extent.e_addr;
4950 }
4951 }
4952 if (iolock_inited == TRUE) {
4953 cluster_iostate_wait(&iostate, 0, "cluster_read_copy");
4954 }
4955
4956 if (iostate.io_error) {
4957 error = iostate.io_error;
4958 } else {
4959 u_int32_t io_requested;
4960
4961 io_requested = val_size;
4962
4963 retval = cluster_copy_upl_data(uio, upl, start_offset, (int *)&io_requested);
4964
4965 io_req_size -= (val_size - io_requested);
4966 }
4967 } else {
4968 if (iolock_inited == TRUE) {
4969 cluster_iostate_wait(&iostate, 0, "cluster_read_copy");
4970 }
4971 }
4972 if (start_pg < last_pg) {
4973 /*
4974 * compute the range of pages that we actually issued an I/O for
4975 * and either commit them as valid if the I/O succeeded
4976 * or abort them if the I/O failed or we're not supposed to
4977 * keep them in the cache
4978 */
4979 io_size = (last_pg - start_pg) * PAGE_SIZE;
4980
4981 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 35)) | DBG_FUNC_START, upl, start_pg * PAGE_SIZE, io_size, error, 0);
4982
4983 if (error || (flags & IO_NOCACHE)) {
4984 ubc_upl_abort_range(upl, start_pg * PAGE_SIZE, io_size,
4985 UPL_ABORT_DUMP_PAGES | UPL_ABORT_FREE_ON_EMPTY);
4986 } else {
4987 int commit_flags = UPL_COMMIT_CLEAR_DIRTY | UPL_COMMIT_FREE_ON_EMPTY;
4988
4989 if (take_reference) {
4990 commit_flags |= UPL_COMMIT_INACTIVATE;
4991 } else {
4992 commit_flags |= UPL_COMMIT_SPECULATE;
4993 }
4994
4995 ubc_upl_commit_range(upl, start_pg * PAGE_SIZE, io_size, commit_flags);
4996 }
4997 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 35)) | DBG_FUNC_END, upl, start_pg * PAGE_SIZE, io_size, error, 0);
4998 }
4999 if ((last_pg - start_pg) < pages_in_upl) {
5000 /*
5001 * the set of pages that we issued an I/O for did not encompass
5002 * the entire upl... so just release these without modifying
5003 * their state
5004 */
5005 if (error) {
5006 if (leftover_upl_aborted) {
5007 ubc_upl_abort_range(upl, start_pg * PAGE_SIZE, (uio_last - start_pg) * PAGE_SIZE,
5008 UPL_ABORT_FREE_ON_EMPTY);
5009 } else {
5010 ubc_upl_abort_range(upl, 0, upl_size, UPL_ABORT_FREE_ON_EMPTY);
5011 }
5012 } else {
5013 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 35)) | DBG_FUNC_START,
5014 upl, -1, pages_in_upl - (last_pg - start_pg), 0, 0);
5015
5016 /*
5017 * handle any valid pages at the beginning of
5018 * the upl... release these appropriately
5019 */
5020 cluster_read_upl_release(upl, 0, start_pg, take_reference);
5021
5022 /*
5023 * handle any valid pages immediately after the
5024 * pages we issued I/O for... ... release these appropriately
5025 */
5026 cluster_read_upl_release(upl, last_pg, uio_last, take_reference);
5027
5028 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 35)) | DBG_FUNC_END, upl, -1, -1, 0, 0);
5029 }
5030 }
5031 if (retval == 0) {
5032 retval = error;
5033 }
5034
5035 if (io_req_size) {
5036 uint32_t max_throttle_size = calculate_max_throttle_size(vp);
5037
5038 if (cluster_is_throttled(vp)) {
5039 /*
5040 * we're in the throttle window, at the very least
5041 * we want to limit the size of the I/O we're about
5042 * to issue
5043 */
5044 rd_ahead_enabled = 0;
5045 prefetch_enabled = 0;
5046 max_rd_size = max_throttle_size;
5047 } else {
5048 if (max_rd_size == max_throttle_size) {
5049 /*
5050 * coming out of throttled state
5051 */
5052 if (policy != THROTTLE_LEVEL_TIER3 && policy != THROTTLE_LEVEL_TIER2) {
5053 if (rap != NULL) {
5054 rd_ahead_enabled = 1;
5055 }
5056 prefetch_enabled = 1;
5057 }
5058 max_rd_size = max_prefetch;
5059 last_ioread_offset = 0;
5060 }
5061 }
5062 }
5063 }
5064 if (iolock_inited == TRUE) {
5065 /*
5066 * cluster_io returned an error after it
5067 * had already issued some I/O. we need
5068 * to wait for that I/O to complete before
5069 * we can destroy the iostate mutex...
5070 * 'retval' already contains the early error
5071 * so no need to pick it up from iostate.io_error
5072 */
5073 cluster_iostate_wait(&iostate, 0, "cluster_read_copy");
5074
5075 lck_mtx_destroy(&iostate.io_mtxp, &cl_mtx_grp);
5076 }
5077 if (rap != NULL) {
5078 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 32)) | DBG_FUNC_END,
5079 (int)uio->uio_offset, io_req_size, rap->cl_lastr, retval, 0);
5080
5081 lck_mtx_unlock(&rap->cl_lockr);
5082 } else {
5083 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 32)) | DBG_FUNC_END,
5084 (int)uio->uio_offset, io_req_size, 0, retval, 0);
5085 }
5086
5087 return retval;
5088 }
5089
5090 /*
5091 * We don't want another read/write lock for every vnode in the system
5092 * so we keep a hash of them here. There should never be very many of
5093 * these around at any point in time.
5094 */
5095 cl_direct_read_lock_t *
cluster_lock_direct_read(vnode_t vp,lck_rw_type_t type)5096 cluster_lock_direct_read(vnode_t vp, lck_rw_type_t type)
5097 {
5098 struct cl_direct_read_locks *head
5099 = &cl_direct_read_locks[(uintptr_t)vp / sizeof(*vp)
5100 % CL_DIRECT_READ_LOCK_BUCKETS];
5101
5102 struct cl_direct_read_lock *lck, *new_lck = NULL;
5103
5104 for (;;) {
5105 lck_spin_lock(&cl_direct_read_spin_lock);
5106
5107 LIST_FOREACH(lck, head, chain) {
5108 if (lck->vp == vp) {
5109 ++lck->ref_count;
5110 lck_spin_unlock(&cl_direct_read_spin_lock);
5111 if (new_lck) {
5112 // Someone beat us to it, ditch the allocation
5113 lck_rw_destroy(&new_lck->rw_lock, &cl_mtx_grp);
5114 kfree_type(cl_direct_read_lock_t, new_lck);
5115 }
5116 lck_rw_lock(&lck->rw_lock, type);
5117 return lck;
5118 }
5119 }
5120
5121 if (new_lck) {
5122 // Use the lock we allocated
5123 LIST_INSERT_HEAD(head, new_lck, chain);
5124 lck_spin_unlock(&cl_direct_read_spin_lock);
5125 lck_rw_lock(&new_lck->rw_lock, type);
5126 return new_lck;
5127 }
5128
5129 lck_spin_unlock(&cl_direct_read_spin_lock);
5130
5131 // Allocate a new lock
5132 new_lck = kalloc_type(cl_direct_read_lock_t, Z_WAITOK);
5133 lck_rw_init(&new_lck->rw_lock, &cl_mtx_grp, LCK_ATTR_NULL);
5134 new_lck->vp = vp;
5135 new_lck->ref_count = 1;
5136
5137 // Got to go round again
5138 }
5139 }
5140
5141 void
cluster_unlock_direct_read(cl_direct_read_lock_t * lck)5142 cluster_unlock_direct_read(cl_direct_read_lock_t *lck)
5143 {
5144 lck_rw_done(&lck->rw_lock);
5145
5146 lck_spin_lock(&cl_direct_read_spin_lock);
5147 if (lck->ref_count == 1) {
5148 LIST_REMOVE(lck, chain);
5149 lck_spin_unlock(&cl_direct_read_spin_lock);
5150 lck_rw_destroy(&lck->rw_lock, &cl_mtx_grp);
5151 kfree_type(cl_direct_read_lock_t, lck);
5152 } else {
5153 --lck->ref_count;
5154 lck_spin_unlock(&cl_direct_read_spin_lock);
5155 }
5156 }
5157
5158 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)5159 cluster_read_direct(vnode_t vp, struct uio *uio, off_t filesize, int *read_type, u_int32_t *read_length,
5160 int flags, int (*callback)(buf_t, void *), void *callback_arg)
5161 {
5162 upl_t upl = NULL;
5163 upl_page_info_t *pl;
5164 off_t max_io_size;
5165 vm_offset_t upl_offset, vector_upl_offset = 0;
5166 upl_size_t upl_size = 0, vector_upl_size = 0;
5167 vm_size_t upl_needed_size;
5168 unsigned int pages_in_pl;
5169 upl_control_flags_t upl_flags;
5170 kern_return_t kret = KERN_SUCCESS;
5171 unsigned int i;
5172 int force_data_sync;
5173 int retval = 0;
5174 int no_zero_fill = 0;
5175 int io_flag = 0;
5176 int misaligned = 0;
5177 struct clios iostate;
5178 user_addr_t iov_base;
5179 u_int32_t io_req_size;
5180 u_int32_t offset_in_file;
5181 u_int32_t offset_in_iovbase;
5182 u_int32_t io_size;
5183 u_int32_t io_min;
5184 u_int32_t xsize;
5185 u_int32_t devblocksize;
5186 u_int32_t mem_alignment_mask;
5187 u_int32_t max_upl_size;
5188 u_int32_t max_rd_size;
5189 u_int32_t max_rd_ahead;
5190 u_int32_t max_vector_size;
5191 boolean_t io_throttled = FALSE;
5192
5193 u_int32_t vector_upl_iosize = 0;
5194 int issueVectorUPL = 0, useVectorUPL = (uio->uio_iovcnt > 1);
5195 off_t v_upl_uio_offset = 0;
5196 int vector_upl_index = 0;
5197 upl_t vector_upl = NULL;
5198 cl_direct_read_lock_t *lock = NULL;
5199
5200 assert(vm_map_page_shift(current_map()) >= PAGE_SHIFT);
5201
5202 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 70)) | DBG_FUNC_START,
5203 (int)uio->uio_offset, (int)filesize, *read_type, *read_length, 0);
5204
5205 max_upl_size = cluster_max_io_size(vp->v_mount, CL_READ);
5206
5207 max_rd_size = max_upl_size;
5208
5209 if (__improbable(os_mul_overflow(max_rd_size, IO_SCALE(vp, 2),
5210 &max_rd_ahead) || (max_rd_ahead > overlapping_read_max))) {
5211 max_rd_ahead = overlapping_read_max;
5212 }
5213
5214 io_flag = CL_COMMIT | CL_READ | CL_ASYNC | CL_NOZERO | CL_DIRECT_IO;
5215
5216 if (flags & IO_PASSIVE) {
5217 io_flag |= CL_PASSIVE;
5218 }
5219
5220 if (flags & IO_ENCRYPTED) {
5221 io_flag |= CL_RAW_ENCRYPTED;
5222 }
5223
5224 if (flags & IO_NOCACHE) {
5225 io_flag |= CL_NOCACHE;
5226 }
5227
5228 if (flags & IO_SKIP_ENCRYPTION) {
5229 io_flag |= CL_ENCRYPTED;
5230 }
5231
5232 iostate.io_completed = 0;
5233 iostate.io_issued = 0;
5234 iostate.io_error = 0;
5235 iostate.io_wanted = 0;
5236
5237 lck_mtx_init(&iostate.io_mtxp, &cl_mtx_grp, LCK_ATTR_NULL);
5238
5239 devblocksize = (u_int32_t)vp->v_mount->mnt_devblocksize;
5240 mem_alignment_mask = (u_int32_t)vp->v_mount->mnt_alignmentmask;
5241
5242 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 70)) | DBG_FUNC_NONE,
5243 (int)devblocksize, (int)mem_alignment_mask, 0, 0, 0);
5244
5245 if (devblocksize == 1) {
5246 /*
5247 * the AFP client advertises a devblocksize of 1
5248 * however, its BLOCKMAP routine maps to physical
5249 * blocks that are PAGE_SIZE in size...
5250 * therefore we can't ask for I/Os that aren't page aligned
5251 * or aren't multiples of PAGE_SIZE in size
5252 * by setting devblocksize to PAGE_SIZE, we re-instate
5253 * the old behavior we had before the mem_alignment_mask
5254 * changes went in...
5255 */
5256 devblocksize = PAGE_SIZE;
5257 }
5258
5259 /*
5260 * We are going to need this uio for the prefaulting later
5261 * especially for the cases where multiple non-contiguous
5262 * iovs are passed into this routine.
5263 *
5264 * Note that we only want to prefault for direct IOs to userspace buffers,
5265 * not kernel buffers.
5266 */
5267 uio_t uio_acct = NULL;
5268 if (uio->uio_segflg != UIO_SYSSPACE) {
5269 uio_acct = uio_duplicate(uio);
5270 }
5271
5272 next_dread:
5273 io_req_size = *read_length;
5274 iov_base = uio_curriovbase(uio);
5275
5276 offset_in_file = (u_int32_t)uio->uio_offset & (devblocksize - 1);
5277 offset_in_iovbase = (u_int32_t)iov_base & mem_alignment_mask;
5278
5279 if (vm_map_page_mask(current_map()) < PAGE_MASK) {
5280 /*
5281 * XXX TODO4K
5282 * Direct I/O might not work as expected from a 16k kernel space
5283 * to a 4k user space because each 4k chunk might point to
5284 * a different 16k physical page...
5285 * Let's go the "misaligned" way.
5286 */
5287 if (!misaligned) {
5288 DEBUG4K_VFS("forcing misaligned\n");
5289 }
5290 misaligned = 1;
5291 }
5292
5293 if (offset_in_file || offset_in_iovbase) {
5294 /*
5295 * one of the 2 important offsets is misaligned
5296 * so fire an I/O through the cache for this entire vector
5297 */
5298 misaligned = 1;
5299 }
5300 if (iov_base & (devblocksize - 1)) {
5301 /*
5302 * the offset in memory must be on a device block boundary
5303 * so that we can guarantee that we can generate an
5304 * I/O that ends on a page boundary in cluster_io
5305 */
5306 misaligned = 1;
5307 }
5308
5309 max_io_size = filesize - uio->uio_offset;
5310
5311 /*
5312 * The user must request IO in aligned chunks. If the
5313 * offset into the file is bad, or the userland pointer
5314 * is non-aligned, then we cannot service the encrypted IO request.
5315 */
5316 if (flags & IO_ENCRYPTED) {
5317 if (misaligned || (io_req_size & (devblocksize - 1))) {
5318 retval = EINVAL;
5319 }
5320
5321 max_io_size = roundup(max_io_size, devblocksize);
5322 }
5323
5324 if ((off_t)io_req_size > max_io_size) {
5325 io_req_size = (u_int32_t)max_io_size;
5326 }
5327
5328 /*
5329 * When we get to this point, we know...
5330 * -- the offset into the file is on a devblocksize boundary
5331 */
5332
5333 while (io_req_size && retval == 0) {
5334 u_int32_t io_start;
5335
5336 if (cluster_is_throttled(vp)) {
5337 uint32_t max_throttle_size = calculate_max_throttle_size(vp);
5338
5339 /*
5340 * we're in the throttle window, at the very least
5341 * we want to limit the size of the I/O we're about
5342 * to issue
5343 */
5344 max_rd_size = max_throttle_size;
5345 max_rd_ahead = max_throttle_size - 1;
5346 max_vector_size = max_throttle_size;
5347 } else {
5348 max_rd_size = max_upl_size;
5349 max_rd_ahead = max_rd_size * IO_SCALE(vp, 2);
5350 max_vector_size = MAX_VECTOR_UPL_SIZE;
5351 }
5352 io_start = io_size = io_req_size;
5353
5354 /*
5355 * First look for pages already in the cache
5356 * and move them to user space. But only do this
5357 * check if we are not retrieving encrypted data directly
5358 * from the filesystem; those blocks should never
5359 * be in the UBC.
5360 *
5361 * cluster_copy_ubc_data returns the resid
5362 * in io_size
5363 */
5364 if ((flags & IO_ENCRYPTED) == 0) {
5365 retval = cluster_copy_ubc_data_internal(vp, uio, (int *)&io_size, 0, 0);
5366 }
5367 /*
5368 * calculate the number of bytes actually copied
5369 * starting size - residual
5370 */
5371 xsize = io_start - io_size;
5372
5373 io_req_size -= xsize;
5374
5375 if (useVectorUPL && (xsize || (iov_base & PAGE_MASK))) {
5376 /*
5377 * We found something in the cache or we have an iov_base that's not
5378 * page-aligned.
5379 *
5380 * Issue all I/O's that have been collected within this Vectored UPL.
5381 */
5382 if (vector_upl_index) {
5383 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);
5384 reset_vector_run_state();
5385 }
5386
5387 if (xsize) {
5388 useVectorUPL = 0;
5389 }
5390
5391 /*
5392 * After this point, if we are using the Vector UPL path and the base is
5393 * not page-aligned then the UPL with that base will be the first in the vector UPL.
5394 */
5395 }
5396
5397 /*
5398 * check to see if we are finished with this request.
5399 *
5400 * If we satisfied this IO already, then io_req_size will be 0.
5401 * Otherwise, see if the IO was mis-aligned and needs to go through
5402 * the UBC to deal with the 'tail'.
5403 *
5404 */
5405 if (io_req_size == 0 || (misaligned)) {
5406 /*
5407 * see if there's another uio vector to
5408 * process that's of type IO_DIRECT
5409 *
5410 * break out of while loop to get there
5411 */
5412 break;
5413 }
5414 /*
5415 * assume the request ends on a device block boundary
5416 */
5417 io_min = devblocksize;
5418
5419 /*
5420 * we can handle I/O's in multiples of the device block size
5421 * however, if io_size isn't a multiple of devblocksize we
5422 * want to clip it back to the nearest page boundary since
5423 * we are going to have to go through cluster_read_copy to
5424 * deal with the 'overhang'... by clipping it to a PAGE_SIZE
5425 * multiple, we avoid asking the drive for the same physical
5426 * blocks twice.. once for the partial page at the end of the
5427 * request and a 2nd time for the page we read into the cache
5428 * (which overlaps the end of the direct read) in order to
5429 * get at the overhang bytes
5430 */
5431 if (io_size & (devblocksize - 1)) {
5432 assert(!(flags & IO_ENCRYPTED));
5433 /*
5434 * Clip the request to the previous page size boundary
5435 * since request does NOT end on a device block boundary
5436 */
5437 io_size &= ~PAGE_MASK;
5438 io_min = PAGE_SIZE;
5439 }
5440 if (retval || io_size < io_min) {
5441 /*
5442 * either an error or we only have the tail left to
5443 * complete via the copy path...
5444 * we may have already spun some portion of this request
5445 * off as async requests... we need to wait for the I/O
5446 * to complete before returning
5447 */
5448 goto wait_for_dreads;
5449 }
5450
5451 /*
5452 * Don't re-check the UBC data if we are looking for uncached IO
5453 * or asking for encrypted blocks.
5454 */
5455 if ((flags & IO_ENCRYPTED) == 0) {
5456 if ((xsize = io_size) > max_rd_size) {
5457 xsize = max_rd_size;
5458 }
5459
5460 io_size = 0;
5461
5462 if (!lock) {
5463 /*
5464 * We hold a lock here between the time we check the
5465 * cache and the time we issue I/O. This saves us
5466 * from having to lock the pages in the cache. Not
5467 * all clients will care about this lock but some
5468 * clients may want to guarantee stability between
5469 * here and when the I/O is issued in which case they
5470 * will take the lock exclusively.
5471 */
5472 lock = cluster_lock_direct_read(vp, LCK_RW_TYPE_SHARED);
5473 }
5474
5475 ubc_range_op(vp, uio->uio_offset, uio->uio_offset + xsize, UPL_ROP_ABSENT, (int *)&io_size);
5476
5477 if (io_size == 0) {
5478 /*
5479 * a page must have just come into the cache
5480 * since the first page in this range is no
5481 * longer absent, go back and re-evaluate
5482 */
5483 continue;
5484 }
5485 }
5486 if ((flags & IO_RETURN_ON_THROTTLE)) {
5487 if (cluster_is_throttled(vp) == THROTTLE_NOW) {
5488 if (!cluster_io_present_in_BC(vp, uio->uio_offset)) {
5489 /*
5490 * we're in the throttle window and at least 1 I/O
5491 * has already been issued by a throttleable thread
5492 * in this window, so return with EAGAIN to indicate
5493 * to the FS issuing the cluster_read call that it
5494 * should now throttle after dropping any locks
5495 */
5496 throttle_info_update_by_mount(vp->v_mount);
5497
5498 io_throttled = TRUE;
5499 goto wait_for_dreads;
5500 }
5501 }
5502 }
5503 if (io_size > max_rd_size) {
5504 io_size = max_rd_size;
5505 }
5506
5507 iov_base = uio_curriovbase(uio);
5508
5509 upl_offset = (vm_offset_t)((u_int32_t)iov_base & PAGE_MASK);
5510 upl_needed_size = (upl_offset + io_size + (PAGE_SIZE - 1)) & ~PAGE_MASK;
5511
5512 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 72)) | DBG_FUNC_START,
5513 (int)upl_offset, upl_needed_size, (int)iov_base, io_size, 0);
5514
5515 if (upl_offset == 0 && ((io_size & PAGE_MASK) == 0)) {
5516 no_zero_fill = 1;
5517 } else {
5518 no_zero_fill = 0;
5519 }
5520
5521 vm_map_t map = UIO_SEG_IS_USER_SPACE(uio->uio_segflg) ? current_map() : kernel_map;
5522 for (force_data_sync = 0; force_data_sync < 3; force_data_sync++) {
5523 pages_in_pl = 0;
5524 upl_size = (upl_size_t)upl_needed_size;
5525 upl_flags = UPL_FILE_IO | UPL_NO_SYNC | UPL_SET_INTERNAL | UPL_SET_LITE | UPL_SET_IO_WIRE;
5526 if (no_zero_fill) {
5527 upl_flags |= UPL_NOZEROFILL;
5528 }
5529 if (force_data_sync) {
5530 upl_flags |= UPL_FORCE_DATA_SYNC;
5531 }
5532
5533 kret = vm_map_create_upl(map,
5534 (vm_map_offset_t)(iov_base & ~((user_addr_t)PAGE_MASK)),
5535 &upl_size, &upl, NULL, &pages_in_pl, &upl_flags, VM_KERN_MEMORY_FILE);
5536
5537 if (kret != KERN_SUCCESS) {
5538 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 72)) | DBG_FUNC_END,
5539 (int)upl_offset, upl_size, io_size, kret, 0);
5540 /*
5541 * failed to get pagelist
5542 *
5543 * we may have already spun some portion of this request
5544 * off as async requests... we need to wait for the I/O
5545 * to complete before returning
5546 */
5547 goto wait_for_dreads;
5548 }
5549 pages_in_pl = upl_size / PAGE_SIZE;
5550 pl = UPL_GET_INTERNAL_PAGE_LIST(upl);
5551
5552 for (i = 0; i < pages_in_pl; i++) {
5553 if (!upl_page_present(pl, i)) {
5554 break;
5555 }
5556 }
5557 if (i == pages_in_pl) {
5558 break;
5559 }
5560
5561 ubc_upl_abort(upl, 0);
5562 }
5563 if (force_data_sync >= 3) {
5564 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 72)) | DBG_FUNC_END,
5565 (int)upl_offset, upl_size, io_size, kret, 0);
5566
5567 goto wait_for_dreads;
5568 }
5569 /*
5570 * Consider the possibility that upl_size wasn't satisfied.
5571 */
5572 if (upl_size < upl_needed_size) {
5573 if (upl_size && upl_offset == 0) {
5574 io_size = upl_size;
5575 } else {
5576 io_size = 0;
5577 }
5578 }
5579 if (io_size == 0) {
5580 ubc_upl_abort(upl, 0);
5581 goto wait_for_dreads;
5582 }
5583 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 72)) | DBG_FUNC_END,
5584 (int)upl_offset, upl_size, io_size, kret, 0);
5585
5586 if (useVectorUPL) {
5587 vm_offset_t end_off = ((iov_base + io_size) & PAGE_MASK);
5588 if (end_off) {
5589 issueVectorUPL = 1;
5590 }
5591 /*
5592 * After this point, if we are using a vector UPL, then
5593 * either all the UPL elements end on a page boundary OR
5594 * this UPL is the last element because it does not end
5595 * on a page boundary.
5596 */
5597 }
5598
5599 /*
5600 * request asynchronously so that we can overlap
5601 * the preparation of the next I/O
5602 * if there are already too many outstanding reads
5603 * wait until some have completed before issuing the next read
5604 */
5605 cluster_iostate_wait(&iostate, max_rd_ahead, "cluster_read_direct");
5606
5607 if (iostate.io_error) {
5608 /*
5609 * one of the earlier reads we issued ran into a hard error
5610 * don't issue any more reads, cleanup the UPL
5611 * that was just created but not used, then
5612 * go wait for any other reads to complete before
5613 * returning the error to the caller
5614 */
5615 ubc_upl_abort(upl, 0);
5616
5617 goto wait_for_dreads;
5618 }
5619 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 73)) | DBG_FUNC_START,
5620 upl, (int)upl_offset, (int)uio->uio_offset, io_size, 0);
5621
5622 if (!useVectorUPL) {
5623 if (no_zero_fill) {
5624 io_flag &= ~CL_PRESERVE;
5625 } else {
5626 io_flag |= CL_PRESERVE;
5627 }
5628
5629 retval = cluster_io(vp, upl, upl_offset, uio->uio_offset, io_size, io_flag, (buf_t)NULL, &iostate, callback, callback_arg);
5630 } else {
5631 if (!vector_upl_index) {
5632 vector_upl = vector_upl_create(upl_offset, uio->uio_iovcnt);
5633 v_upl_uio_offset = uio->uio_offset;
5634 vector_upl_offset = upl_offset;
5635 }
5636
5637 vector_upl_set_subupl(vector_upl, upl, upl_size);
5638 vector_upl_set_iostate(vector_upl, upl, vector_upl_size, upl_size);
5639 vector_upl_index++;
5640 vector_upl_size += upl_size;
5641 vector_upl_iosize += io_size;
5642
5643 if (issueVectorUPL || vector_upl_index == vector_upl_max_upls(vector_upl) || vector_upl_size >= max_vector_size) {
5644 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);
5645 reset_vector_run_state();
5646 }
5647 }
5648
5649 if (lock) {
5650 // We don't need to wait for the I/O to complete
5651 cluster_unlock_direct_read(lock);
5652 lock = NULL;
5653 }
5654
5655 /*
5656 * update the uio structure
5657 */
5658 if ((flags & IO_ENCRYPTED) && (max_io_size < io_size)) {
5659 uio_update(uio, (user_size_t)max_io_size);
5660 } else {
5661 uio_update(uio, (user_size_t)io_size);
5662 }
5663
5664 io_req_size -= io_size;
5665
5666 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 73)) | DBG_FUNC_END,
5667 upl, (int)uio->uio_offset, io_req_size, retval, 0);
5668 } /* end while */
5669
5670 if (retval == 0 && iostate.io_error == 0 && io_req_size == 0 && uio->uio_offset < filesize) {
5671 retval = cluster_io_type(uio, read_type, read_length, 0);
5672
5673 if (retval == 0 && *read_type == IO_DIRECT) {
5674 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 70)) | DBG_FUNC_NONE,
5675 (int)uio->uio_offset, (int)filesize, *read_type, *read_length, 0);
5676
5677 goto next_dread;
5678 }
5679 }
5680
5681 wait_for_dreads:
5682
5683 if (retval == 0 && iostate.io_error == 0 && useVectorUPL && vector_upl_index) {
5684 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);
5685 reset_vector_run_state();
5686 }
5687
5688 // We don't need to wait for the I/O to complete
5689 if (lock) {
5690 cluster_unlock_direct_read(lock);
5691 }
5692
5693 /*
5694 * make sure all async reads that are part of this stream
5695 * have completed before we return
5696 */
5697 cluster_iostate_wait(&iostate, 0, "cluster_read_direct");
5698
5699 if (iostate.io_error) {
5700 retval = iostate.io_error;
5701 }
5702
5703 lck_mtx_destroy(&iostate.io_mtxp, &cl_mtx_grp);
5704
5705 if (io_throttled == TRUE && retval == 0) {
5706 retval = EAGAIN;
5707 }
5708
5709 vm_map_offset_t current_page_size, current_page_mask;
5710 current_page_size = vm_map_page_size(current_map());
5711 current_page_mask = vm_map_page_mask(current_map());
5712 if (uio_acct) {
5713 assert(uio_acct->uio_segflg != UIO_SYSSPACE);
5714 off_t bytes_to_prefault = 0, bytes_prefaulted = 0;
5715 user_addr_t curr_iov_base = 0;
5716 user_addr_t curr_iov_end = 0;
5717 user_size_t curr_iov_len = 0;
5718
5719 bytes_to_prefault = uio_offset(uio) - uio_offset(uio_acct);
5720
5721 for (; bytes_prefaulted < bytes_to_prefault;) {
5722 curr_iov_base = uio_curriovbase(uio_acct);
5723 curr_iov_len = MIN(uio_curriovlen(uio_acct), bytes_to_prefault - bytes_prefaulted);
5724 curr_iov_end = curr_iov_base + curr_iov_len;
5725
5726 for (; curr_iov_base < curr_iov_end;) {
5727 /*
5728 * This is specifically done for pmap accounting purposes.
5729 * vm_pre_fault() will call vm_fault() to enter the page into
5730 * the pmap if there isn't _a_ physical page for that VA already.
5731 */
5732 vm_pre_fault(vm_map_trunc_page(curr_iov_base, current_page_mask), VM_PROT_READ);
5733 curr_iov_base += current_page_size;
5734 bytes_prefaulted += current_page_size;
5735 }
5736 /*
5737 * Use update instead of advance so we can see how many iovs we processed.
5738 */
5739 uio_update(uio_acct, curr_iov_len);
5740 }
5741 uio_free(uio_acct);
5742 uio_acct = NULL;
5743 }
5744
5745 if (io_req_size && retval == 0) {
5746 /*
5747 * we couldn't handle the tail of this request in DIRECT mode
5748 * so fire it through the copy path
5749 */
5750 if (flags & IO_ENCRYPTED) {
5751 /*
5752 * We cannot fall back to the copy path for encrypted I/O. If this
5753 * happens, there is something wrong with the user buffer passed
5754 * down.
5755 */
5756 retval = EFAULT;
5757 } else {
5758 retval = cluster_read_copy(vp, uio, io_req_size, filesize, flags, callback, callback_arg);
5759 }
5760
5761 *read_type = IO_UNKNOWN;
5762 }
5763 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 70)) | DBG_FUNC_END,
5764 (int)uio->uio_offset, (int)uio_resid(uio), io_req_size, retval, 0);
5765
5766 return retval;
5767 }
5768
5769
5770 static int
cluster_read_contig(vnode_t vp,struct uio * uio,off_t filesize,int * read_type,u_int32_t * read_length,int (* callback)(buf_t,void *),void * callback_arg,int flags)5771 cluster_read_contig(vnode_t vp, struct uio *uio, off_t filesize, int *read_type, u_int32_t *read_length,
5772 int (*callback)(buf_t, void *), void *callback_arg, int flags)
5773 {
5774 upl_page_info_t *pl;
5775 upl_t upl[MAX_VECTS];
5776 vm_offset_t upl_offset;
5777 addr64_t dst_paddr = 0;
5778 user_addr_t iov_base;
5779 off_t max_size;
5780 upl_size_t upl_size;
5781 vm_size_t upl_needed_size;
5782 mach_msg_type_number_t pages_in_pl;
5783 upl_control_flags_t upl_flags;
5784 kern_return_t kret;
5785 struct clios iostate;
5786 int error = 0;
5787 int cur_upl = 0;
5788 int num_upl = 0;
5789 int n;
5790 u_int32_t xsize;
5791 u_int32_t io_size;
5792 u_int32_t devblocksize;
5793 u_int32_t mem_alignment_mask;
5794 u_int32_t tail_size = 0;
5795 int bflag;
5796
5797 if (flags & IO_PASSIVE) {
5798 bflag = CL_PASSIVE;
5799 } else {
5800 bflag = 0;
5801 }
5802
5803 if (flags & IO_NOCACHE) {
5804 bflag |= CL_NOCACHE;
5805 }
5806
5807 /*
5808 * When we enter this routine, we know
5809 * -- the read_length will not exceed the current iov_len
5810 * -- the target address is physically contiguous for read_length
5811 */
5812 cluster_syncup(vp, filesize, callback, callback_arg, PUSH_SYNC);
5813
5814 devblocksize = (u_int32_t)vp->v_mount->mnt_devblocksize;
5815 mem_alignment_mask = (u_int32_t)vp->v_mount->mnt_alignmentmask;
5816
5817 iostate.io_completed = 0;
5818 iostate.io_issued = 0;
5819 iostate.io_error = 0;
5820 iostate.io_wanted = 0;
5821
5822 lck_mtx_init(&iostate.io_mtxp, &cl_mtx_grp, LCK_ATTR_NULL);
5823
5824 next_cread:
5825 io_size = *read_length;
5826
5827 max_size = filesize - uio->uio_offset;
5828
5829 if (io_size > max_size) {
5830 io_size = (u_int32_t)max_size;
5831 }
5832
5833 iov_base = uio_curriovbase(uio);
5834
5835 upl_offset = (vm_offset_t)((u_int32_t)iov_base & PAGE_MASK);
5836 upl_needed_size = upl_offset + io_size;
5837
5838 pages_in_pl = 0;
5839 upl_size = (upl_size_t)upl_needed_size;
5840 upl_flags = UPL_FILE_IO | UPL_NO_SYNC | UPL_CLEAN_IN_PLACE | UPL_SET_INTERNAL | UPL_SET_LITE | UPL_SET_IO_WIRE;
5841
5842
5843 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 92)) | DBG_FUNC_START,
5844 (int)upl_offset, (int)upl_size, (int)iov_base, io_size, 0);
5845
5846 vm_map_t map = UIO_SEG_IS_USER_SPACE(uio->uio_segflg) ? current_map() : kernel_map;
5847 kret = vm_map_get_upl(map,
5848 vm_map_trunc_page(iov_base, vm_map_page_mask(map)),
5849 &upl_size, &upl[cur_upl], NULL, &pages_in_pl, &upl_flags, VM_KERN_MEMORY_FILE, 0);
5850
5851 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 92)) | DBG_FUNC_END,
5852 (int)upl_offset, upl_size, io_size, kret, 0);
5853
5854 if (kret != KERN_SUCCESS) {
5855 /*
5856 * failed to get pagelist
5857 */
5858 error = EINVAL;
5859 goto wait_for_creads;
5860 }
5861 num_upl++;
5862
5863 if (upl_size < upl_needed_size) {
5864 /*
5865 * The upl_size wasn't satisfied.
5866 */
5867 error = EINVAL;
5868 goto wait_for_creads;
5869 }
5870 pl = ubc_upl_pageinfo(upl[cur_upl]);
5871
5872 dst_paddr = ((addr64_t)upl_phys_page(pl, 0) << PAGE_SHIFT) + (addr64_t)upl_offset;
5873
5874 while (((uio->uio_offset & (devblocksize - 1)) || io_size < devblocksize) && io_size) {
5875 u_int32_t head_size;
5876
5877 head_size = devblocksize - (u_int32_t)(uio->uio_offset & (devblocksize - 1));
5878
5879 if (head_size > io_size) {
5880 head_size = io_size;
5881 }
5882
5883 error = cluster_align_phys_io(vp, uio, dst_paddr, head_size, CL_READ, callback, callback_arg);
5884
5885 if (error) {
5886 goto wait_for_creads;
5887 }
5888
5889 upl_offset += head_size;
5890 dst_paddr += head_size;
5891 io_size -= head_size;
5892
5893 iov_base += head_size;
5894 }
5895 if ((u_int32_t)iov_base & mem_alignment_mask) {
5896 /*
5897 * request doesn't set up on a memory boundary
5898 * the underlying DMA engine can handle...
5899 * return an error instead of going through
5900 * the slow copy path since the intent of this
5901 * path is direct I/O to device memory
5902 */
5903 error = EINVAL;
5904 goto wait_for_creads;
5905 }
5906
5907 tail_size = io_size & (devblocksize - 1);
5908
5909 io_size -= tail_size;
5910
5911 while (io_size && error == 0) {
5912 if (io_size > MAX_IO_CONTIG_SIZE) {
5913 xsize = MAX_IO_CONTIG_SIZE;
5914 } else {
5915 xsize = io_size;
5916 }
5917 /*
5918 * request asynchronously so that we can overlap
5919 * the preparation of the next I/O... we'll do
5920 * the commit after all the I/O has completed
5921 * since its all issued against the same UPL
5922 * if there are already too many outstanding reads
5923 * wait until some have completed before issuing the next
5924 */
5925 cluster_iostate_wait(&iostate, MAX_IO_CONTIG_SIZE * IO_SCALE(vp, 2), "cluster_read_contig");
5926
5927 if (iostate.io_error) {
5928 /*
5929 * one of the earlier reads we issued ran into a hard error
5930 * don't issue any more reads...
5931 * go wait for any other reads to complete before
5932 * returning the error to the caller
5933 */
5934 goto wait_for_creads;
5935 }
5936 error = cluster_io(vp, upl[cur_upl], upl_offset, uio->uio_offset, xsize,
5937 CL_READ | CL_NOZERO | CL_DEV_MEMORY | CL_ASYNC | bflag,
5938 (buf_t)NULL, &iostate, callback, callback_arg);
5939 /*
5940 * The cluster_io read was issued successfully,
5941 * update the uio structure
5942 */
5943 if (error == 0) {
5944 uio_update(uio, (user_size_t)xsize);
5945
5946 dst_paddr += xsize;
5947 upl_offset += xsize;
5948 io_size -= xsize;
5949 }
5950 }
5951 if (error == 0 && iostate.io_error == 0 && tail_size == 0 && num_upl < MAX_VECTS && uio->uio_offset < filesize) {
5952 error = cluster_io_type(uio, read_type, read_length, 0);
5953
5954 if (error == 0 && *read_type == IO_CONTIG) {
5955 cur_upl++;
5956 goto next_cread;
5957 }
5958 } else {
5959 *read_type = IO_UNKNOWN;
5960 }
5961
5962 wait_for_creads:
5963 /*
5964 * make sure all async reads that are part of this stream
5965 * have completed before we proceed
5966 */
5967 cluster_iostate_wait(&iostate, 0, "cluster_read_contig");
5968
5969 if (iostate.io_error) {
5970 error = iostate.io_error;
5971 }
5972
5973 lck_mtx_destroy(&iostate.io_mtxp, &cl_mtx_grp);
5974
5975 if (error == 0 && tail_size) {
5976 error = cluster_align_phys_io(vp, uio, dst_paddr, tail_size, CL_READ, callback, callback_arg);
5977 }
5978
5979 for (n = 0; n < num_upl; n++) {
5980 /*
5981 * just release our hold on each physically contiguous
5982 * region without changing any state
5983 */
5984 ubc_upl_abort(upl[n], 0);
5985 }
5986
5987 return error;
5988 }
5989
5990
5991 static int
cluster_io_type(struct uio * uio,int * io_type,u_int32_t * io_length,u_int32_t min_length)5992 cluster_io_type(struct uio *uio, int *io_type, u_int32_t *io_length, u_int32_t min_length)
5993 {
5994 user_size_t iov_len;
5995 user_addr_t iov_base = 0;
5996 upl_t upl;
5997 upl_size_t upl_size;
5998 upl_control_flags_t upl_flags;
5999 int retval = 0;
6000
6001 /*
6002 * skip over any emtpy vectors
6003 */
6004 uio_update(uio, (user_size_t)0);
6005
6006 iov_len = MIN(uio_curriovlen(uio), uio_resid(uio));
6007
6008 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 94)) | DBG_FUNC_START, uio, (int)iov_len, 0, 0, 0);
6009
6010 if (iov_len) {
6011 iov_base = uio_curriovbase(uio);
6012 /*
6013 * make sure the size of the vector isn't too big...
6014 * internally, we want to handle all of the I/O in
6015 * chunk sizes that fit in a 32 bit int
6016 */
6017 if (iov_len > (user_size_t)MAX_IO_REQUEST_SIZE) {
6018 upl_size = MAX_IO_REQUEST_SIZE;
6019 } else {
6020 upl_size = (u_int32_t)iov_len;
6021 }
6022
6023 upl_flags = UPL_QUERY_OBJECT_TYPE;
6024
6025 vm_map_t map = UIO_SEG_IS_USER_SPACE(uio->uio_segflg) ? current_map() : kernel_map;
6026 if ((vm_map_get_upl(map,
6027 vm_map_trunc_page(iov_base, vm_map_page_mask(map)),
6028 &upl_size, &upl, NULL, NULL, &upl_flags, VM_KERN_MEMORY_FILE, 0)) != KERN_SUCCESS) {
6029 /*
6030 * the user app must have passed in an invalid address
6031 */
6032 retval = EFAULT;
6033 }
6034 if (upl_size == 0) {
6035 retval = EFAULT;
6036 }
6037
6038 *io_length = upl_size;
6039
6040 if (upl_flags & UPL_PHYS_CONTIG) {
6041 *io_type = IO_CONTIG;
6042 } else if (iov_len >= min_length) {
6043 *io_type = IO_DIRECT;
6044 } else {
6045 *io_type = IO_COPY;
6046 }
6047 } else {
6048 /*
6049 * nothing left to do for this uio
6050 */
6051 *io_length = 0;
6052 *io_type = IO_UNKNOWN;
6053 }
6054 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 94)) | DBG_FUNC_END, iov_base, *io_type, *io_length, retval, 0);
6055
6056 if (*io_type == IO_DIRECT &&
6057 vm_map_page_shift(current_map()) < PAGE_SHIFT) {
6058 /* no direct I/O for sub-page-size address spaces */
6059 DEBUG4K_VFS("io_type IO_DIRECT -> IO_COPY\n");
6060 *io_type = IO_COPY;
6061 }
6062
6063 return retval;
6064 }
6065
6066
6067 /*
6068 * generate advisory I/O's in the largest chunks possible
6069 * the completed pages will be released into the VM cache
6070 */
6071 int
advisory_read(vnode_t vp,off_t filesize,off_t f_offset,int resid)6072 advisory_read(vnode_t vp, off_t filesize, off_t f_offset, int resid)
6073 {
6074 return advisory_read_ext(vp, filesize, f_offset, resid, NULL, NULL, CL_PASSIVE);
6075 }
6076
6077 int
advisory_read_ext(vnode_t vp,off_t filesize,off_t f_offset,int resid,int (* callback)(buf_t,void *),void * callback_arg,int bflag)6078 advisory_read_ext(vnode_t vp, off_t filesize, off_t f_offset, int resid, int (*callback)(buf_t, void *), void *callback_arg, int bflag)
6079 {
6080 upl_page_info_t *pl;
6081 upl_t upl = NULL;
6082 vm_offset_t upl_offset;
6083 int upl_size;
6084 off_t upl_f_offset;
6085 int start_offset;
6086 int start_pg;
6087 int last_pg;
6088 int pages_in_upl;
6089 off_t max_size;
6090 int io_size;
6091 kern_return_t kret;
6092 int retval = 0;
6093 int issued_io;
6094 int skip_range;
6095 uint32_t max_io_size;
6096
6097
6098 if (!UBCINFOEXISTS(vp)) {
6099 return EINVAL;
6100 }
6101
6102 if (f_offset < 0 || resid < 0) {
6103 return EINVAL;
6104 }
6105
6106 max_io_size = cluster_max_io_size(vp->v_mount, CL_READ);
6107
6108 if (disk_conditioner_mount_is_ssd(vp->v_mount)) {
6109 if (max_io_size > speculative_prefetch_max_iosize) {
6110 max_io_size = speculative_prefetch_max_iosize;
6111 }
6112 }
6113
6114 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 60)) | DBG_FUNC_START,
6115 (int)f_offset, resid, (int)filesize, 0, 0);
6116
6117 while (resid && f_offset < filesize && retval == 0) {
6118 /*
6119 * compute the size of the upl needed to encompass
6120 * the requested read... limit each call to cluster_io
6121 * to the maximum UPL size... cluster_io will clip if
6122 * this exceeds the maximum io_size for the device,
6123 * make sure to account for
6124 * a starting offset that's not page aligned
6125 */
6126 start_offset = (int)(f_offset & PAGE_MASK_64);
6127 upl_f_offset = f_offset - (off_t)start_offset;
6128 max_size = filesize - f_offset;
6129
6130 if (resid < max_size) {
6131 io_size = resid;
6132 } else {
6133 io_size = (int)max_size;
6134 }
6135
6136 upl_size = (start_offset + io_size + (PAGE_SIZE - 1)) & ~PAGE_MASK;
6137 if ((uint32_t)upl_size > max_io_size) {
6138 upl_size = max_io_size;
6139 }
6140
6141 skip_range = 0;
6142 /*
6143 * return the number of contiguously present pages in the cache
6144 * starting at upl_f_offset within the file
6145 */
6146 ubc_range_op(vp, upl_f_offset, upl_f_offset + upl_size, UPL_ROP_PRESENT, &skip_range);
6147
6148 if (skip_range) {
6149 /*
6150 * skip over pages already present in the cache
6151 */
6152 io_size = skip_range - start_offset;
6153
6154 f_offset += io_size;
6155 resid -= io_size;
6156
6157 if (skip_range == upl_size) {
6158 continue;
6159 }
6160 /*
6161 * have to issue some real I/O
6162 * at this point, we know it's starting on a page boundary
6163 * because we've skipped over at least the first page in the request
6164 */
6165 start_offset = 0;
6166 upl_f_offset += skip_range;
6167 upl_size -= skip_range;
6168 }
6169 pages_in_upl = upl_size / PAGE_SIZE;
6170
6171 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 61)) | DBG_FUNC_START,
6172 upl, (int)upl_f_offset, upl_size, start_offset, 0);
6173
6174 kret = ubc_create_upl_kernel(vp,
6175 upl_f_offset,
6176 upl_size,
6177 &upl,
6178 &pl,
6179 UPL_RET_ONLY_ABSENT | UPL_SET_LITE,
6180 VM_KERN_MEMORY_FILE);
6181 if (kret != KERN_SUCCESS) {
6182 return retval;
6183 }
6184 issued_io = 0;
6185
6186 /*
6187 * before we start marching forward, we must make sure we end on
6188 * a present page, otherwise we will be working with a freed
6189 * upl
6190 */
6191 for (last_pg = pages_in_upl - 1; last_pg >= 0; last_pg--) {
6192 if (upl_page_present(pl, last_pg)) {
6193 break;
6194 }
6195 }
6196 pages_in_upl = last_pg + 1;
6197
6198
6199 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 61)) | DBG_FUNC_END,
6200 upl, (int)upl_f_offset, upl_size, start_offset, 0);
6201
6202
6203 for (last_pg = 0; last_pg < pages_in_upl;) {
6204 /*
6205 * scan from the beginning of the upl looking for the first
6206 * page that is present.... this will become the first page in
6207 * the request we're going to make to 'cluster_io'... if all
6208 * of the pages are absent, we won't call through to 'cluster_io'
6209 */
6210 for (start_pg = last_pg; start_pg < pages_in_upl; start_pg++) {
6211 if (upl_page_present(pl, start_pg)) {
6212 break;
6213 }
6214 }
6215
6216 /*
6217 * scan from the starting present page looking for an absent
6218 * page before the end of the upl is reached, if we
6219 * find one, then it will terminate the range of pages being
6220 * presented to 'cluster_io'
6221 */
6222 for (last_pg = start_pg; last_pg < pages_in_upl; last_pg++) {
6223 if (!upl_page_present(pl, last_pg)) {
6224 break;
6225 }
6226 }
6227
6228 if (last_pg > start_pg) {
6229 /*
6230 * we found a range of pages that must be filled
6231 * if the last page in this range is the last page of the file
6232 * we may have to clip the size of it to keep from reading past
6233 * the end of the last physical block associated with the file
6234 */
6235 upl_offset = start_pg * PAGE_SIZE;
6236 io_size = (last_pg - start_pg) * PAGE_SIZE;
6237
6238 if ((off_t)(upl_f_offset + upl_offset + io_size) > filesize) {
6239 io_size = (int)(filesize - (upl_f_offset + upl_offset));
6240 }
6241
6242 /*
6243 * issue an asynchronous read to cluster_io
6244 */
6245 retval = cluster_io(vp, upl, upl_offset, upl_f_offset + upl_offset, io_size,
6246 CL_ASYNC | CL_READ | CL_COMMIT | CL_AGE | bflag, (buf_t)NULL, (struct clios *)NULL, callback, callback_arg);
6247
6248 issued_io = 1;
6249 }
6250 }
6251 if (issued_io == 0) {
6252 ubc_upl_abort(upl, 0);
6253 }
6254
6255 io_size = upl_size - start_offset;
6256
6257 if (io_size > resid) {
6258 io_size = resid;
6259 }
6260 f_offset += io_size;
6261 resid -= io_size;
6262 }
6263
6264 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 60)) | DBG_FUNC_END,
6265 (int)f_offset, resid, retval, 0, 0);
6266
6267 return retval;
6268 }
6269
6270
6271 int
cluster_push(vnode_t vp,int flags)6272 cluster_push(vnode_t vp, int flags)
6273 {
6274 return cluster_push_ext(vp, flags, NULL, NULL);
6275 }
6276
6277
6278 int
cluster_push_ext(vnode_t vp,int flags,int (* callback)(buf_t,void *),void * callback_arg)6279 cluster_push_ext(vnode_t vp, int flags, int (*callback)(buf_t, void *), void *callback_arg)
6280 {
6281 return cluster_push_err(vp, flags, callback, callback_arg, NULL);
6282 }
6283
6284 /* write errors via err, but return the number of clusters written */
6285 extern uint32_t system_inshutdown;
6286 uint32_t cl_sparse_push_error = 0;
6287 int
cluster_push_err(vnode_t vp,int flags,int (* callback)(buf_t,void *),void * callback_arg,int * err)6288 cluster_push_err(vnode_t vp, int flags, int (*callback)(buf_t, void *), void *callback_arg, int *err)
6289 {
6290 int retval;
6291 int my_sparse_wait = 0;
6292 struct cl_writebehind *wbp;
6293 int local_err = 0;
6294
6295 if (err) {
6296 *err = 0;
6297 }
6298
6299 if (!UBCINFOEXISTS(vp)) {
6300 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 53)) | DBG_FUNC_NONE, kdebug_vnode(vp), flags, 0, -1, 0);
6301 return 0;
6302 }
6303 /* return if deferred write is set */
6304 if (((unsigned int)vfs_flags(vp->v_mount) & MNT_DEFWRITE) && (flags & IO_DEFWRITE)) {
6305 return 0;
6306 }
6307 if ((wbp = cluster_get_wbp(vp, CLW_RETURNLOCKED)) == NULL) {
6308 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 53)) | DBG_FUNC_NONE, kdebug_vnode(vp), flags, 0, -2, 0);
6309 return 0;
6310 }
6311 if (!ISSET(flags, IO_SYNC) && wbp->cl_number == 0 && wbp->cl_scmap == NULL) {
6312 lck_mtx_unlock(&wbp->cl_lockw);
6313
6314 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 53)) | DBG_FUNC_NONE, kdebug_vnode(vp), flags, 0, -3, 0);
6315 return 0;
6316 }
6317 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 53)) | DBG_FUNC_START,
6318 wbp->cl_scmap, wbp->cl_number, flags, 0, 0);
6319
6320 /*
6321 * if we have an fsync in progress, we don't want to allow any additional
6322 * sync/fsync/close(s) to occur until it finishes.
6323 * note that its possible for writes to continue to occur to this file
6324 * while we're waiting and also once the fsync starts to clean if we're
6325 * in the sparse map case
6326 */
6327 while (wbp->cl_sparse_wait) {
6328 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 97)) | DBG_FUNC_START, kdebug_vnode(vp), 0, 0, 0, 0);
6329
6330 msleep((caddr_t)&wbp->cl_sparse_wait, &wbp->cl_lockw, PRIBIO + 1, "cluster_push_ext", NULL);
6331
6332 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 97)) | DBG_FUNC_END, kdebug_vnode(vp), 0, 0, 0, 0);
6333 }
6334 if (flags & IO_SYNC) {
6335 my_sparse_wait = 1;
6336 wbp->cl_sparse_wait = 1;
6337
6338 /*
6339 * this is an fsync (or equivalent)... we must wait for any existing async
6340 * cleaning operations to complete before we evaulate the current state
6341 * and finish cleaning... this insures that all writes issued before this
6342 * fsync actually get cleaned to the disk before this fsync returns
6343 */
6344 while (wbp->cl_sparse_pushes) {
6345 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 98)) | DBG_FUNC_START, kdebug_vnode(vp), 0, 0, 0, 0);
6346
6347 msleep((caddr_t)&wbp->cl_sparse_pushes, &wbp->cl_lockw, PRIBIO + 1, "cluster_push_ext", NULL);
6348
6349 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 98)) | DBG_FUNC_END, kdebug_vnode(vp), 0, 0, 0, 0);
6350 }
6351 }
6352 if (wbp->cl_scmap) {
6353 void *scmap;
6354
6355 if (wbp->cl_sparse_pushes < SPARSE_PUSH_LIMIT) {
6356 scmap = wbp->cl_scmap;
6357 wbp->cl_scmap = NULL;
6358
6359 wbp->cl_sparse_pushes++;
6360
6361 lck_mtx_unlock(&wbp->cl_lockw);
6362
6363 retval = sparse_cluster_push(wbp, &scmap, vp, ubc_getsize(vp), PUSH_ALL, flags, callback, callback_arg, FALSE);
6364
6365 lck_mtx_lock(&wbp->cl_lockw);
6366
6367 wbp->cl_sparse_pushes--;
6368
6369 if (retval) {
6370 if (wbp->cl_scmap != NULL) {
6371 /*
6372 * panic("cluster_push_err: Expected NULL cl_scmap\n");
6373 *
6374 * This can happen if we get an error from the underlying FS
6375 * e.g. ENOSPC, EPERM or EIO etc. We hope that these errors
6376 * are transient and the I/Os will succeed at a later point.
6377 *
6378 * The tricky part here is that a new sparse cluster has been
6379 * allocated and tracking a different set of dirty pages. So these
6380 * pages are not going to be pushed out with the next sparse_cluster_push.
6381 * An explicit msync or file close will, however, push the pages out.
6382 *
6383 * What if those calls still don't work? And so, during shutdown we keep
6384 * trying till we succeed...
6385 */
6386
6387 if (system_inshutdown) {
6388 if ((retval == ENOSPC) && (vp->v_mount->mnt_flag & (MNT_LOCAL | MNT_REMOVABLE)) == MNT_LOCAL) {
6389 os_atomic_inc(&cl_sparse_push_error, relaxed);
6390 }
6391 } else {
6392 vfs_drt_control(&scmap, 0); /* emit stats and free this memory. Dirty pages stay intact. */
6393 scmap = NULL;
6394 }
6395 } else {
6396 wbp->cl_scmap = scmap;
6397 }
6398 }
6399
6400 if (wbp->cl_sparse_wait && wbp->cl_sparse_pushes == 0) {
6401 wakeup((caddr_t)&wbp->cl_sparse_pushes);
6402 }
6403 } else {
6404 retval = sparse_cluster_push(wbp, &(wbp->cl_scmap), vp, ubc_getsize(vp), PUSH_ALL, flags, callback, callback_arg, FALSE);
6405 }
6406
6407 local_err = retval;
6408
6409 if (err) {
6410 *err = retval;
6411 }
6412 retval = 1;
6413 } else {
6414 retval = cluster_try_push(wbp, vp, ubc_getsize(vp), PUSH_ALL, flags, callback, callback_arg, &local_err, FALSE);
6415 if (err) {
6416 *err = local_err;
6417 }
6418 }
6419 lck_mtx_unlock(&wbp->cl_lockw);
6420
6421 if (flags & IO_SYNC) {
6422 (void)vnode_waitforwrites(vp, 0, 0, 0, "cluster_push");
6423 }
6424
6425 if (my_sparse_wait) {
6426 /*
6427 * I'm the owner of the serialization token
6428 * clear it and wakeup anyone that is waiting
6429 * for me to finish
6430 */
6431 lck_mtx_lock(&wbp->cl_lockw);
6432
6433 wbp->cl_sparse_wait = 0;
6434 wakeup((caddr_t)&wbp->cl_sparse_wait);
6435
6436 lck_mtx_unlock(&wbp->cl_lockw);
6437 }
6438 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 53)) | DBG_FUNC_END,
6439 wbp->cl_scmap, wbp->cl_number, retval, local_err, 0);
6440
6441 return retval;
6442 }
6443
6444
6445 __private_extern__ void
cluster_release(struct ubc_info * ubc)6446 cluster_release(struct ubc_info *ubc)
6447 {
6448 struct cl_writebehind *wbp;
6449 struct cl_readahead *rap;
6450
6451 if ((wbp = ubc->cl_wbehind)) {
6452 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 81)) | DBG_FUNC_START, ubc, wbp->cl_scmap, 0, 0, 0);
6453
6454 if (wbp->cl_scmap) {
6455 vfs_drt_control(&(wbp->cl_scmap), 0);
6456 }
6457 lck_mtx_destroy(&wbp->cl_lockw, &cl_mtx_grp);
6458 zfree(cl_wr_zone, wbp);
6459 ubc->cl_wbehind = NULL;
6460 } else {
6461 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 81)) | DBG_FUNC_START, ubc, 0, 0, 0, 0);
6462 }
6463
6464 if ((rap = ubc->cl_rahead)) {
6465 lck_mtx_destroy(&rap->cl_lockr, &cl_mtx_grp);
6466 zfree(cl_rd_zone, rap);
6467 ubc->cl_rahead = NULL;
6468 }
6469
6470 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 81)) | DBG_FUNC_END, ubc, rap, wbp, 0, 0);
6471 }
6472
6473
6474 static int
cluster_try_push(struct cl_writebehind * wbp,vnode_t vp,off_t EOF,int push_flag,int io_flags,int (* callback)(buf_t,void *),void * callback_arg,int * err,boolean_t vm_initiated)6475 cluster_try_push(struct cl_writebehind *wbp, vnode_t vp, off_t EOF, int push_flag, int io_flags, int (*callback)(buf_t, void *), void *callback_arg, int *err, boolean_t vm_initiated)
6476 {
6477 int cl_index;
6478 int cl_index1;
6479 int min_index;
6480 int cl_len;
6481 int cl_pushed = 0;
6482 struct cl_wextent l_clusters[MAX_CLUSTERS];
6483 u_int max_cluster_pgcount;
6484 int error = 0;
6485
6486 max_cluster_pgcount = MAX_CLUSTER_SIZE(vp) / PAGE_SIZE;
6487 /*
6488 * the write behind context exists and has
6489 * already been locked...
6490 */
6491 if (wbp->cl_number == 0) {
6492 /*
6493 * no clusters to push
6494 * return number of empty slots
6495 */
6496 return MAX_CLUSTERS;
6497 }
6498
6499 /*
6500 * make a local 'sorted' copy of the clusters
6501 * and clear wbp->cl_number so that new clusters can
6502 * be developed
6503 */
6504 for (cl_index = 0; cl_index < wbp->cl_number; cl_index++) {
6505 for (min_index = -1, cl_index1 = 0; cl_index1 < wbp->cl_number; cl_index1++) {
6506 if (wbp->cl_clusters[cl_index1].b_addr == wbp->cl_clusters[cl_index1].e_addr) {
6507 continue;
6508 }
6509 if (min_index == -1) {
6510 min_index = cl_index1;
6511 } else if (wbp->cl_clusters[cl_index1].b_addr < wbp->cl_clusters[min_index].b_addr) {
6512 min_index = cl_index1;
6513 }
6514 }
6515 if (min_index == -1) {
6516 break;
6517 }
6518
6519 l_clusters[cl_index].b_addr = wbp->cl_clusters[min_index].b_addr;
6520 l_clusters[cl_index].e_addr = wbp->cl_clusters[min_index].e_addr;
6521 l_clusters[cl_index].io_flags = wbp->cl_clusters[min_index].io_flags;
6522
6523 wbp->cl_clusters[min_index].b_addr = wbp->cl_clusters[min_index].e_addr;
6524 }
6525 wbp->cl_number = 0;
6526
6527 cl_len = cl_index;
6528
6529 /* skip switching to the sparse cluster mechanism if on diskimage */
6530 if (((push_flag & PUSH_DELAY) && cl_len == MAX_CLUSTERS) &&
6531 !(vp->v_mount->mnt_kern_flag & MNTK_VIRTUALDEV)) {
6532 int i;
6533
6534 /*
6535 * determine if we appear to be writing the file sequentially
6536 * if not, by returning without having pushed any clusters
6537 * we will cause this vnode to be pushed into the sparse cluster mechanism
6538 * used for managing more random I/O patterns
6539 *
6540 * we know that we've got all clusters currently in use and the next write doesn't fit into one of them...
6541 * that's why we're in try_push with PUSH_DELAY...
6542 *
6543 * check to make sure that all the clusters except the last one are 'full'... and that each cluster
6544 * is adjacent to the next (i.e. we're looking for sequential writes) they were sorted above
6545 * so we can just make a simple pass through, up to, but not including the last one...
6546 * note that e_addr is not inclusive, so it will be equal to the b_addr of the next cluster if they
6547 * are sequential
6548 *
6549 * we let the last one be partial as long as it was adjacent to the previous one...
6550 * we need to do this to deal with multi-threaded servers that might write an I/O or 2 out
6551 * of order... if this occurs at the tail of the last cluster, we don't want to fall into the sparse cluster world...
6552 */
6553 for (i = 0; i < MAX_CLUSTERS - 1; i++) {
6554 if ((l_clusters[i].e_addr - l_clusters[i].b_addr) != max_cluster_pgcount) {
6555 goto dont_try;
6556 }
6557 if (l_clusters[i].e_addr != l_clusters[i + 1].b_addr) {
6558 goto dont_try;
6559 }
6560 }
6561 }
6562 if (vm_initiated == TRUE) {
6563 lck_mtx_unlock(&wbp->cl_lockw);
6564 }
6565
6566 for (cl_index = 0; cl_index < cl_len; cl_index++) {
6567 int flags;
6568 struct cl_extent cl;
6569 int retval;
6570
6571 flags = io_flags & (IO_PASSIVE | IO_CLOSE);
6572
6573 /*
6574 * try to push each cluster in turn...
6575 */
6576 if (l_clusters[cl_index].io_flags & CLW_IONOCACHE) {
6577 flags |= IO_NOCACHE;
6578 }
6579
6580 if (l_clusters[cl_index].io_flags & CLW_IOPASSIVE) {
6581 flags |= IO_PASSIVE;
6582 }
6583
6584 if (push_flag & PUSH_SYNC) {
6585 flags |= IO_SYNC;
6586 }
6587
6588 cl.b_addr = l_clusters[cl_index].b_addr;
6589 cl.e_addr = l_clusters[cl_index].e_addr;
6590
6591 retval = cluster_push_now(vp, &cl, EOF, flags, callback, callback_arg, vm_initiated);
6592
6593 if (retval == 0) {
6594 cl_pushed++;
6595
6596 l_clusters[cl_index].b_addr = 0;
6597 l_clusters[cl_index].e_addr = 0;
6598 } else if (error == 0) {
6599 error = retval;
6600 }
6601
6602 if (!(push_flag & PUSH_ALL)) {
6603 break;
6604 }
6605 }
6606 if (vm_initiated == TRUE) {
6607 lck_mtx_lock(&wbp->cl_lockw);
6608 }
6609
6610 if (err) {
6611 *err = error;
6612 }
6613
6614 dont_try:
6615 if (cl_len > cl_pushed) {
6616 /*
6617 * we didn't push all of the clusters, so
6618 * lets try to merge them back in to the vnode
6619 */
6620 if ((MAX_CLUSTERS - wbp->cl_number) < (cl_len - cl_pushed)) {
6621 /*
6622 * we picked up some new clusters while we were trying to
6623 * push the old ones... this can happen because I've dropped
6624 * the vnode lock... the sum of the
6625 * leftovers plus the new cluster count exceeds our ability
6626 * to represent them, so switch to the sparse cluster mechanism
6627 *
6628 * collect the active public clusters...
6629 */
6630 sparse_cluster_switch(wbp, vp, EOF, callback, callback_arg, vm_initiated);
6631
6632 for (cl_index = 0, cl_index1 = 0; cl_index < cl_len; cl_index++) {
6633 if (l_clusters[cl_index].b_addr == l_clusters[cl_index].e_addr) {
6634 continue;
6635 }
6636 wbp->cl_clusters[cl_index1].b_addr = l_clusters[cl_index].b_addr;
6637 wbp->cl_clusters[cl_index1].e_addr = l_clusters[cl_index].e_addr;
6638 wbp->cl_clusters[cl_index1].io_flags = l_clusters[cl_index].io_flags;
6639
6640 cl_index1++;
6641 }
6642 /*
6643 * update the cluster count
6644 */
6645 wbp->cl_number = cl_index1;
6646
6647 /*
6648 * and collect the original clusters that were moved into the
6649 * local storage for sorting purposes
6650 */
6651 sparse_cluster_switch(wbp, vp, EOF, callback, callback_arg, vm_initiated);
6652 } else {
6653 /*
6654 * we've got room to merge the leftovers back in
6655 * just append them starting at the next 'hole'
6656 * represented by wbp->cl_number
6657 */
6658 for (cl_index = 0, cl_index1 = wbp->cl_number; cl_index < cl_len; cl_index++) {
6659 if (l_clusters[cl_index].b_addr == l_clusters[cl_index].e_addr) {
6660 continue;
6661 }
6662
6663 wbp->cl_clusters[cl_index1].b_addr = l_clusters[cl_index].b_addr;
6664 wbp->cl_clusters[cl_index1].e_addr = l_clusters[cl_index].e_addr;
6665 wbp->cl_clusters[cl_index1].io_flags = l_clusters[cl_index].io_flags;
6666
6667 cl_index1++;
6668 }
6669 /*
6670 * update the cluster count
6671 */
6672 wbp->cl_number = cl_index1;
6673 }
6674 }
6675 return MAX_CLUSTERS - wbp->cl_number;
6676 }
6677
6678
6679
6680 static int
cluster_push_now(vnode_t vp,struct cl_extent * cl,off_t EOF,int flags,int (* callback)(buf_t,void *),void * callback_arg,boolean_t vm_initiated)6681 cluster_push_now(vnode_t vp, struct cl_extent *cl, off_t EOF, int flags,
6682 int (*callback)(buf_t, void *), void *callback_arg, boolean_t vm_initiated)
6683 {
6684 upl_page_info_t *pl;
6685 upl_t upl;
6686 vm_offset_t upl_offset;
6687 int upl_size;
6688 off_t upl_f_offset;
6689 int pages_in_upl;
6690 int start_pg;
6691 int last_pg;
6692 int io_size;
6693 int io_flags;
6694 int upl_flags;
6695 int bflag;
6696 int size;
6697 int error = 0;
6698 int retval;
6699 kern_return_t kret;
6700
6701 if (flags & IO_PASSIVE) {
6702 bflag = CL_PASSIVE;
6703 } else {
6704 bflag = 0;
6705 }
6706
6707 if (flags & IO_SKIP_ENCRYPTION) {
6708 bflag |= CL_ENCRYPTED;
6709 }
6710
6711 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 51)) | DBG_FUNC_START,
6712 (int)cl->b_addr, (int)cl->e_addr, (int)EOF, flags, 0);
6713
6714 if ((pages_in_upl = (int)(cl->e_addr - cl->b_addr)) == 0) {
6715 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 51)) | DBG_FUNC_END, 1, 0, 0, 0, 0);
6716
6717 return 0;
6718 }
6719 upl_size = pages_in_upl * PAGE_SIZE;
6720 upl_f_offset = (off_t)(cl->b_addr * PAGE_SIZE_64);
6721
6722 if (upl_f_offset + upl_size >= EOF) {
6723 if (upl_f_offset >= EOF) {
6724 /*
6725 * must have truncated the file and missed
6726 * clearing a dangling cluster (i.e. it's completely
6727 * beyond the new EOF
6728 */
6729 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 51)) | DBG_FUNC_END, 1, 1, 0, 0, 0);
6730
6731 return 0;
6732 }
6733 size = (int)(EOF - upl_f_offset);
6734
6735 upl_size = (size + (PAGE_SIZE - 1)) & ~PAGE_MASK;
6736 pages_in_upl = upl_size / PAGE_SIZE;
6737 } else {
6738 size = upl_size;
6739 }
6740
6741
6742 if (vm_initiated) {
6743 vnode_pageout(vp, NULL, (upl_offset_t)0, upl_f_offset, (upl_size_t)upl_size,
6744 UPL_MSYNC | UPL_VNODE_PAGER | UPL_KEEPCACHED, &error);
6745
6746 return error;
6747 }
6748 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 41)) | DBG_FUNC_START, upl_size, size, 0, 0, 0);
6749
6750 /*
6751 * by asking for UPL_COPYOUT_FROM and UPL_RET_ONLY_DIRTY, we get the following desirable behavior
6752 *
6753 * - only pages that are currently dirty are returned... these are the ones we need to clean
6754 * - the hardware dirty bit is cleared when the page is gathered into the UPL... the software dirty bit is set
6755 * - if we have to abort the I/O for some reason, the software dirty bit is left set since we didn't clean the page
6756 * - when we commit the page, the software dirty bit is cleared... the hardware dirty bit is untouched so that if
6757 * someone dirties this page while the I/O is in progress, we don't lose track of the new state
6758 *
6759 * when the I/O completes, we no longer ask for an explicit clear of the DIRTY state (either soft or hard)
6760 */
6761
6762 if ((vp->v_flag & VNOCACHE_DATA) || (flags & IO_NOCACHE)) {
6763 upl_flags = UPL_COPYOUT_FROM | UPL_RET_ONLY_DIRTY | UPL_SET_LITE | UPL_WILL_BE_DUMPED;
6764 } else {
6765 upl_flags = UPL_COPYOUT_FROM | UPL_RET_ONLY_DIRTY | UPL_SET_LITE;
6766 }
6767
6768 kret = ubc_create_upl_kernel(vp,
6769 upl_f_offset,
6770 upl_size,
6771 &upl,
6772 &pl,
6773 upl_flags,
6774 VM_KERN_MEMORY_FILE);
6775 if (kret != KERN_SUCCESS) {
6776 panic("cluster_push: failed to get pagelist");
6777 }
6778
6779 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 41)) | DBG_FUNC_END, upl, upl_f_offset, 0, 0, 0);
6780
6781 /*
6782 * since we only asked for the dirty pages back
6783 * it's possible that we may only get a few or even none, so...
6784 * before we start marching forward, we must make sure we know
6785 * where the last present page is in the UPL, otherwise we could
6786 * end up working with a freed upl due to the FREE_ON_EMPTY semantics
6787 * employed by commit_range and abort_range.
6788 */
6789 for (last_pg = pages_in_upl - 1; last_pg >= 0; last_pg--) {
6790 if (upl_page_present(pl, last_pg)) {
6791 break;
6792 }
6793 }
6794 pages_in_upl = last_pg + 1;
6795
6796 if (pages_in_upl == 0) {
6797 ubc_upl_abort(upl, 0);
6798
6799 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 51)) | DBG_FUNC_END, 1, 2, 0, 0, 0);
6800 return 0;
6801 }
6802
6803 for (last_pg = 0; last_pg < pages_in_upl;) {
6804 /*
6805 * find the next dirty page in the UPL
6806 * this will become the first page in the
6807 * next I/O to generate
6808 */
6809 for (start_pg = last_pg; start_pg < pages_in_upl; start_pg++) {
6810 if (upl_dirty_page(pl, start_pg)) {
6811 break;
6812 }
6813 if (upl_page_present(pl, start_pg)) {
6814 /*
6815 * RET_ONLY_DIRTY will return non-dirty 'precious' pages
6816 * just release these unchanged since we're not going
6817 * to steal them or change their state
6818 */
6819 ubc_upl_abort_range(upl, start_pg * PAGE_SIZE, PAGE_SIZE, UPL_ABORT_FREE_ON_EMPTY);
6820 }
6821 }
6822 if (start_pg >= pages_in_upl) {
6823 /*
6824 * done... no more dirty pages to push
6825 */
6826 break;
6827 }
6828 if (start_pg > last_pg) {
6829 /*
6830 * skipped over some non-dirty pages
6831 */
6832 size -= ((start_pg - last_pg) * PAGE_SIZE);
6833 }
6834
6835 /*
6836 * find a range of dirty pages to write
6837 */
6838 for (last_pg = start_pg; last_pg < pages_in_upl; last_pg++) {
6839 if (!upl_dirty_page(pl, last_pg)) {
6840 break;
6841 }
6842 }
6843 upl_offset = start_pg * PAGE_SIZE;
6844
6845 io_size = min(size, (last_pg - start_pg) * PAGE_SIZE);
6846
6847 io_flags = CL_THROTTLE | CL_COMMIT | CL_AGE | bflag;
6848
6849 if (!(flags & IO_SYNC)) {
6850 io_flags |= CL_ASYNC;
6851 }
6852
6853 if (flags & IO_CLOSE) {
6854 io_flags |= CL_CLOSE;
6855 }
6856
6857 if (flags & IO_NOCACHE) {
6858 io_flags |= CL_NOCACHE;
6859 }
6860
6861 retval = cluster_io(vp, upl, upl_offset, upl_f_offset + upl_offset, io_size,
6862 io_flags, (buf_t)NULL, (struct clios *)NULL, callback, callback_arg);
6863
6864 if (error == 0 && retval) {
6865 error = retval;
6866 }
6867
6868 size -= io_size;
6869 }
6870 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 51)) | DBG_FUNC_END, 1, 3, error, 0, 0);
6871
6872 return error;
6873 }
6874
6875
6876 /*
6877 * sparse_cluster_switch is called with the write behind lock held
6878 */
6879 static int
sparse_cluster_switch(struct cl_writebehind * wbp,vnode_t vp,off_t EOF,int (* callback)(buf_t,void *),void * callback_arg,boolean_t vm_initiated)6880 sparse_cluster_switch(struct cl_writebehind *wbp, vnode_t vp, off_t EOF, int (*callback)(buf_t, void *), void *callback_arg, boolean_t vm_initiated)
6881 {
6882 int cl_index;
6883 int error = 0;
6884
6885 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 78)) | DBG_FUNC_START, kdebug_vnode(vp), wbp->cl_scmap, wbp->cl_number, 0, 0);
6886
6887 for (cl_index = 0; cl_index < wbp->cl_number; cl_index++) {
6888 int flags;
6889 struct cl_extent cl;
6890
6891 for (cl.b_addr = wbp->cl_clusters[cl_index].b_addr; cl.b_addr < wbp->cl_clusters[cl_index].e_addr; cl.b_addr++) {
6892 if (ubc_page_op(vp, (off_t)(cl.b_addr * PAGE_SIZE_64), 0, NULL, &flags) == KERN_SUCCESS) {
6893 if (flags & UPL_POP_DIRTY) {
6894 cl.e_addr = cl.b_addr + 1;
6895
6896 error = sparse_cluster_add(wbp, &(wbp->cl_scmap), vp, &cl, EOF, callback, callback_arg, vm_initiated);
6897
6898 if (error) {
6899 break;
6900 }
6901 }
6902 }
6903 }
6904 }
6905 wbp->cl_number -= cl_index;
6906
6907 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 78)) | DBG_FUNC_END, kdebug_vnode(vp), wbp->cl_scmap, wbp->cl_number, error, 0);
6908
6909 return error;
6910 }
6911
6912
6913 /*
6914 * sparse_cluster_push must be called with the write-behind lock held if the scmap is
6915 * still associated with the write-behind context... however, if the scmap has been disassociated
6916 * from the write-behind context (the cluster_push case), the wb lock is not held
6917 */
6918 static int
sparse_cluster_push(struct cl_writebehind * wbp,void ** scmap,vnode_t vp,off_t EOF,int push_flag,int io_flags,int (* callback)(buf_t,void *),void * callback_arg,boolean_t vm_initiated)6919 sparse_cluster_push(struct cl_writebehind *wbp, void **scmap, vnode_t vp, off_t EOF, int push_flag,
6920 int io_flags, int (*callback)(buf_t, void *), void *callback_arg, boolean_t vm_initiated)
6921 {
6922 struct cl_extent cl;
6923 off_t offset;
6924 u_int length;
6925 void *l_scmap;
6926 int error = 0;
6927
6928 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 79)) | DBG_FUNC_START, kdebug_vnode(vp), (*scmap), 0, push_flag, 0);
6929
6930 if (push_flag & PUSH_ALL) {
6931 vfs_drt_control(scmap, 1);
6932 }
6933
6934 l_scmap = *scmap;
6935
6936 for (;;) {
6937 int retval;
6938
6939 if (vfs_drt_get_cluster(scmap, &offset, &length) != KERN_SUCCESS) {
6940 /*
6941 * Not finding anything to push will return KERN_FAILURE.
6942 * Confusing since it isn't really a failure. But that's the
6943 * reason we don't set 'error' here like we do below.
6944 */
6945 break;
6946 }
6947
6948 if (vm_initiated == TRUE) {
6949 lck_mtx_unlock(&wbp->cl_lockw);
6950 }
6951
6952 cl.b_addr = (daddr64_t)(offset / PAGE_SIZE_64);
6953 cl.e_addr = (daddr64_t)((offset + length) / PAGE_SIZE_64);
6954
6955 retval = cluster_push_now(vp, &cl, EOF, io_flags, callback, callback_arg, vm_initiated);
6956 if (error == 0 && retval) {
6957 error = retval;
6958 }
6959
6960 if (vm_initiated == TRUE) {
6961 lck_mtx_lock(&wbp->cl_lockw);
6962
6963 if (*scmap != l_scmap) {
6964 break;
6965 }
6966 }
6967
6968 if (error) {
6969 if (vfs_drt_mark_pages(scmap, offset, length, NULL) != KERN_SUCCESS) {
6970 panic("Failed to restore dirty state on failure");
6971 }
6972
6973 break;
6974 }
6975
6976 if (!(push_flag & PUSH_ALL)) {
6977 break;
6978 }
6979 }
6980 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 79)) | DBG_FUNC_END, kdebug_vnode(vp), (*scmap), error, 0, 0);
6981
6982 return error;
6983 }
6984
6985
6986 /*
6987 * sparse_cluster_add is called with the write behind lock held
6988 */
6989 static int
sparse_cluster_add(struct cl_writebehind * wbp,void ** scmap,vnode_t vp,struct cl_extent * cl,off_t EOF,int (* callback)(buf_t,void *),void * callback_arg,boolean_t vm_initiated)6990 sparse_cluster_add(struct cl_writebehind *wbp, void **scmap, vnode_t vp, struct cl_extent *cl, off_t EOF,
6991 int (*callback)(buf_t, void *), void *callback_arg, boolean_t vm_initiated)
6992 {
6993 u_int new_dirty;
6994 u_int length;
6995 off_t offset;
6996 int error = 0;
6997 int push_flag = 0; /* Is this a valid value? */
6998
6999 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 80)) | DBG_FUNC_START, (*scmap), 0, cl->b_addr, (int)cl->e_addr, 0);
7000
7001 offset = (off_t)(cl->b_addr * PAGE_SIZE_64);
7002 length = ((u_int)(cl->e_addr - cl->b_addr)) * PAGE_SIZE;
7003
7004 while (vfs_drt_mark_pages(scmap, offset, length, &new_dirty) != KERN_SUCCESS) {
7005 /*
7006 * no room left in the map
7007 * only a partial update was done
7008 * push out some pages and try again
7009 */
7010
7011 if (vfs_get_scmap_push_behavior_internal(scmap, &push_flag)) {
7012 push_flag = 0;
7013 }
7014
7015 error = sparse_cluster_push(wbp, scmap, vp, EOF, push_flag, 0, callback, callback_arg, vm_initiated);
7016
7017 if (error) {
7018 break;
7019 }
7020
7021 offset += (new_dirty * PAGE_SIZE_64);
7022 length -= (new_dirty * PAGE_SIZE);
7023 }
7024 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 80)) | DBG_FUNC_END, kdebug_vnode(vp), (*scmap), error, 0, 0);
7025
7026 return error;
7027 }
7028
7029
7030 static int
cluster_align_phys_io(vnode_t vp,struct uio * uio,addr64_t usr_paddr,u_int32_t xsize,int flags,int (* callback)(buf_t,void *),void * callback_arg)7031 cluster_align_phys_io(vnode_t vp, struct uio *uio, addr64_t usr_paddr, u_int32_t xsize, int flags, int (*callback)(buf_t, void *), void *callback_arg)
7032 {
7033 upl_page_info_t *pl;
7034 upl_t upl;
7035 addr64_t ubc_paddr;
7036 kern_return_t kret;
7037 int error = 0;
7038 int did_read = 0;
7039 int abort_flags;
7040 int upl_flags;
7041 int bflag;
7042
7043 if (flags & IO_PASSIVE) {
7044 bflag = CL_PASSIVE;
7045 } else {
7046 bflag = 0;
7047 }
7048
7049 if (flags & IO_NOCACHE) {
7050 bflag |= CL_NOCACHE;
7051 }
7052
7053 upl_flags = UPL_SET_LITE;
7054
7055 if (!(flags & CL_READ)) {
7056 /*
7057 * "write" operation: let the UPL subsystem know
7058 * that we intend to modify the buffer cache pages
7059 * we're gathering.
7060 */
7061 upl_flags |= UPL_WILL_MODIFY;
7062 } else {
7063 /*
7064 * indicate that there is no need to pull the
7065 * mapping for this page... we're only going
7066 * to read from it, not modify it.
7067 */
7068 upl_flags |= UPL_FILE_IO;
7069 }
7070 kret = ubc_create_upl_kernel(vp,
7071 uio->uio_offset & ~PAGE_MASK_64,
7072 PAGE_SIZE,
7073 &upl,
7074 &pl,
7075 upl_flags,
7076 VM_KERN_MEMORY_FILE);
7077
7078 if (kret != KERN_SUCCESS) {
7079 return EINVAL;
7080 }
7081
7082 if (!upl_valid_page(pl, 0)) {
7083 /*
7084 * issue a synchronous read to cluster_io
7085 */
7086 error = cluster_io(vp, upl, 0, uio->uio_offset & ~PAGE_MASK_64, PAGE_SIZE,
7087 CL_READ | bflag, (buf_t)NULL, (struct clios *)NULL, callback, callback_arg);
7088 if (error) {
7089 ubc_upl_abort_range(upl, 0, PAGE_SIZE, UPL_ABORT_DUMP_PAGES | UPL_ABORT_FREE_ON_EMPTY);
7090
7091 return error;
7092 }
7093 did_read = 1;
7094 }
7095 ubc_paddr = ((addr64_t)upl_phys_page(pl, 0) << PAGE_SHIFT) + (addr64_t)(uio->uio_offset & PAGE_MASK_64);
7096
7097 /*
7098 * NOTE: There is no prototype for the following in BSD. It, and the definitions
7099 * of the defines for cppvPsrc, cppvPsnk, cppvFsnk, and cppvFsrc will be found in
7100 * osfmk/ppc/mappings.h. They are not included here because there appears to be no
7101 * way to do so without exporting them to kexts as well.
7102 */
7103 if (flags & CL_READ) {
7104 // copypv(ubc_paddr, usr_paddr, xsize, cppvPsrc | cppvPsnk | cppvFsnk); /* Copy physical to physical and flush the destination */
7105 copypv(ubc_paddr, usr_paddr, xsize, 2 | 1 | 4); /* Copy physical to physical and flush the destination */
7106 } else {
7107 // copypv(usr_paddr, ubc_paddr, xsize, cppvPsrc | cppvPsnk | cppvFsrc); /* Copy physical to physical and flush the source */
7108 copypv(usr_paddr, ubc_paddr, xsize, 2 | 1 | 8); /* Copy physical to physical and flush the source */
7109 }
7110 if (!(flags & CL_READ) || (upl_valid_page(pl, 0) && upl_dirty_page(pl, 0))) {
7111 /*
7112 * issue a synchronous write to cluster_io
7113 */
7114 error = cluster_io(vp, upl, 0, uio->uio_offset & ~PAGE_MASK_64, PAGE_SIZE,
7115 bflag, (buf_t)NULL, (struct clios *)NULL, callback, callback_arg);
7116 }
7117 if (error == 0) {
7118 uio_update(uio, (user_size_t)xsize);
7119 }
7120
7121 if (did_read) {
7122 abort_flags = UPL_ABORT_FREE_ON_EMPTY;
7123 } else {
7124 abort_flags = UPL_ABORT_FREE_ON_EMPTY | UPL_ABORT_DUMP_PAGES;
7125 }
7126
7127 ubc_upl_abort_range(upl, 0, PAGE_SIZE, abort_flags);
7128
7129 return error;
7130 }
7131
7132 int
cluster_copy_upl_data(struct uio * uio,upl_t upl,int upl_offset,int * io_resid)7133 cluster_copy_upl_data(struct uio *uio, upl_t upl, int upl_offset, int *io_resid)
7134 {
7135 int pg_offset;
7136 int pg_index;
7137 int csize;
7138 int segflg;
7139 int retval = 0;
7140 int xsize;
7141 upl_page_info_t *pl;
7142 int dirty_count;
7143
7144 xsize = *io_resid;
7145
7146 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 34)) | DBG_FUNC_START,
7147 (int)uio->uio_offset, upl_offset, xsize, 0, 0);
7148
7149 segflg = uio->uio_segflg;
7150
7151 switch (segflg) {
7152 case UIO_USERSPACE32:
7153 case UIO_USERISPACE32:
7154 uio->uio_segflg = UIO_PHYS_USERSPACE32;
7155 break;
7156
7157 case UIO_USERSPACE:
7158 case UIO_USERISPACE:
7159 uio->uio_segflg = UIO_PHYS_USERSPACE;
7160 break;
7161
7162 case UIO_USERSPACE64:
7163 case UIO_USERISPACE64:
7164 uio->uio_segflg = UIO_PHYS_USERSPACE64;
7165 break;
7166
7167 case UIO_SYSSPACE:
7168 uio->uio_segflg = UIO_PHYS_SYSSPACE;
7169 break;
7170 }
7171 pl = ubc_upl_pageinfo(upl);
7172
7173 pg_index = upl_offset / PAGE_SIZE;
7174 pg_offset = upl_offset & PAGE_MASK;
7175 csize = min(PAGE_SIZE - pg_offset, xsize);
7176
7177 dirty_count = 0;
7178 while (xsize && retval == 0) {
7179 addr64_t paddr;
7180 ppnum_t pn = upl_phys_page(pl, pg_index);
7181
7182 paddr = ((addr64_t)pn << PAGE_SHIFT) + pg_offset;
7183 if ((uio->uio_rw == UIO_WRITE) && (upl_dirty_page(pl, pg_index) == FALSE)) {
7184 dirty_count++;
7185 }
7186
7187 /* such phyiscal pages should never be restricted pages */
7188 if (pmap_is_page_restricted(pn)) {
7189 panic("%s: cannot uiomove64 into a restricted page", __func__);
7190 }
7191
7192 retval = uiomove64(paddr, csize, uio);
7193
7194 pg_index += 1;
7195 pg_offset = 0;
7196 xsize -= csize;
7197 csize = min(PAGE_SIZE, xsize);
7198 }
7199 *io_resid = xsize;
7200
7201 uio->uio_segflg = segflg;
7202
7203 if (dirty_count) {
7204 task_update_logical_writes(current_task(), (dirty_count * PAGE_SIZE), TASK_WRITE_DEFERRED, upl_lookup_vnode(upl));
7205 }
7206
7207 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 34)) | DBG_FUNC_END,
7208 (int)uio->uio_offset, xsize, retval, segflg, 0);
7209
7210 return retval;
7211 }
7212
7213
7214 int
cluster_copy_ubc_data(vnode_t vp,struct uio * uio,int * io_resid,int mark_dirty)7215 cluster_copy_ubc_data(vnode_t vp, struct uio *uio, int *io_resid, int mark_dirty)
7216 {
7217 return cluster_copy_ubc_data_internal(vp, uio, io_resid, mark_dirty, 1);
7218 }
7219
7220
7221 static int
cluster_copy_ubc_data_internal(vnode_t vp,struct uio * uio,int * io_resid,int mark_dirty,int take_reference)7222 cluster_copy_ubc_data_internal(vnode_t vp, struct uio *uio, int *io_resid, int mark_dirty, int take_reference)
7223 {
7224 int segflg;
7225 int io_size;
7226 int xsize;
7227 int start_offset;
7228 int retval = 0;
7229 memory_object_control_t control;
7230
7231 io_size = *io_resid;
7232
7233 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 34)) | DBG_FUNC_START,
7234 (int)uio->uio_offset, io_size, mark_dirty, take_reference, 0);
7235
7236 control = ubc_getobject(vp, UBC_FLAGS_NONE);
7237
7238 if (control == MEMORY_OBJECT_CONTROL_NULL) {
7239 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 34)) | DBG_FUNC_END,
7240 (int)uio->uio_offset, io_size, retval, 3, 0);
7241
7242 return 0;
7243 }
7244 segflg = uio->uio_segflg;
7245
7246 switch (segflg) {
7247 case UIO_USERSPACE32:
7248 case UIO_USERISPACE32:
7249 uio->uio_segflg = UIO_PHYS_USERSPACE32;
7250 break;
7251
7252 case UIO_USERSPACE64:
7253 case UIO_USERISPACE64:
7254 uio->uio_segflg = UIO_PHYS_USERSPACE64;
7255 break;
7256
7257 case UIO_USERSPACE:
7258 case UIO_USERISPACE:
7259 uio->uio_segflg = UIO_PHYS_USERSPACE;
7260 break;
7261
7262 case UIO_SYSSPACE:
7263 uio->uio_segflg = UIO_PHYS_SYSSPACE;
7264 break;
7265 }
7266
7267 if ((io_size = *io_resid)) {
7268 start_offset = (int)(uio->uio_offset & PAGE_MASK_64);
7269 xsize = (int)uio_resid(uio);
7270
7271 retval = memory_object_control_uiomove(control, uio->uio_offset - start_offset, uio,
7272 start_offset, io_size, mark_dirty, take_reference);
7273 xsize -= uio_resid(uio);
7274
7275 int num_bytes_copied = xsize;
7276 if (num_bytes_copied && uio_rw(uio)) {
7277 task_update_logical_writes(current_task(), num_bytes_copied, TASK_WRITE_DEFERRED, vp);
7278 }
7279 io_size -= xsize;
7280 }
7281 uio->uio_segflg = segflg;
7282 *io_resid = io_size;
7283
7284 KERNEL_DEBUG((FSDBG_CODE(DBG_FSRW, 34)) | DBG_FUNC_END,
7285 (int)uio->uio_offset, io_size, retval, 0x80000000 | segflg, 0);
7286
7287 return retval;
7288 }
7289
7290
7291 int
is_file_clean(vnode_t vp,off_t filesize)7292 is_file_clean(vnode_t vp, off_t filesize)
7293 {
7294 off_t f_offset;
7295 int flags;
7296 int total_dirty = 0;
7297
7298 for (f_offset = 0; f_offset < filesize; f_offset += PAGE_SIZE_64) {
7299 if (ubc_page_op(vp, f_offset, 0, NULL, &flags) == KERN_SUCCESS) {
7300 if (flags & UPL_POP_DIRTY) {
7301 total_dirty++;
7302 }
7303 }
7304 }
7305 if (total_dirty) {
7306 return EINVAL;
7307 }
7308
7309 return 0;
7310 }
7311
7312
7313
7314 /*
7315 * Dirty region tracking/clustering mechanism.
7316 *
7317 * This code (vfs_drt_*) provides a mechanism for tracking and clustering
7318 * dirty regions within a larger space (file). It is primarily intended to
7319 * support clustering in large files with many dirty areas.
7320 *
7321 * The implementation assumes that the dirty regions are pages.
7322 *
7323 * To represent dirty pages within the file, we store bit vectors in a
7324 * variable-size circular hash.
7325 */
7326
7327 /*
7328 * Bitvector size. This determines the number of pages we group in a
7329 * single hashtable entry. Each hashtable entry is aligned to this
7330 * size within the file.
7331 */
7332 #define DRT_BITVECTOR_PAGES ((1024 * 256) / PAGE_SIZE)
7333
7334 /*
7335 * File offset handling.
7336 *
7337 * DRT_ADDRESS_MASK is dependent on DRT_BITVECTOR_PAGES;
7338 * the correct formula is (~((DRT_BITVECTOR_PAGES * PAGE_SIZE) - 1))
7339 */
7340 #define DRT_ADDRESS_MASK (~((DRT_BITVECTOR_PAGES * PAGE_SIZE) - 1))
7341 #define DRT_ALIGN_ADDRESS(addr) ((addr) & DRT_ADDRESS_MASK)
7342
7343 /*
7344 * Hashtable address field handling.
7345 *
7346 * The low-order bits of the hashtable address are used to conserve
7347 * space.
7348 *
7349 * DRT_HASH_COUNT_MASK must be large enough to store the range
7350 * 0-DRT_BITVECTOR_PAGES inclusive, as well as have one value
7351 * to indicate that the bucket is actually unoccupied.
7352 */
7353 #define DRT_HASH_GET_ADDRESS(scm, i) ((scm)->scm_hashtable[(i)].dhe_control & DRT_ADDRESS_MASK)
7354 #define DRT_HASH_SET_ADDRESS(scm, i, a) \
7355 do { \
7356 (scm)->scm_hashtable[(i)].dhe_control = \
7357 ((scm)->scm_hashtable[(i)].dhe_control & ~DRT_ADDRESS_MASK) | DRT_ALIGN_ADDRESS(a); \
7358 } while (0)
7359 #define DRT_HASH_COUNT_MASK 0x1ff
7360 #define DRT_HASH_GET_COUNT(scm, i) ((scm)->scm_hashtable[(i)].dhe_control & DRT_HASH_COUNT_MASK)
7361 #define DRT_HASH_SET_COUNT(scm, i, c) \
7362 do { \
7363 (scm)->scm_hashtable[(i)].dhe_control = \
7364 ((scm)->scm_hashtable[(i)].dhe_control & ~DRT_HASH_COUNT_MASK) | ((c) & DRT_HASH_COUNT_MASK); \
7365 } while (0)
7366 #define DRT_HASH_CLEAR(scm, i) \
7367 do { \
7368 (scm)->scm_hashtable[(i)].dhe_control = 0; \
7369 } while (0)
7370 #define DRT_HASH_VACATE(scm, i) DRT_HASH_SET_COUNT((scm), (i), DRT_HASH_COUNT_MASK)
7371 #define DRT_HASH_VACANT(scm, i) (DRT_HASH_GET_COUNT((scm), (i)) == DRT_HASH_COUNT_MASK)
7372 #define DRT_HASH_COPY(oscm, oi, scm, i) \
7373 do { \
7374 (scm)->scm_hashtable[(i)].dhe_control = (oscm)->scm_hashtable[(oi)].dhe_control; \
7375 DRT_BITVECTOR_COPY(oscm, oi, scm, i); \
7376 } while(0);
7377
7378
7379 #if !defined(XNU_TARGET_OS_OSX)
7380 /*
7381 * Hash table moduli.
7382 *
7383 * Since the hashtable entry's size is dependent on the size of
7384 * the bitvector, and since the hashtable size is constrained to
7385 * both being prime and fitting within the desired allocation
7386 * size, these values need to be manually determined.
7387 *
7388 * For DRT_BITVECTOR_SIZE = 64, the entry size is 16 bytes.
7389 *
7390 * The small hashtable allocation is 4096 bytes, so the modulus is 251.
7391 * The large hashtable allocation is 32768 bytes, so the modulus is 2039.
7392 * The xlarge hashtable allocation is 131072 bytes, so the modulus is 8179.
7393 */
7394
7395 #define DRT_HASH_SMALL_MODULUS 251
7396 #define DRT_HASH_LARGE_MODULUS 2039
7397 #define DRT_HASH_XLARGE_MODULUS 8179
7398
7399 /*
7400 * Physical memory required before the large hash modulus is permitted.
7401 *
7402 * On small memory systems, the large hash modulus can lead to phsyical
7403 * memory starvation, so we avoid using it there.
7404 */
7405 #define DRT_HASH_LARGE_MEMORY_REQUIRED (1024LL * 1024LL * 1024LL) /* 1GiB */
7406 #define DRT_HASH_XLARGE_MEMORY_REQUIRED (8 * 1024LL * 1024LL * 1024LL) /* 8GiB */
7407
7408 #define DRT_SMALL_ALLOCATION 4096 /* 80 bytes spare */
7409 #define DRT_LARGE_ALLOCATION 32768 /* 144 bytes spare */
7410 #define DRT_XLARGE_ALLOCATION 131072 /* 208 bytes spare */
7411
7412 #else /* XNU_TARGET_OS_OSX */
7413 /*
7414 * Hash table moduli.
7415 *
7416 * Since the hashtable entry's size is dependent on the size of
7417 * the bitvector, and since the hashtable size is constrained to
7418 * both being prime and fitting within the desired allocation
7419 * size, these values need to be manually determined.
7420 *
7421 * For DRT_BITVECTOR_SIZE = 64, the entry size is 16 bytes.
7422 *
7423 * The small hashtable allocation is 16384 bytes, so the modulus is 1019.
7424 * The large hashtable allocation is 131072 bytes, so the modulus is 8179.
7425 * The xlarge hashtable allocation is 524288 bytes, so the modulus is 32749.
7426 */
7427
7428 #define DRT_HASH_SMALL_MODULUS 1019
7429 #define DRT_HASH_LARGE_MODULUS 8179
7430 #define DRT_HASH_XLARGE_MODULUS 32749
7431
7432 /*
7433 * Physical memory required before the large hash modulus is permitted.
7434 *
7435 * On small memory systems, the large hash modulus can lead to phsyical
7436 * memory starvation, so we avoid using it there.
7437 */
7438 #define DRT_HASH_LARGE_MEMORY_REQUIRED (4 * 1024LL * 1024LL * 1024LL) /* 4GiB */
7439 #define DRT_HASH_XLARGE_MEMORY_REQUIRED (32 * 1024LL * 1024LL * 1024LL) /* 32GiB */
7440
7441 #define DRT_SMALL_ALLOCATION 16384 /* 80 bytes spare */
7442 #define DRT_LARGE_ALLOCATION 131072 /* 208 bytes spare */
7443 #define DRT_XLARGE_ALLOCATION 524288 /* 304 bytes spare */
7444
7445 #endif /* ! XNU_TARGET_OS_OSX */
7446
7447 /* *** nothing below here has secret dependencies on DRT_BITVECTOR_PAGES *** */
7448
7449 /*
7450 * Hashtable entry.
7451 */
7452 struct vfs_drt_hashentry {
7453 u_int64_t dhe_control;
7454 /*
7455 * dhe_bitvector was declared as dhe_bitvector[DRT_BITVECTOR_PAGES / 32];
7456 * DRT_BITVECTOR_PAGES is defined as ((1024 * 256) / PAGE_SIZE)
7457 * Since PAGE_SIZE is only known at boot time,
7458 * -define MAX_DRT_BITVECTOR_PAGES for smallest supported page size (4k)
7459 * -declare dhe_bitvector array for largest possible length
7460 */
7461 #define MAX_DRT_BITVECTOR_PAGES (1024 * 256)/( 4 * 1024)
7462 u_int32_t dhe_bitvector[MAX_DRT_BITVECTOR_PAGES / 32];
7463 };
7464
7465 /*
7466 * Hashtable bitvector handling.
7467 *
7468 * Bitvector fields are 32 bits long.
7469 */
7470
7471 #define DRT_HASH_SET_BIT(scm, i, bit) \
7472 (scm)->scm_hashtable[(i)].dhe_bitvector[(bit) / 32] |= (1 << ((bit) % 32))
7473
7474 #define DRT_HASH_CLEAR_BIT(scm, i, bit) \
7475 (scm)->scm_hashtable[(i)].dhe_bitvector[(bit) / 32] &= ~(1 << ((bit) % 32))
7476
7477 #define DRT_HASH_TEST_BIT(scm, i, bit) \
7478 ((scm)->scm_hashtable[(i)].dhe_bitvector[(bit) / 32] & (1 << ((bit) % 32)))
7479
7480 #define DRT_BITVECTOR_CLEAR(scm, i) \
7481 bzero(&(scm)->scm_hashtable[(i)].dhe_bitvector[0], (MAX_DRT_BITVECTOR_PAGES / 32) * sizeof(u_int32_t))
7482
7483 #define DRT_BITVECTOR_COPY(oscm, oi, scm, i) \
7484 bcopy(&(oscm)->scm_hashtable[(oi)].dhe_bitvector[0], \
7485 &(scm)->scm_hashtable[(i)].dhe_bitvector[0], \
7486 (MAX_DRT_BITVECTOR_PAGES / 32) * sizeof(u_int32_t))
7487
7488 /*
7489 * Dirty Region Tracking structure.
7490 *
7491 * The hashtable is allocated entirely inside the DRT structure.
7492 *
7493 * The hash is a simple circular prime modulus arrangement, the structure
7494 * is resized from small to large if it overflows.
7495 */
7496
7497 struct vfs_drt_clustermap {
7498 u_int32_t scm_magic; /* sanity/detection */
7499 #define DRT_SCM_MAGIC 0x12020003
7500 u_int32_t scm_modulus; /* current ring size */
7501 u_int32_t scm_buckets; /* number of occupied buckets */
7502 u_int32_t scm_lastclean; /* last entry we cleaned */
7503 u_int32_t scm_iskips; /* number of slot skips */
7504
7505 struct vfs_drt_hashentry scm_hashtable[0];
7506 };
7507
7508
7509 #define DRT_HASH(scm, addr) ((addr) % (scm)->scm_modulus)
7510 #define DRT_HASH_NEXT(scm, addr) (((addr) + 1) % (scm)->scm_modulus)
7511
7512 /*
7513 * Debugging codes and arguments.
7514 */
7515 #define DRT_DEBUG_EMPTYFREE (FSDBG_CODE(DBG_FSRW, 82)) /* nil */
7516 #define DRT_DEBUG_RETCLUSTER (FSDBG_CODE(DBG_FSRW, 83)) /* offset, length */
7517 #define DRT_DEBUG_ALLOC (FSDBG_CODE(DBG_FSRW, 84)) /* copycount */
7518 #define DRT_DEBUG_INSERT (FSDBG_CODE(DBG_FSRW, 85)) /* offset, iskip */
7519 #define DRT_DEBUG_MARK (FSDBG_CODE(DBG_FSRW, 86)) /* offset, length,
7520 * dirty */
7521 /* 0, setcount */
7522 /* 1 (clean, no map) */
7523 /* 2 (map alloc fail) */
7524 /* 3, resid (partial) */
7525 #define DRT_DEBUG_6 (FSDBG_CODE(DBG_FSRW, 87))
7526 #define DRT_DEBUG_SCMDATA (FSDBG_CODE(DBG_FSRW, 88)) /* modulus, buckets,
7527 * lastclean, iskips */
7528
7529
7530 static kern_return_t vfs_drt_alloc_map(struct vfs_drt_clustermap **cmapp);
7531 static kern_return_t vfs_drt_free_map(struct vfs_drt_clustermap *cmap);
7532 static kern_return_t vfs_drt_search_index(struct vfs_drt_clustermap *cmap,
7533 u_int64_t offset, int *indexp);
7534 static kern_return_t vfs_drt_get_index(struct vfs_drt_clustermap **cmapp,
7535 u_int64_t offset,
7536 int *indexp,
7537 int recursed);
7538 static kern_return_t vfs_drt_do_mark_pages(
7539 void **cmapp,
7540 u_int64_t offset,
7541 u_int length,
7542 u_int *setcountp,
7543 int dirty);
7544 static void vfs_drt_trace(
7545 struct vfs_drt_clustermap *cmap,
7546 int code,
7547 int arg1,
7548 int arg2,
7549 int arg3,
7550 int arg4);
7551
7552
7553 /*
7554 * Allocate and initialise a sparse cluster map.
7555 *
7556 * Will allocate a new map, resize or compact an existing map.
7557 *
7558 * XXX we should probably have at least one intermediate map size,
7559 * as the 1:16 ratio seems a bit drastic.
7560 */
7561 static kern_return_t
vfs_drt_alloc_map(struct vfs_drt_clustermap ** cmapp)7562 vfs_drt_alloc_map(struct vfs_drt_clustermap **cmapp)
7563 {
7564 struct vfs_drt_clustermap *cmap = NULL, *ocmap = NULL;
7565 kern_return_t kret = KERN_SUCCESS;
7566 u_int64_t offset = 0;
7567 u_int32_t i = 0;
7568 int modulus_size = 0, map_size = 0, active_buckets = 0, index = 0, copycount = 0;
7569
7570 ocmap = NULL;
7571 if (cmapp != NULL) {
7572 ocmap = *cmapp;
7573 }
7574
7575 /*
7576 * Decide on the size of the new map.
7577 */
7578 if (ocmap == NULL) {
7579 modulus_size = DRT_HASH_SMALL_MODULUS;
7580 map_size = DRT_SMALL_ALLOCATION;
7581 } else {
7582 /* count the number of active buckets in the old map */
7583 active_buckets = 0;
7584 for (i = 0; i < ocmap->scm_modulus; i++) {
7585 if (!DRT_HASH_VACANT(ocmap, i) &&
7586 (DRT_HASH_GET_COUNT(ocmap, i) != 0)) {
7587 active_buckets++;
7588 }
7589 }
7590 /*
7591 * If we're currently using the small allocation, check to
7592 * see whether we should grow to the large one.
7593 */
7594 if (ocmap->scm_modulus == DRT_HASH_SMALL_MODULUS) {
7595 /*
7596 * If the ring is nearly full and we are allowed to
7597 * use the large modulus, upgrade.
7598 */
7599 if ((active_buckets > (DRT_HASH_SMALL_MODULUS - 5)) &&
7600 (max_mem >= DRT_HASH_LARGE_MEMORY_REQUIRED)) {
7601 modulus_size = DRT_HASH_LARGE_MODULUS;
7602 map_size = DRT_LARGE_ALLOCATION;
7603 } else {
7604 modulus_size = DRT_HASH_SMALL_MODULUS;
7605 map_size = DRT_SMALL_ALLOCATION;
7606 }
7607 } else if (ocmap->scm_modulus == DRT_HASH_LARGE_MODULUS) {
7608 if ((active_buckets > (DRT_HASH_LARGE_MODULUS - 5)) &&
7609 (max_mem >= DRT_HASH_XLARGE_MEMORY_REQUIRED)) {
7610 modulus_size = DRT_HASH_XLARGE_MODULUS;
7611 map_size = DRT_XLARGE_ALLOCATION;
7612 } else {
7613 /*
7614 * If the ring is completely full and we can't
7615 * expand, there's nothing useful for us to do.
7616 * Behave as though we had compacted into the new
7617 * array and return.
7618 */
7619 return KERN_SUCCESS;
7620 }
7621 } else {
7622 /* already using the xlarge modulus */
7623 modulus_size = DRT_HASH_XLARGE_MODULUS;
7624 map_size = DRT_XLARGE_ALLOCATION;
7625
7626 /*
7627 * If the ring is completely full, there's
7628 * nothing useful for us to do. Behave as
7629 * though we had compacted into the new
7630 * array and return.
7631 */
7632 if (active_buckets >= DRT_HASH_XLARGE_MODULUS) {
7633 return KERN_SUCCESS;
7634 }
7635 }
7636 }
7637
7638 /*
7639 * Allocate and initialise the new map.
7640 */
7641
7642 kret = kmem_alloc(kernel_map, (vm_offset_t *)&cmap, map_size,
7643 KMA_DATA, VM_KERN_MEMORY_FILE);
7644 if (kret != KERN_SUCCESS) {
7645 return kret;
7646 }
7647 cmap->scm_magic = DRT_SCM_MAGIC;
7648 cmap->scm_modulus = modulus_size;
7649 cmap->scm_buckets = 0;
7650 cmap->scm_lastclean = 0;
7651 cmap->scm_iskips = 0;
7652 for (i = 0; i < cmap->scm_modulus; i++) {
7653 DRT_HASH_CLEAR(cmap, i);
7654 DRT_HASH_VACATE(cmap, i);
7655 DRT_BITVECTOR_CLEAR(cmap, i);
7656 }
7657
7658 /*
7659 * If there's an old map, re-hash entries from it into the new map.
7660 */
7661 copycount = 0;
7662 if (ocmap != NULL) {
7663 for (i = 0; i < ocmap->scm_modulus; i++) {
7664 /* skip empty buckets */
7665 if (DRT_HASH_VACANT(ocmap, i) ||
7666 (DRT_HASH_GET_COUNT(ocmap, i) == 0)) {
7667 continue;
7668 }
7669 /* get new index */
7670 offset = DRT_HASH_GET_ADDRESS(ocmap, i);
7671 kret = vfs_drt_get_index(&cmap, offset, &index, 1);
7672 if (kret != KERN_SUCCESS) {
7673 /* XXX need to bail out gracefully here */
7674 panic("vfs_drt: new cluster map mysteriously too small");
7675 index = 0;
7676 }
7677 /* copy */
7678 DRT_HASH_COPY(ocmap, i, cmap, index);
7679 copycount++;
7680 }
7681 }
7682
7683 /* log what we've done */
7684 vfs_drt_trace(cmap, DRT_DEBUG_ALLOC, copycount, 0, 0, 0);
7685
7686 /*
7687 * It's important to ensure that *cmapp always points to
7688 * a valid map, so we must overwrite it before freeing
7689 * the old map.
7690 */
7691 *cmapp = cmap;
7692 if (ocmap != NULL) {
7693 /* emit stats into trace buffer */
7694 vfs_drt_trace(ocmap, DRT_DEBUG_SCMDATA,
7695 ocmap->scm_modulus,
7696 ocmap->scm_buckets,
7697 ocmap->scm_lastclean,
7698 ocmap->scm_iskips);
7699
7700 vfs_drt_free_map(ocmap);
7701 }
7702 return KERN_SUCCESS;
7703 }
7704
7705
7706 /*
7707 * Free a sparse cluster map.
7708 */
7709 static kern_return_t
vfs_drt_free_map(struct vfs_drt_clustermap * cmap)7710 vfs_drt_free_map(struct vfs_drt_clustermap *cmap)
7711 {
7712 vm_size_t map_size = 0;
7713
7714 if (cmap->scm_modulus == DRT_HASH_SMALL_MODULUS) {
7715 map_size = DRT_SMALL_ALLOCATION;
7716 } else if (cmap->scm_modulus == DRT_HASH_LARGE_MODULUS) {
7717 map_size = DRT_LARGE_ALLOCATION;
7718 } else if (cmap->scm_modulus == DRT_HASH_XLARGE_MODULUS) {
7719 map_size = DRT_XLARGE_ALLOCATION;
7720 } else {
7721 panic("vfs_drt_free_map: Invalid modulus %d", cmap->scm_modulus);
7722 }
7723
7724 kmem_free(kernel_map, (vm_offset_t)cmap, map_size);
7725 return KERN_SUCCESS;
7726 }
7727
7728
7729 /*
7730 * Find the hashtable slot currently occupied by an entry for the supplied offset.
7731 */
7732 static kern_return_t
vfs_drt_search_index(struct vfs_drt_clustermap * cmap,u_int64_t offset,int * indexp)7733 vfs_drt_search_index(struct vfs_drt_clustermap *cmap, u_int64_t offset, int *indexp)
7734 {
7735 int index;
7736 u_int32_t i;
7737
7738 offset = DRT_ALIGN_ADDRESS(offset);
7739 index = DRT_HASH(cmap, offset);
7740
7741 /* traverse the hashtable */
7742 for (i = 0; i < cmap->scm_modulus; i++) {
7743 /*
7744 * If the slot is vacant, we can stop.
7745 */
7746 if (DRT_HASH_VACANT(cmap, index)) {
7747 break;
7748 }
7749
7750 /*
7751 * If the address matches our offset, we have success.
7752 */
7753 if (DRT_HASH_GET_ADDRESS(cmap, index) == offset) {
7754 *indexp = index;
7755 return KERN_SUCCESS;
7756 }
7757
7758 /*
7759 * Move to the next slot, try again.
7760 */
7761 index = DRT_HASH_NEXT(cmap, index);
7762 }
7763 /*
7764 * It's not there.
7765 */
7766 return KERN_FAILURE;
7767 }
7768
7769 /*
7770 * Find the hashtable slot for the supplied offset. If we haven't allocated
7771 * one yet, allocate one and populate the address field. Note that it will
7772 * not have a nonzero page count and thus will still technically be free, so
7773 * in the case where we are called to clean pages, the slot will remain free.
7774 */
7775 static kern_return_t
vfs_drt_get_index(struct vfs_drt_clustermap ** cmapp,u_int64_t offset,int * indexp,int recursed)7776 vfs_drt_get_index(struct vfs_drt_clustermap **cmapp, u_int64_t offset, int *indexp, int recursed)
7777 {
7778 struct vfs_drt_clustermap *cmap;
7779 kern_return_t kret;
7780 u_int32_t index;
7781 u_int32_t i;
7782
7783 cmap = *cmapp;
7784
7785 /* look for an existing entry */
7786 kret = vfs_drt_search_index(cmap, offset, indexp);
7787 if (kret == KERN_SUCCESS) {
7788 return kret;
7789 }
7790
7791 /* need to allocate an entry */
7792 offset = DRT_ALIGN_ADDRESS(offset);
7793 index = DRT_HASH(cmap, offset);
7794
7795 /* scan from the index forwards looking for a vacant slot */
7796 for (i = 0; i < cmap->scm_modulus; i++) {
7797 /* slot vacant? */
7798 if (DRT_HASH_VACANT(cmap, index) || DRT_HASH_GET_COUNT(cmap, index) == 0) {
7799 cmap->scm_buckets++;
7800 if (index < cmap->scm_lastclean) {
7801 cmap->scm_lastclean = index;
7802 }
7803 DRT_HASH_SET_ADDRESS(cmap, index, offset);
7804 DRT_HASH_SET_COUNT(cmap, index, 0);
7805 DRT_BITVECTOR_CLEAR(cmap, index);
7806 *indexp = index;
7807 vfs_drt_trace(cmap, DRT_DEBUG_INSERT, (int)offset, i, 0, 0);
7808 return KERN_SUCCESS;
7809 }
7810 cmap->scm_iskips += i;
7811 index = DRT_HASH_NEXT(cmap, index);
7812 }
7813
7814 /*
7815 * We haven't found a vacant slot, so the map is full. If we're not
7816 * already recursed, try reallocating/compacting it.
7817 */
7818 if (recursed) {
7819 return KERN_FAILURE;
7820 }
7821 kret = vfs_drt_alloc_map(cmapp);
7822 if (kret == KERN_SUCCESS) {
7823 /* now try to insert again */
7824 kret = vfs_drt_get_index(cmapp, offset, indexp, 1);
7825 }
7826 return kret;
7827 }
7828
7829 /*
7830 * Implementation of set dirty/clean.
7831 *
7832 * In the 'clean' case, not finding a map is OK.
7833 */
7834 static kern_return_t
vfs_drt_do_mark_pages(void ** private,u_int64_t offset,u_int length,u_int * setcountp,int dirty)7835 vfs_drt_do_mark_pages(
7836 void **private,
7837 u_int64_t offset,
7838 u_int length,
7839 u_int *setcountp,
7840 int dirty)
7841 {
7842 struct vfs_drt_clustermap *cmap, **cmapp;
7843 kern_return_t kret;
7844 int i, index, pgoff, pgcount, setcount, ecount;
7845
7846 cmapp = (struct vfs_drt_clustermap **)private;
7847 cmap = *cmapp;
7848
7849 vfs_drt_trace(cmap, DRT_DEBUG_MARK | DBG_FUNC_START, (int)offset, (int)length, dirty, 0);
7850
7851 if (setcountp != NULL) {
7852 *setcountp = 0;
7853 }
7854
7855 /* allocate a cluster map if we don't already have one */
7856 if (cmap == NULL) {
7857 /* no cluster map, nothing to clean */
7858 if (!dirty) {
7859 vfs_drt_trace(cmap, DRT_DEBUG_MARK | DBG_FUNC_END, 1, 0, 0, 0);
7860 return KERN_SUCCESS;
7861 }
7862 kret = vfs_drt_alloc_map(cmapp);
7863 if (kret != KERN_SUCCESS) {
7864 vfs_drt_trace(cmap, DRT_DEBUG_MARK | DBG_FUNC_END, 2, 0, 0, 0);
7865 return kret;
7866 }
7867 }
7868 setcount = 0;
7869
7870 /*
7871 * Iterate over the length of the region.
7872 */
7873 while (length > 0) {
7874 /*
7875 * Get the hashtable index for this offset.
7876 *
7877 * XXX this will add blank entries if we are clearing a range
7878 * that hasn't been dirtied.
7879 */
7880 kret = vfs_drt_get_index(cmapp, offset, &index, 0);
7881 cmap = *cmapp; /* may have changed! */
7882 /* this may be a partial-success return */
7883 if (kret != KERN_SUCCESS) {
7884 if (setcountp != NULL) {
7885 *setcountp = setcount;
7886 }
7887 vfs_drt_trace(cmap, DRT_DEBUG_MARK | DBG_FUNC_END, 3, (int)length, 0, 0);
7888
7889 return kret;
7890 }
7891
7892 /*
7893 * Work out how many pages we're modifying in this
7894 * hashtable entry.
7895 */
7896 pgoff = (int)((offset - DRT_ALIGN_ADDRESS(offset)) / PAGE_SIZE);
7897 pgcount = min((length / PAGE_SIZE), (DRT_BITVECTOR_PAGES - pgoff));
7898
7899 /*
7900 * Iterate over pages, dirty/clearing as we go.
7901 */
7902 ecount = DRT_HASH_GET_COUNT(cmap, index);
7903 for (i = 0; i < pgcount; i++) {
7904 if (dirty) {
7905 if (!DRT_HASH_TEST_BIT(cmap, index, pgoff + i)) {
7906 if (ecount >= DRT_BITVECTOR_PAGES) {
7907 panic("ecount >= DRT_BITVECTOR_PAGES, cmap = %p, index = %d, bit = %d", cmap, index, pgoff + i);
7908 }
7909 DRT_HASH_SET_BIT(cmap, index, pgoff + i);
7910 ecount++;
7911 setcount++;
7912 }
7913 } else {
7914 if (DRT_HASH_TEST_BIT(cmap, index, pgoff + i)) {
7915 if (ecount <= 0) {
7916 panic("ecount <= 0, cmap = %p, index = %d, bit = %d", cmap, index, pgoff + i);
7917 }
7918 assert(ecount > 0);
7919 DRT_HASH_CLEAR_BIT(cmap, index, pgoff + i);
7920 ecount--;
7921 setcount++;
7922 }
7923 }
7924 }
7925 DRT_HASH_SET_COUNT(cmap, index, ecount);
7926
7927 offset += pgcount * PAGE_SIZE;
7928 length -= pgcount * PAGE_SIZE;
7929 }
7930 if (setcountp != NULL) {
7931 *setcountp = setcount;
7932 }
7933
7934 vfs_drt_trace(cmap, DRT_DEBUG_MARK | DBG_FUNC_END, 0, setcount, 0, 0);
7935
7936 return KERN_SUCCESS;
7937 }
7938
7939 /*
7940 * Mark a set of pages as dirty/clean.
7941 *
7942 * This is a public interface.
7943 *
7944 * cmapp
7945 * Pointer to storage suitable for holding a pointer. Note that
7946 * this must either be NULL or a value set by this function.
7947 *
7948 * size
7949 * Current file size in bytes.
7950 *
7951 * offset
7952 * Offset of the first page to be marked as dirty, in bytes. Must be
7953 * page-aligned.
7954 *
7955 * length
7956 * Length of dirty region, in bytes. Must be a multiple of PAGE_SIZE.
7957 *
7958 * setcountp
7959 * Number of pages newly marked dirty by this call (optional).
7960 *
7961 * Returns KERN_SUCCESS if all the pages were successfully marked.
7962 */
7963 static kern_return_t
vfs_drt_mark_pages(void ** cmapp,off_t offset,u_int length,u_int * setcountp)7964 vfs_drt_mark_pages(void **cmapp, off_t offset, u_int length, u_int *setcountp)
7965 {
7966 /* XXX size unused, drop from interface */
7967 return vfs_drt_do_mark_pages(cmapp, offset, length, setcountp, 1);
7968 }
7969
7970 #if 0
7971 static kern_return_t
7972 vfs_drt_unmark_pages(void **cmapp, off_t offset, u_int length)
7973 {
7974 return vfs_drt_do_mark_pages(cmapp, offset, length, NULL, 0);
7975 }
7976 #endif
7977
7978 /*
7979 * Get a cluster of dirty pages.
7980 *
7981 * This is a public interface.
7982 *
7983 * cmapp
7984 * Pointer to storage managed by drt_mark_pages. Note that this must
7985 * be NULL or a value set by drt_mark_pages.
7986 *
7987 * offsetp
7988 * Returns the byte offset into the file of the first page in the cluster.
7989 *
7990 * lengthp
7991 * Returns the length in bytes of the cluster of dirty pages.
7992 *
7993 * Returns success if a cluster was found. If KERN_FAILURE is returned, there
7994 * are no dirty pages meeting the minmum size criteria. Private storage will
7995 * be released if there are no more dirty pages left in the map
7996 *
7997 */
7998 static kern_return_t
vfs_drt_get_cluster(void ** cmapp,off_t * offsetp,u_int * lengthp)7999 vfs_drt_get_cluster(void **cmapp, off_t *offsetp, u_int *lengthp)
8000 {
8001 struct vfs_drt_clustermap *cmap;
8002 u_int64_t offset;
8003 u_int length;
8004 u_int32_t j;
8005 int index, i, fs, ls;
8006
8007 /* sanity */
8008 if ((cmapp == NULL) || (*cmapp == NULL)) {
8009 return KERN_FAILURE;
8010 }
8011 cmap = *cmapp;
8012
8013 /* walk the hashtable */
8014 for (offset = 0, j = 0; j < cmap->scm_modulus; offset += (DRT_BITVECTOR_PAGES * PAGE_SIZE), j++) {
8015 index = DRT_HASH(cmap, offset);
8016
8017 if (DRT_HASH_VACANT(cmap, index) || (DRT_HASH_GET_COUNT(cmap, index) == 0)) {
8018 continue;
8019 }
8020
8021 /* scan the bitfield for a string of bits */
8022 fs = -1;
8023
8024 for (i = 0; i < DRT_BITVECTOR_PAGES; i++) {
8025 if (DRT_HASH_TEST_BIT(cmap, index, i)) {
8026 fs = i;
8027 break;
8028 }
8029 }
8030 if (fs == -1) {
8031 /* didn't find any bits set */
8032 panic("vfs_drt: entry summary count > 0 but no bits set in map, cmap = %p, index = %d, count = %lld",
8033 cmap, index, DRT_HASH_GET_COUNT(cmap, index));
8034 }
8035 for (ls = 0; i < DRT_BITVECTOR_PAGES; i++, ls++) {
8036 if (!DRT_HASH_TEST_BIT(cmap, index, i)) {
8037 break;
8038 }
8039 }
8040
8041 /* compute offset and length, mark pages clean */
8042 offset = DRT_HASH_GET_ADDRESS(cmap, index) + (PAGE_SIZE * fs);
8043 length = ls * PAGE_SIZE;
8044 vfs_drt_do_mark_pages(cmapp, offset, length, NULL, 0);
8045 cmap->scm_lastclean = index;
8046
8047 /* return successful */
8048 *offsetp = (off_t)offset;
8049 *lengthp = length;
8050
8051 vfs_drt_trace(cmap, DRT_DEBUG_RETCLUSTER, (int)offset, (int)length, 0, 0);
8052 return KERN_SUCCESS;
8053 }
8054 /*
8055 * We didn't find anything... hashtable is empty
8056 * emit stats into trace buffer and
8057 * then free it
8058 */
8059 vfs_drt_trace(cmap, DRT_DEBUG_SCMDATA,
8060 cmap->scm_modulus,
8061 cmap->scm_buckets,
8062 cmap->scm_lastclean,
8063 cmap->scm_iskips);
8064
8065 vfs_drt_free_map(cmap);
8066 *cmapp = NULL;
8067
8068 return KERN_FAILURE;
8069 }
8070
8071
8072 static kern_return_t
vfs_drt_control(void ** cmapp,int op_type)8073 vfs_drt_control(void **cmapp, int op_type)
8074 {
8075 struct vfs_drt_clustermap *cmap;
8076
8077 /* sanity */
8078 if ((cmapp == NULL) || (*cmapp == NULL)) {
8079 return KERN_FAILURE;
8080 }
8081 cmap = *cmapp;
8082
8083 switch (op_type) {
8084 case 0:
8085 /* emit stats into trace buffer */
8086 vfs_drt_trace(cmap, DRT_DEBUG_SCMDATA,
8087 cmap->scm_modulus,
8088 cmap->scm_buckets,
8089 cmap->scm_lastclean,
8090 cmap->scm_iskips);
8091
8092 vfs_drt_free_map(cmap);
8093 *cmapp = NULL;
8094 break;
8095
8096 case 1:
8097 cmap->scm_lastclean = 0;
8098 break;
8099 }
8100 return KERN_SUCCESS;
8101 }
8102
8103
8104
8105 /*
8106 * Emit a summary of the state of the clustermap into the trace buffer
8107 * along with some caller-provided data.
8108 */
8109 #if KDEBUG
8110 static void
vfs_drt_trace(__unused struct vfs_drt_clustermap * cmap,int code,int arg1,int arg2,int arg3,int arg4)8111 vfs_drt_trace(__unused struct vfs_drt_clustermap *cmap, int code, int arg1, int arg2, int arg3, int arg4)
8112 {
8113 KERNEL_DEBUG(code, arg1, arg2, arg3, arg4, 0);
8114 }
8115 #else
8116 static void
vfs_drt_trace(__unused struct vfs_drt_clustermap * cmap,__unused int code,__unused int arg1,__unused int arg2,__unused int arg3,__unused int arg4)8117 vfs_drt_trace(__unused struct vfs_drt_clustermap *cmap, __unused int code,
8118 __unused int arg1, __unused int arg2, __unused int arg3,
8119 __unused int arg4)
8120 {
8121 }
8122 #endif
8123
8124 #if 0
8125 /*
8126 * Perform basic sanity check on the hash entry summary count
8127 * vs. the actual bits set in the entry.
8128 */
8129 static void
8130 vfs_drt_sanity(struct vfs_drt_clustermap *cmap)
8131 {
8132 int index, i;
8133 int bits_on;
8134
8135 for (index = 0; index < cmap->scm_modulus; index++) {
8136 if (DRT_HASH_VACANT(cmap, index)) {
8137 continue;
8138 }
8139
8140 for (bits_on = 0, i = 0; i < DRT_BITVECTOR_PAGES; i++) {
8141 if (DRT_HASH_TEST_BIT(cmap, index, i)) {
8142 bits_on++;
8143 }
8144 }
8145 if (bits_on != DRT_HASH_GET_COUNT(cmap, index)) {
8146 panic("bits_on = %d, index = %d", bits_on, index);
8147 }
8148 }
8149 }
8150 #endif
8151
8152 /*
8153 * Internal interface only.
8154 */
8155 static kern_return_t
vfs_get_scmap_push_behavior_internal(void ** cmapp,int * push_flag)8156 vfs_get_scmap_push_behavior_internal(void **cmapp, int *push_flag)
8157 {
8158 struct vfs_drt_clustermap *cmap;
8159
8160 /* sanity */
8161 if ((cmapp == NULL) || (*cmapp == NULL) || (push_flag == NULL)) {
8162 return KERN_FAILURE;
8163 }
8164 cmap = *cmapp;
8165
8166 if (cmap->scm_modulus == DRT_HASH_XLARGE_MODULUS) {
8167 /*
8168 * If we have a full xlarge sparse cluster,
8169 * we push it out all at once so the cluster
8170 * map can be available to absorb more I/Os.
8171 * This is done on large memory configs so
8172 * the small I/Os don't interfere with the
8173 * pro workloads.
8174 */
8175 *push_flag = PUSH_ALL;
8176 }
8177 return KERN_SUCCESS;
8178 }
8179