xref: /freebsd/sys/contrib/openzfs/module/zfs/dmu_zfetch.c (revision 22649d4dba730d46244fd2dff4fd174903c8379f)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * This file and its contents are supplied under the terms of the
4  * Common Development and Distribution License ("CDDL"), version 1.0.
5  * You may only use this file in accordance with the terms of version
6  * 1.0 of the CDDL.
7  *
8  * A full copy of the text of the CDDL should have accompanied this
9  * source.  A copy of the CDDL is also available via the Internet at
10  * https://opensource.org/license/CDDL-1.0.
11  */
12 /*
13  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
14  * Use is subject to license terms.
15  */
16 
17 /*
18  * Copyright (c) 2013, 2017 by Delphix. All rights reserved.
19  */
20 
21 #include <sys/zfs_context.h>
22 #include <sys/arc_impl.h>
23 #include <sys/dnode.h>
24 #include <sys/dmu_objset.h>
25 #include <sys/dmu_zfetch.h>
26 #include <sys/dmu.h>
27 #include <sys/dbuf.h>
28 #include <sys/kstat.h>
29 #include <sys/wmsum.h>
30 
31 /*
32  * This tunable disables predictive prefetch.  Note that it leaves "prescient"
33  * prefetch (e.g. prefetch for zfs send) intact.  Unlike predictive prefetch,
34  * prescient prefetch never issues i/os that end up not being needed,
35  * so it can't hurt performance.
36  */
37 
38 static int zfs_prefetch_disable = B_FALSE;
39 
40 /* max # of streams per zfetch */
41 static unsigned int	zfetch_max_streams = 8;
42 /* min time before stream reclaim */
43 static unsigned int	zfetch_min_sec_reap = 1;
44 /* max time before stream delete */
45 static unsigned int	zfetch_max_sec_reap = 2;
46 #ifdef _ILP32
47 /* min bytes to prefetch per stream (default 2MB) */
48 static unsigned int	zfetch_min_distance = 2 * 1024 * 1024;
49 /* max bytes to prefetch per stream (default 8MB) */
50 unsigned int	zfetch_max_distance = 8 * 1024 * 1024;
51 #else
52 /* min bytes to prefetch per stream (default 4MB) */
53 static unsigned int	zfetch_min_distance = 4 * 1024 * 1024;
54 /* max bytes to prefetch per stream (default 64MB) */
55 unsigned int	zfetch_max_distance = 64 * 1024 * 1024;
56 #endif
57 /* max bytes to prefetch indirects for per stream (default 128MB) */
58 unsigned int	zfetch_max_idistance = 128 * 1024 * 1024;
59 /* max request reorder distance within a stream (default 16MB) */
60 unsigned int	zfetch_max_reorder = 16 * 1024 * 1024;
61 /* Max log2 fraction of holes in a stream */
62 unsigned int	zfetch_hole_shift = 2;
63 
64 typedef struct zfetch_stats {
65 	kstat_named_t zfetchstat_hits;
66 	kstat_named_t zfetchstat_future;
67 	kstat_named_t zfetchstat_stride;
68 	kstat_named_t zfetchstat_past;
69 	kstat_named_t zfetchstat_misses;
70 	kstat_named_t zfetchstat_max_streams;
71 	kstat_named_t zfetchstat_io_issued;
72 	kstat_named_t zfetchstat_io_active;
73 } zfetch_stats_t;
74 
75 static zfetch_stats_t zfetch_stats = {
76 	{ "hits",			KSTAT_DATA_UINT64 },
77 	{ "future",			KSTAT_DATA_UINT64 },
78 	{ "stride",			KSTAT_DATA_UINT64 },
79 	{ "past",			KSTAT_DATA_UINT64 },
80 	{ "misses",			KSTAT_DATA_UINT64 },
81 	{ "max_streams",		KSTAT_DATA_UINT64 },
82 	{ "io_issued",			KSTAT_DATA_UINT64 },
83 	{ "io_active",			KSTAT_DATA_UINT64 },
84 };
85 
86 struct {
87 	wmsum_t zfetchstat_hits;
88 	wmsum_t zfetchstat_future;
89 	wmsum_t zfetchstat_stride;
90 	wmsum_t zfetchstat_past;
91 	wmsum_t zfetchstat_misses;
92 	wmsum_t zfetchstat_max_streams;
93 	wmsum_t zfetchstat_io_issued;
94 	aggsum_t zfetchstat_io_active;
95 } zfetch_sums;
96 
97 #define	ZFETCHSTAT_BUMP(stat)					\
98 	wmsum_add(&zfetch_sums.stat, 1)
99 #define	ZFETCHSTAT_ADD(stat, val)				\
100 	wmsum_add(&zfetch_sums.stat, val)
101 
102 
103 static kstat_t		*zfetch_ksp;
104 
105 static int
zfetch_kstats_update(kstat_t * ksp,int rw)106 zfetch_kstats_update(kstat_t *ksp, int rw)
107 {
108 	zfetch_stats_t *zs = ksp->ks_data;
109 
110 	if (rw == KSTAT_WRITE)
111 		return (EACCES);
112 	zs->zfetchstat_hits.value.ui64 =
113 	    wmsum_value(&zfetch_sums.zfetchstat_hits);
114 	zs->zfetchstat_future.value.ui64 =
115 	    wmsum_value(&zfetch_sums.zfetchstat_future);
116 	zs->zfetchstat_stride.value.ui64 =
117 	    wmsum_value(&zfetch_sums.zfetchstat_stride);
118 	zs->zfetchstat_past.value.ui64 =
119 	    wmsum_value(&zfetch_sums.zfetchstat_past);
120 	zs->zfetchstat_misses.value.ui64 =
121 	    wmsum_value(&zfetch_sums.zfetchstat_misses);
122 	zs->zfetchstat_max_streams.value.ui64 =
123 	    wmsum_value(&zfetch_sums.zfetchstat_max_streams);
124 	zs->zfetchstat_io_issued.value.ui64 =
125 	    wmsum_value(&zfetch_sums.zfetchstat_io_issued);
126 	zs->zfetchstat_io_active.value.ui64 =
127 	    aggsum_value(&zfetch_sums.zfetchstat_io_active);
128 	return (0);
129 }
130 
131 void
zfetch_init(void)132 zfetch_init(void)
133 {
134 	wmsum_init(&zfetch_sums.zfetchstat_hits, 0);
135 	wmsum_init(&zfetch_sums.zfetchstat_future, 0);
136 	wmsum_init(&zfetch_sums.zfetchstat_stride, 0);
137 	wmsum_init(&zfetch_sums.zfetchstat_past, 0);
138 	wmsum_init(&zfetch_sums.zfetchstat_misses, 0);
139 	wmsum_init(&zfetch_sums.zfetchstat_max_streams, 0);
140 	wmsum_init(&zfetch_sums.zfetchstat_io_issued, 0);
141 	aggsum_init(&zfetch_sums.zfetchstat_io_active, 0);
142 
143 	zfetch_ksp = kstat_create("zfs", 0, "zfetchstats", "misc",
144 	    KSTAT_TYPE_NAMED, sizeof (zfetch_stats) / sizeof (kstat_named_t),
145 	    KSTAT_FLAG_VIRTUAL);
146 
147 	if (zfetch_ksp != NULL) {
148 		zfetch_ksp->ks_data = &zfetch_stats;
149 		zfetch_ksp->ks_update = zfetch_kstats_update;
150 		kstat_install(zfetch_ksp);
151 	}
152 }
153 
154 void
zfetch_fini(void)155 zfetch_fini(void)
156 {
157 	if (zfetch_ksp != NULL) {
158 		kstat_delete(zfetch_ksp);
159 		zfetch_ksp = NULL;
160 	}
161 
162 	wmsum_fini(&zfetch_sums.zfetchstat_hits);
163 	wmsum_fini(&zfetch_sums.zfetchstat_future);
164 	wmsum_fini(&zfetch_sums.zfetchstat_stride);
165 	wmsum_fini(&zfetch_sums.zfetchstat_past);
166 	wmsum_fini(&zfetch_sums.zfetchstat_misses);
167 	wmsum_fini(&zfetch_sums.zfetchstat_max_streams);
168 	wmsum_fini(&zfetch_sums.zfetchstat_io_issued);
169 	ASSERT0(aggsum_value(&zfetch_sums.zfetchstat_io_active));
170 	aggsum_fini(&zfetch_sums.zfetchstat_io_active);
171 }
172 
173 /*
174  * This takes a pointer to a zfetch structure and a dnode.  It performs the
175  * necessary setup for the zfetch structure, grokking data from the
176  * associated dnode.
177  */
178 void
dmu_zfetch_init(zfetch_t * zf,dnode_t * dno)179 dmu_zfetch_init(zfetch_t *zf, dnode_t *dno)
180 {
181 	if (zf == NULL)
182 		return;
183 	zf->zf_dnode = dno;
184 	zf->zf_numstreams = 0;
185 
186 	list_create(&zf->zf_stream, sizeof (zstream_t),
187 	    offsetof(zstream_t, zs_node));
188 
189 	mutex_init(&zf->zf_lock, NULL, MUTEX_DEFAULT, NULL);
190 }
191 
192 static void
dmu_zfetch_stream_fini(zstream_t * zs)193 dmu_zfetch_stream_fini(zstream_t *zs)
194 {
195 	ASSERT(!list_link_active(&zs->zs_node));
196 	zfs_refcount_destroy(&zs->zs_callers);
197 	zfs_refcount_destroy(&zs->zs_refs);
198 	kmem_free(zs, sizeof (*zs));
199 }
200 
201 static void
dmu_zfetch_stream_remove(zfetch_t * zf,zstream_t * zs)202 dmu_zfetch_stream_remove(zfetch_t *zf, zstream_t *zs)
203 {
204 	ASSERT(MUTEX_HELD(&zf->zf_lock));
205 	list_remove(&zf->zf_stream, zs);
206 	zf->zf_numstreams--;
207 	membar_producer();
208 	if (zfs_refcount_remove(&zs->zs_refs, NULL) == 0)
209 		dmu_zfetch_stream_fini(zs);
210 }
211 
212 /*
213  * Clean-up state associated with a zfetch structure (e.g. destroy the
214  * streams).  This doesn't free the zfetch_t itself, that's left to the caller.
215  */
216 void
dmu_zfetch_fini(zfetch_t * zf)217 dmu_zfetch_fini(zfetch_t *zf)
218 {
219 	zstream_t *zs;
220 
221 	mutex_enter(&zf->zf_lock);
222 	while ((zs = list_head(&zf->zf_stream)) != NULL)
223 		dmu_zfetch_stream_remove(zf, zs);
224 	mutex_exit(&zf->zf_lock);
225 	list_destroy(&zf->zf_stream);
226 	mutex_destroy(&zf->zf_lock);
227 
228 	zf->zf_dnode = NULL;
229 }
230 
231 /*
232  * If there aren't too many active streams already, create one more.
233  * In process delete/reuse all streams without hits for zfetch_max_sec_reap.
234  * If needed, reuse oldest stream without hits for zfetch_min_sec_reap or ever.
235  * The "blkid" argument is the next block that we expect this stream to access.
236  */
237 static zstream_t *
dmu_zfetch_stream_create(zfetch_t * zf,uint64_t blkid)238 dmu_zfetch_stream_create(zfetch_t *zf, uint64_t blkid)
239 {
240 	zstream_t *zs, *zs_next, *zs_old = NULL;
241 	uint_t now = gethrestime_sec(), t;
242 
243 	ASSERT(MUTEX_HELD(&zf->zf_lock));
244 
245 	/*
246 	 * Delete too old streams, reusing the first found one.
247 	 */
248 	t = now - zfetch_max_sec_reap;
249 	for (zs = list_head(&zf->zf_stream); zs != NULL; zs = zs_next) {
250 		zs_next = list_next(&zf->zf_stream, zs);
251 		/*
252 		 * Skip if still active.  1 -- zf_stream reference.
253 		 */
254 		if ((int)(zs->zs_atime - t) >= 0)
255 			continue;
256 		if (zfs_refcount_count(&zs->zs_refs) != 1)
257 			continue;
258 		if (zs_old)
259 			dmu_zfetch_stream_remove(zf, zs);
260 		else
261 			zs_old = zs;
262 	}
263 	if (zs_old) {
264 		zs = zs_old;
265 		list_remove(&zf->zf_stream, zs);
266 		goto reuse;
267 	}
268 
269 	/*
270 	 * The maximum number of streams is normally zfetch_max_streams,
271 	 * but for small files we lower it such that it's at least possible
272 	 * for all the streams to be non-overlapping.
273 	 */
274 	uint32_t max_streams = MAX(1, MIN(zfetch_max_streams,
275 	    (zf->zf_dnode->dn_maxblkid << zf->zf_dnode->dn_datablkshift) /
276 	    zfetch_max_distance));
277 	if (zf->zf_numstreams >= max_streams) {
278 		t = now - zfetch_min_sec_reap;
279 		for (zs = list_head(&zf->zf_stream); zs != NULL;
280 		    zs = list_next(&zf->zf_stream, zs)) {
281 			if ((int)(zs->zs_atime - t) >= 0)
282 				continue;
283 			if (zfs_refcount_count(&zs->zs_refs) != 1)
284 				continue;
285 			if (zs_old == NULL ||
286 			    (int)(zs_old->zs_atime - zs->zs_atime) >= 0)
287 				zs_old = zs;
288 		}
289 		if (zs_old) {
290 			zs = zs_old;
291 			list_remove(&zf->zf_stream, zs);
292 			goto reuse;
293 		}
294 		ZFETCHSTAT_BUMP(zfetchstat_max_streams);
295 		return (NULL);
296 	}
297 
298 	zs = kmem_zalloc(sizeof (*zs), KM_SLEEP);
299 	zfs_refcount_create(&zs->zs_callers);
300 	zfs_refcount_create(&zs->zs_refs);
301 	/* One reference for zf_stream. */
302 	zfs_refcount_add(&zs->zs_refs, NULL);
303 	zf->zf_numstreams++;
304 
305 reuse:
306 	list_insert_head(&zf->zf_stream, zs);
307 	zs->zs_blkid = blkid;
308 	/* Allow immediate stream reuse until first hit. */
309 	zs->zs_atime = now - zfetch_min_sec_reap;
310 	memset(zs->zs_ranges, 0, sizeof (zs->zs_ranges));
311 	zs->zs_pf_dist = 0;
312 	zs->zs_ipf_dist = 0;
313 	zs->zs_pf_start = blkid;
314 	zs->zs_pf_end = blkid;
315 	zs->zs_ipf_start = blkid;
316 	zs->zs_ipf_end = blkid;
317 	zs->zs_missed = B_FALSE;
318 	zs->zs_more = B_FALSE;
319 	return (zs);
320 }
321 
322 static void
dmu_zfetch_done(void * arg,uint64_t level,uint64_t blkid,boolean_t io_issued)323 dmu_zfetch_done(void *arg, uint64_t level, uint64_t blkid, boolean_t io_issued)
324 {
325 	zstream_t *zs = arg;
326 
327 	if (io_issued && level == 0 && blkid < zs->zs_blkid)
328 		zs->zs_more = B_TRUE;
329 	if (zfs_refcount_remove(&zs->zs_refs, NULL) == 0)
330 		dmu_zfetch_stream_fini(zs);
331 	aggsum_add(&zfetch_sums.zfetchstat_io_active, -1);
332 }
333 
334 /*
335  * Process stream hit access for nblks blocks starting at zs_blkid.  Return
336  * number of blocks to proceed for after aggregation with future ranges.
337  */
338 static uint64_t
dmu_zfetch_hit(zstream_t * zs,uint64_t nblks)339 dmu_zfetch_hit(zstream_t *zs, uint64_t nblks)
340 {
341 	uint_t i, j;
342 
343 	/* Optimize sequential accesses (no future ranges). */
344 	if (zs->zs_ranges[0].start == 0)
345 		goto done;
346 
347 	/* Look for intersections with further ranges. */
348 	for (i = 0; i < ZFETCH_RANGES; i++) {
349 		zsrange_t *r = &zs->zs_ranges[i];
350 		if (r->start == 0 || r->start > nblks)
351 			break;
352 		if (r->end >= nblks) {
353 			nblks = r->end;
354 			i++;
355 			break;
356 		}
357 	}
358 
359 	/* Delete all found intersecting ranges, updates remaining. */
360 	for (j = 0; i < ZFETCH_RANGES; i++, j++) {
361 		if (zs->zs_ranges[i].start == 0)
362 			break;
363 		ASSERT3U(zs->zs_ranges[i].start, >, nblks);
364 		ASSERT3U(zs->zs_ranges[i].end, >, nblks);
365 		zs->zs_ranges[j].start = zs->zs_ranges[i].start - nblks;
366 		zs->zs_ranges[j].end = zs->zs_ranges[i].end - nblks;
367 	}
368 	if (j < ZFETCH_RANGES) {
369 		zs->zs_ranges[j].start = 0;
370 		zs->zs_ranges[j].end = 0;
371 	}
372 
373 done:
374 	zs->zs_blkid += nblks;
375 	return (nblks);
376 }
377 
378 /*
379  * Process future stream access for nblks blocks starting at blkid.  Return
380  * number of blocks to proceed for if future ranges reach fill threshold.
381  */
382 static uint64_t
dmu_zfetch_future(zstream_t * zs,uint64_t blkid,uint64_t nblks)383 dmu_zfetch_future(zstream_t *zs, uint64_t blkid, uint64_t nblks)
384 {
385 	ASSERT3U(blkid, >, zs->zs_blkid);
386 	blkid -= zs->zs_blkid;
387 	ASSERT3U(blkid + nblks, <=, UINT16_MAX);
388 
389 	/* Search for first and last intersection or insert point. */
390 	uint_t f = ZFETCH_RANGES, l = 0, i;
391 	for (i = 0; i < ZFETCH_RANGES; i++) {
392 		zsrange_t *r = &zs->zs_ranges[i];
393 		if (r->start == 0 || r->start > blkid + nblks)
394 			break;
395 		if (r->end < blkid)
396 			continue;
397 		if (f > i)
398 			f = i;
399 		if (l < i)
400 			l = i;
401 	}
402 	if (f <= l) {
403 		/* Got some intersecting range, expand it if needed. */
404 		if (zs->zs_ranges[f].start > blkid)
405 			zs->zs_ranges[f].start = blkid;
406 		zs->zs_ranges[f].end = MAX(zs->zs_ranges[l].end, blkid + nblks);
407 		if (f < l) {
408 			/* Got more than one intersection, remove others. */
409 			for (f++, l++; l < ZFETCH_RANGES; f++, l++) {
410 				zs->zs_ranges[f].start = zs->zs_ranges[l].start;
411 				zs->zs_ranges[f].end = zs->zs_ranges[l].end;
412 			}
413 			zs->zs_ranges[f].start = 0;
414 			zs->zs_ranges[f].end = 0;
415 		}
416 	} else if (i < ZFETCH_RANGES) {
417 		/* Got no intersecting ranges, insert new one. */
418 		for (l = ZFETCH_RANGES - 1; l > i; l--) {
419 			zs->zs_ranges[l].start = zs->zs_ranges[l - 1].start;
420 			zs->zs_ranges[l].end = zs->zs_ranges[l - 1].end;
421 		}
422 		zs->zs_ranges[i].start = blkid;
423 		zs->zs_ranges[i].end = blkid + nblks;
424 	} else {
425 		/* No space left to insert.  Drop the range. */
426 		return (0);
427 	}
428 
429 	/* Check if with the new access addition we reached fill threshold. */
430 	if (zfetch_hole_shift >= 16)
431 		return (0);
432 	uint_t hole = 0;
433 	for (i = f = l = 0; i < ZFETCH_RANGES; i++) {
434 		zsrange_t *r = &zs->zs_ranges[i];
435 		if (r->start == 0)
436 			break;
437 		hole += r->start - f;
438 		f = r->end;
439 		if (hole <= r->end >> zfetch_hole_shift)
440 			l = r->end;
441 	}
442 	if (l > 0)
443 		return (dmu_zfetch_hit(zs, l));
444 
445 	return (0);
446 }
447 
448 /*
449  * Prime a zfetch stream at blkid, so that the first demand access triggered
450  * enough prefetch without ramp-up to sequentially read up to end_blkid.
451  */
452 boolean_t
dmu_zfetch_prime(zfetch_t * zf,uint64_t blkid,uint64_t end_blkid)453 dmu_zfetch_prime(zfetch_t *zf, uint64_t blkid, uint64_t end_blkid)
454 {
455 	zstream_t *zs;
456 	dnode_t *dn = zf->zf_dnode;
457 	spa_t *spa = dn->dn_objset->os_spa;
458 
459 	ASSERT(RW_LOCK_HELD(&dn->dn_struct_rwlock));
460 	if (zfs_prefetch_disable ||
461 	    dn->dn_objset->os_prefetch == ZFS_PREFETCH_NONE)
462 		return (B_FALSE);
463 
464 	if (!spa_indirect_vdevs_loaded(spa))
465 		return (B_FALSE);
466 
467 	uint64_t maxblkid = dn->dn_maxblkid;
468 	unsigned int dbs = dn->dn_datablkshift;
469 
470 	if (blkid >= maxblkid)
471 		return (B_FALSE);
472 	if (end_blkid > maxblkid + 1)
473 		end_blkid = maxblkid + 1;
474 
475 	mutex_enter(&zf->zf_lock);
476 
477 	/* Skip if a nearby stream already covers this range. */
478 	uint_t max_near = zfetch_max_reorder >> dbs;
479 	for (zs = list_head(&zf->zf_stream); zs != NULL;
480 	    zs = list_next(&zf->zf_stream, zs)) {
481 		uint64_t diff = (blkid >= zs->zs_blkid) ?
482 		    (blkid - zs->zs_blkid) : (zs->zs_blkid - blkid);
483 		if (diff <= max_near) {
484 			mutex_exit(&zf->zf_lock);
485 			return (B_FALSE);
486 		}
487 	}
488 
489 	/* Skip if at stream limit and none are reclaimable. */
490 	zs = dmu_zfetch_stream_create(zf, blkid);
491 	if (zs == NULL) {
492 		mutex_exit(&zf->zf_lock);
493 		return (B_FALSE);
494 	}
495 	ASSERT3U(zs->zs_blkid, ==, blkid);
496 
497 	/* dmu_zfetch_prepare() will double the distances, so take a half. */
498 	unsigned int nbytes = ((end_blkid - blkid) << dbs) / 2;
499 	zs->zs_pf_dist = MIN(nbytes, zfetch_min_distance);
500 	zs->zs_ipf_dist = MIN(nbytes, zfetch_max_idistance);
501 
502 	mutex_exit(&zf->zf_lock);
503 	return (B_TRUE);
504 }
505 
506 /*
507  * This is the predictive prefetch entry point.  dmu_zfetch_prepare()
508  * associates dnode access specified with blkid and nblks arguments with
509  * prefetch stream, predicts further accesses based on that stats and returns
510  * the stream pointer on success.  That pointer must later be passed to
511  * dmu_zfetch_run() to initiate the speculative prefetch for the stream and
512  * release it.  dmu_zfetch() is a wrapper for simple cases when window between
513  * prediction and prefetch initiation is not needed.
514  * fetch_data argument specifies whether actual data blocks should be fetched:
515  *   FALSE -- prefetch only indirect blocks for predicted data blocks;
516  *   TRUE -- prefetch predicted data blocks plus following indirect blocks.
517  */
518 zstream_t *
dmu_zfetch_prepare(zfetch_t * zf,uint64_t blkid,uint64_t nblks,boolean_t fetch_data,boolean_t have_lock)519 dmu_zfetch_prepare(zfetch_t *zf, uint64_t blkid, uint64_t nblks,
520     boolean_t fetch_data, boolean_t have_lock)
521 {
522 	zstream_t *zs;
523 	spa_t *spa = zf->zf_dnode->dn_objset->os_spa;
524 	zfs_prefetch_type_t os_prefetch = zf->zf_dnode->dn_objset->os_prefetch;
525 	int64_t ipf_start, ipf_end;
526 
527 	if (zfs_prefetch_disable || os_prefetch == ZFS_PREFETCH_NONE)
528 		return (NULL);
529 
530 	if (os_prefetch == ZFS_PREFETCH_METADATA)
531 		fetch_data = B_FALSE;
532 
533 	/*
534 	 * If we haven't yet loaded the indirect vdevs' mappings, we
535 	 * can only read from blocks that we carefully ensure are on
536 	 * concrete vdevs (or previously-loaded indirect vdevs).  So we
537 	 * can't allow the predictive prefetcher to attempt reads of other
538 	 * blocks (e.g. of the MOS's dnode object).
539 	 */
540 	if (!spa_indirect_vdevs_loaded(spa))
541 		return (NULL);
542 
543 	/*
544 	 * As a fast path for small (single-block) files, ignore access
545 	 * to the first block, unless some streams exist, since a prime
546 	 * may be waiting.
547 	 */
548 	if (!have_lock && blkid == 0 && zf->zf_numstreams == 0)
549 		return (NULL);
550 
551 	if (!have_lock)
552 		rw_enter(&zf->zf_dnode->dn_struct_rwlock, RW_READER);
553 
554 	/*
555 	 * A fast path for small files for which no prefetch will happen,
556 	 * unless streams exist, since a prime may be waiting.
557 	 */
558 	uint64_t maxblkid = zf->zf_dnode->dn_maxblkid;
559 	if (maxblkid < 2 && (maxblkid == 0 || zf->zf_numstreams == 0)) {
560 		if (!have_lock)
561 			rw_exit(&zf->zf_dnode->dn_struct_rwlock);
562 		return (NULL);
563 	}
564 	mutex_enter(&zf->zf_lock);
565 
566 	/*
567 	 * Find perfect prefetch stream.  Depending on whether the accesses
568 	 * are block-aligned, first block of the new access may either follow
569 	 * the last block of the previous access, or be equal to it.
570 	 */
571 	unsigned int dbs = zf->zf_dnode->dn_datablkshift;
572 	uint64_t end_blkid = blkid + nblks;
573 	for (zs = list_head(&zf->zf_stream); zs != NULL;
574 	    zs = list_next(&zf->zf_stream, zs)) {
575 		if (blkid == zs->zs_blkid) {
576 			goto hit;
577 		} else if (blkid + 1 == zs->zs_blkid) {
578 			blkid++;
579 			nblks--;
580 			goto hit;
581 		}
582 	}
583 
584 	/*
585 	 * Find close enough prefetch stream.  Access crossing stream position
586 	 * is a hit in its new part.  Access ahead of stream position considered
587 	 * a hit for metadata prefetch, since we do not care about fill percent,
588 	 * or stored for future otherwise.  Access behind stream position is
589 	 * silently ignored, since we already skipped it reaching fill percent.
590 	 */
591 	uint_t max_reorder = MIN((zfetch_max_reorder >> dbs) + 1, UINT16_MAX);
592 	uint_t t = gethrestime_sec() - zfetch_max_sec_reap;
593 	for (zs = list_head(&zf->zf_stream); zs != NULL;
594 	    zs = list_next(&zf->zf_stream, zs)) {
595 		if (blkid > zs->zs_blkid) {
596 			if (end_blkid <= zs->zs_blkid + max_reorder) {
597 				if (!fetch_data) {
598 					nblks = dmu_zfetch_hit(zs,
599 					    end_blkid - zs->zs_blkid);
600 					ZFETCHSTAT_BUMP(zfetchstat_stride);
601 					goto future;
602 				}
603 				nblks = dmu_zfetch_future(zs, blkid, nblks);
604 				if (nblks > 0)
605 					ZFETCHSTAT_BUMP(zfetchstat_stride);
606 				else
607 					ZFETCHSTAT_BUMP(zfetchstat_future);
608 				goto future;
609 			}
610 		} else if (end_blkid >= zs->zs_blkid) {
611 			nblks -= zs->zs_blkid - blkid;
612 			blkid += zs->zs_blkid - blkid;
613 			goto hit;
614 		} else if (end_blkid + max_reorder > zs->zs_blkid &&
615 		    (int)(zs->zs_atime - t) >= 0) {
616 			ZFETCHSTAT_BUMP(zfetchstat_past);
617 			zs->zs_atime = gethrestime_sec();
618 			goto out;
619 		}
620 	}
621 
622 	/*
623 	 * This access is not part of any existing stream.  Create a new
624 	 * stream for it unless we are at the end of file.
625 	 */
626 	ASSERT0P(zs);
627 	if (end_blkid < maxblkid)
628 		(void) dmu_zfetch_stream_create(zf, end_blkid);
629 	mutex_exit(&zf->zf_lock);
630 	ZFETCHSTAT_BUMP(zfetchstat_misses);
631 	ipf_start = 0;
632 	goto prescient;
633 
634 hit:
635 	nblks = dmu_zfetch_hit(zs, nblks);
636 	ZFETCHSTAT_BUMP(zfetchstat_hits);
637 
638 future:
639 	zs->zs_atime = gethrestime_sec();
640 
641 	/* Exit if we already prefetched for this position before. */
642 	if (nblks == 0 && zs->zs_ipf_end > end_blkid)
643 		goto out;
644 
645 	/* If the file is ending, remove the stream. */
646 	end_blkid = zs->zs_blkid;
647 	if (end_blkid >= maxblkid) {
648 		dmu_zfetch_stream_remove(zf, zs);
649 out:
650 		mutex_exit(&zf->zf_lock);
651 		if (!have_lock)
652 			rw_exit(&zf->zf_dnode->dn_struct_rwlock);
653 		return (NULL);
654 	}
655 
656 	/*
657 	 * This access was to a block that we issued a prefetch for on
658 	 * behalf of this stream.  Calculate further prefetch distances.
659 	 *
660 	 * Start prefetch from the demand access size (nblks).  Double the
661 	 * distance every access up to zfetch_min_distance.  After that only
662 	 * if needed increase the distance by 1/8 up to zfetch_max_distance.
663 	 *
664 	 * Don't double the distance beyond single block if we have more
665 	 * than ~6% of ARC held by active prefetches.  It should help with
666 	 * getting out of RAM on some badly mispredicted read patterns.
667 	 */
668 	unsigned int nbytes = nblks << dbs;
669 	unsigned int pf_nblks;
670 	if (fetch_data) {
671 		if (unlikely(zs->zs_pf_dist < nbytes))
672 			zs->zs_pf_dist = nbytes;
673 		else if (zs->zs_pf_dist < zfetch_min_distance &&
674 		    (zs->zs_pf_dist < (1 << dbs) ||
675 		    aggsum_compare(&zfetch_sums.zfetchstat_io_active,
676 		    arc_c_max >> (4 + dbs)) < 0))
677 			zs->zs_pf_dist *= 2;
678 		else if (zs->zs_more)
679 			zs->zs_pf_dist += zs->zs_pf_dist / 8;
680 		zs->zs_more = B_FALSE;
681 		if (zs->zs_pf_dist > zfetch_max_distance)
682 			zs->zs_pf_dist = zfetch_max_distance;
683 		pf_nblks = zs->zs_pf_dist >> dbs;
684 	} else {
685 		pf_nblks = 0;
686 	}
687 	if (zs->zs_pf_start < end_blkid)
688 		zs->zs_pf_start = end_blkid;
689 	if (zs->zs_pf_end < end_blkid + pf_nblks)
690 		zs->zs_pf_end = end_blkid + pf_nblks;
691 
692 	/*
693 	 * Do the same for indirects, starting where we will stop reading
694 	 * data blocks (and the indirects that point to them).
695 	 */
696 	nbytes = MAX(nbytes, (1 << dbs));
697 	if (unlikely(zs->zs_ipf_dist < nbytes))
698 		zs->zs_ipf_dist = nbytes;
699 	else
700 		zs->zs_ipf_dist *= 2;
701 	if (zs->zs_ipf_dist > zfetch_max_idistance)
702 		zs->zs_ipf_dist = zfetch_max_idistance;
703 	pf_nblks = zs->zs_ipf_dist >> dbs;
704 	if (zs->zs_ipf_start < zs->zs_pf_end)
705 		zs->zs_ipf_start = zs->zs_pf_end;
706 	ipf_start = zs->zs_ipf_end;
707 	if (zs->zs_ipf_end < zs->zs_pf_end + pf_nblks)
708 		zs->zs_ipf_end = zs->zs_pf_end + pf_nblks;
709 
710 	zfs_refcount_add(&zs->zs_refs, NULL);
711 	/* Count concurrent callers. */
712 	zfs_refcount_add(&zs->zs_callers, NULL);
713 	mutex_exit(&zf->zf_lock);
714 
715 prescient:
716 	/*
717 	 * Prefetch the following indirect blocks for this access to reduce
718 	 * dbuf_hold() sync read delays in dmu_buf_hold_array_by_dnode().
719 	 * This covers the gap during the first couple accesses when we can
720 	 * not predict the future yet, but know what is needed right now.
721 	 * This should be very rare for reads/writes to need more than one
722 	 * indirect, but more useful for cloning due to much bigger accesses.
723 	 */
724 	ipf_start = MAX(ipf_start, blkid + 1);
725 	int epbs = zf->zf_dnode->dn_indblkshift - SPA_BLKPTRSHIFT;
726 	ipf_start = P2ROUNDUP(ipf_start, 1 << epbs) >> epbs;
727 	ipf_end = P2ROUNDUP(end_blkid, 1 << epbs) >> epbs;
728 
729 	int issued = 0;
730 	for (int64_t iblk = ipf_start; iblk < ipf_end; iblk++) {
731 		issued += dbuf_prefetch(zf->zf_dnode, 1, iblk,
732 		    ZIO_PRIORITY_SYNC_READ, ARC_FLAG_PRESCIENT_PREFETCH);
733 	}
734 
735 	if (!have_lock)
736 		rw_exit(&zf->zf_dnode->dn_struct_rwlock);
737 	if (issued)
738 		ZFETCHSTAT_ADD(zfetchstat_io_issued, issued);
739 	return (zs);
740 }
741 
742 void
dmu_zfetch_run(zfetch_t * zf,zstream_t * zs,boolean_t missed,boolean_t have_lock,boolean_t uncached)743 dmu_zfetch_run(zfetch_t *zf, zstream_t *zs, boolean_t missed,
744     boolean_t have_lock, boolean_t uncached)
745 {
746 	int64_t pf_start, pf_end, ipf_start, ipf_end;
747 	int epbs, issued;
748 
749 	if (missed)
750 		zs->zs_missed = missed;
751 
752 	/*
753 	 * Postpone the prefetch if there are more concurrent callers.
754 	 * It happens when multiple requests are waiting for the same
755 	 * indirect block.  The last one will run the prefetch for all.
756 	 */
757 	if (zfs_refcount_remove(&zs->zs_callers, NULL) != 0) {
758 		/* Drop reference taken in dmu_zfetch_prepare(). */
759 		if (zfs_refcount_remove(&zs->zs_refs, NULL) == 0)
760 			dmu_zfetch_stream_fini(zs);
761 		return;
762 	}
763 
764 	mutex_enter(&zf->zf_lock);
765 	if (zs->zs_missed) {
766 		pf_start = zs->zs_pf_start;
767 		pf_end = zs->zs_pf_start = zs->zs_pf_end;
768 	} else {
769 		pf_start = pf_end = 0;
770 	}
771 	ipf_start = zs->zs_ipf_start;
772 	ipf_end = zs->zs_ipf_start = zs->zs_ipf_end;
773 	mutex_exit(&zf->zf_lock);
774 	ASSERT3S(pf_start, <=, pf_end);
775 	ASSERT3S(ipf_start, <=, ipf_end);
776 
777 	epbs = zf->zf_dnode->dn_indblkshift - SPA_BLKPTRSHIFT;
778 	ipf_start = P2ROUNDUP(ipf_start, 1 << epbs) >> epbs;
779 	ipf_end = P2ROUNDUP(ipf_end, 1 << epbs) >> epbs;
780 	ASSERT3S(ipf_start, <=, ipf_end);
781 	issued = pf_end - pf_start + ipf_end - ipf_start;
782 	if (issued > 1) {
783 		/* More references on top of taken in dmu_zfetch_prepare(). */
784 		zfs_refcount_add_few(&zs->zs_refs, issued - 1, NULL);
785 	} else if (issued == 0) {
786 		/* Some other thread has done our work, so drop the ref. */
787 		if (zfs_refcount_remove(&zs->zs_refs, NULL) == 0)
788 			dmu_zfetch_stream_fini(zs);
789 		return;
790 	}
791 	aggsum_add(&zfetch_sums.zfetchstat_io_active, issued);
792 
793 	if (!have_lock)
794 		rw_enter(&zf->zf_dnode->dn_struct_rwlock, RW_READER);
795 
796 	issued = 0;
797 	for (int64_t blk = pf_start; blk < pf_end; blk++) {
798 		issued += dbuf_prefetch_impl(zf->zf_dnode, 0, blk,
799 		    ZIO_PRIORITY_ASYNC_READ, uncached ?
800 		    ARC_FLAG_UNCACHED : 0, dmu_zfetch_done, zs);
801 	}
802 	for (int64_t iblk = ipf_start; iblk < ipf_end; iblk++) {
803 		issued += dbuf_prefetch_impl(zf->zf_dnode, 1, iblk,
804 		    ZIO_PRIORITY_ASYNC_READ, 0, dmu_zfetch_done, zs);
805 	}
806 
807 	if (!have_lock)
808 		rw_exit(&zf->zf_dnode->dn_struct_rwlock);
809 
810 	if (issued)
811 		ZFETCHSTAT_ADD(zfetchstat_io_issued, issued);
812 }
813 
814 void
dmu_zfetch(zfetch_t * zf,uint64_t blkid,uint64_t nblks,boolean_t fetch_data,boolean_t missed,boolean_t have_lock,boolean_t uncached)815 dmu_zfetch(zfetch_t *zf, uint64_t blkid, uint64_t nblks, boolean_t fetch_data,
816     boolean_t missed, boolean_t have_lock, boolean_t uncached)
817 {
818 	zstream_t *zs;
819 
820 	zs = dmu_zfetch_prepare(zf, blkid, nblks, fetch_data, have_lock);
821 	if (zs)
822 		dmu_zfetch_run(zf, zs, missed, have_lock, uncached);
823 }
824 
825 ZFS_MODULE_PARAM(zfs_prefetch, zfs_prefetch_, disable, INT, ZMOD_RW,
826 	"Disable all ZFS prefetching");
827 
828 ZFS_MODULE_PARAM(zfs_prefetch, zfetch_, max_streams, UINT, ZMOD_RW,
829 	"Max number of streams per zfetch");
830 
831 ZFS_MODULE_PARAM(zfs_prefetch, zfetch_, min_sec_reap, UINT, ZMOD_RW,
832 	"Min time before stream reclaim");
833 
834 ZFS_MODULE_PARAM(zfs_prefetch, zfetch_, max_sec_reap, UINT, ZMOD_RW,
835 	"Max time before stream delete");
836 
837 ZFS_MODULE_PARAM(zfs_prefetch, zfetch_, min_distance, UINT, ZMOD_RW,
838 	"Min bytes to prefetch per stream");
839 
840 ZFS_MODULE_PARAM(zfs_prefetch, zfetch_, max_distance, UINT, ZMOD_RW,
841 	"Max bytes to prefetch per stream");
842 
843 ZFS_MODULE_PARAM(zfs_prefetch, zfetch_, max_idistance, UINT, ZMOD_RW,
844 	"Max bytes to prefetch indirects for per stream");
845 
846 ZFS_MODULE_PARAM(zfs_prefetch, zfetch_, max_reorder, UINT, ZMOD_RW,
847 	"Max request reorder distance within a stream");
848 
849 ZFS_MODULE_PARAM(zfs_prefetch, zfetch_, hole_shift, UINT, ZMOD_RW,
850 	"Max log2 fraction of holes in a stream");
851