xref: /freebsd/sys/contrib/openzfs/module/zfs/dmu.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 (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
14  * Copyright (c) 2011, 2020 by Delphix. All rights reserved.
15  * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
16  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
17  * Copyright (c) 2016, Nexenta Systems, Inc. All rights reserved.
18  * Copyright (c) 2015 by Chunwei Chen. All rights reserved.
19  * Copyright (c) 2019 Datto Inc.
20  * Copyright (c) 2019, 2023, Klara Inc.
21  * Copyright (c) 2019, Allan Jude
22  * Copyright (c) 2022 Hewlett Packard Enterprise Development LP.
23  * Copyright (c) 2021, 2022 by Pawel Jakub Dawidek
24  */
25 
26 #include <sys/dmu.h>
27 #include <sys/dmu_impl.h>
28 #include <sys/dmu_tx.h>
29 #include <sys/dbuf.h>
30 #include <sys/dnode.h>
31 #include <sys/zfs_context.h>
32 #include <sys/dmu_objset.h>
33 #include <sys/dmu_traverse.h>
34 #include <sys/dsl_dataset.h>
35 #include <sys/dsl_dir.h>
36 #include <sys/dsl_pool.h>
37 #include <sys/dsl_synctask.h>
38 #include <sys/dsl_prop.h>
39 #include <sys/dmu_zfetch.h>
40 #include <sys/kstat.h>
41 #include <sys/zfs_ioctl.h>
42 #include <sys/zap.h>
43 #include <sys/zio_checksum.h>
44 #include <sys/zio_compress.h>
45 #include <sys/sa.h>
46 #include <sys/zfeature.h>
47 #include <sys/abd.h>
48 #include <sys/brt.h>
49 #include <sys/trace_zfs.h>
50 #include <sys/zfs_racct.h>
51 #include <sys/zfs_rlock.h>
52 #ifdef _KERNEL
53 #include <sys/vmsystm.h>
54 #include <sys/zfs_znode.h>
55 #endif
56 
57 /*
58  * Enable/disable nopwrite feature.
59  */
60 static int zfs_nopwrite_enabled = 1;
61 
62 /*
63  * Tunable to control percentage of dirtied L1 blocks from frees allowed into
64  * one TXG. After this threshold is crossed, additional dirty blocks from frees
65  * will wait until the next TXG.
66  * A value of zero will disable this throttle.
67  */
68 static uint_t zfs_per_txg_dirty_frees_percent = 30;
69 
70 /*
71  * Enable/disable forcing txg sync when dirty checking for holes with lseek().
72  * By default this is enabled to ensure accurate hole reporting, it can result
73  * in a significant performance penalty for lseek(SEEK_HOLE) heavy workloads.
74  * Disabling this option will result in holes never being reported in dirty
75  * files which is always safe.
76  */
77 static int zfs_dmu_offset_next_sync = 1;
78 
79 /*
80  * Limit the amount we can prefetch with one call to this amount.  This
81  * helps to limit the amount of memory that can be used by prefetching.
82  * Larger objects should be prefetched a bit at a time.
83  */
84 #ifdef _ILP32
85 uint_t dmu_prefetch_max = 8 * 1024 * 1024;
86 #else
87 uint_t dmu_prefetch_max = 8 * SPA_MAXBLOCKSIZE;
88 #endif
89 
90 /*
91  * Override copies= for dedup state objects. 0 means the traditional behaviour
92  * (ie the default for the containing objset ie 3 for the MOS).
93  */
94 uint_t dmu_ddt_copies = 0;
95 
96 const dmu_object_type_info_t dmu_ot[DMU_OT_NUMTYPES] = {
97 	{DMU_BSWAP_UINT8,  TRUE,  FALSE, FALSE, "unallocated"		},
98 	{DMU_BSWAP_ZAP,    TRUE,  TRUE,  FALSE, "object directory"	},
99 	{DMU_BSWAP_UINT64, TRUE,  TRUE,  FALSE, "object array"		},
100 	{DMU_BSWAP_UINT8,  TRUE,  FALSE, FALSE, "packed nvlist"		},
101 	{DMU_BSWAP_UINT64, TRUE,  FALSE, FALSE, "packed nvlist size"	},
102 	{DMU_BSWAP_UINT64, TRUE,  FALSE, FALSE, "bpobj"			},
103 	{DMU_BSWAP_UINT64, TRUE,  FALSE, FALSE, "bpobj header"		},
104 	{DMU_BSWAP_UINT64, TRUE,  FALSE, FALSE, "SPA space map header"	},
105 	{DMU_BSWAP_UINT64, TRUE,  FALSE, FALSE, "SPA space map"		},
106 	{DMU_BSWAP_UINT64, TRUE,  FALSE, TRUE,  "ZIL intent log"	},
107 	{DMU_BSWAP_DNODE,  TRUE,  FALSE, TRUE,  "DMU dnode"		},
108 	{DMU_BSWAP_OBJSET, TRUE,  TRUE,  FALSE, "DMU objset"		},
109 	{DMU_BSWAP_UINT64, TRUE,  TRUE,  FALSE, "DSL directory"		},
110 	{DMU_BSWAP_ZAP,    TRUE,  TRUE,  FALSE, "DSL directory child map"},
111 	{DMU_BSWAP_ZAP,    TRUE,  TRUE,  FALSE, "DSL dataset snap map"	},
112 	{DMU_BSWAP_ZAP,    TRUE,  TRUE,  FALSE, "DSL props"		},
113 	{DMU_BSWAP_UINT64, TRUE,  TRUE,  FALSE, "DSL dataset"		},
114 	{DMU_BSWAP_ZNODE,  TRUE,  FALSE, FALSE, "ZFS znode"		},
115 	{DMU_BSWAP_OLDACL, TRUE,  FALSE, TRUE,  "ZFS V0 ACL"		},
116 	{DMU_BSWAP_UINT8,  FALSE, FALSE, TRUE,  "ZFS plain file"	},
117 	{DMU_BSWAP_ZAP,    TRUE,  FALSE, TRUE,  "ZFS directory"		},
118 	{DMU_BSWAP_ZAP,    TRUE,  FALSE, FALSE, "ZFS master node"	},
119 	{DMU_BSWAP_ZAP,    TRUE,  FALSE, TRUE,  "ZFS delete queue"	},
120 	{DMU_BSWAP_UINT8,  FALSE, FALSE, TRUE,  "zvol object"		},
121 	{DMU_BSWAP_ZAP,    TRUE,  FALSE, FALSE, "zvol prop"		},
122 	{DMU_BSWAP_UINT8,  FALSE, FALSE, TRUE,  "other uint8[]"		},
123 	{DMU_BSWAP_UINT64, FALSE, FALSE, TRUE,  "other uint64[]"	},
124 	{DMU_BSWAP_ZAP,    TRUE,  FALSE, FALSE, "other ZAP"		},
125 	{DMU_BSWAP_ZAP,    TRUE,  FALSE, FALSE, "persistent error log"	},
126 	{DMU_BSWAP_UINT8,  TRUE,  FALSE, FALSE, "SPA history"		},
127 	{DMU_BSWAP_UINT64, TRUE,  FALSE, FALSE, "SPA history offsets"	},
128 	{DMU_BSWAP_ZAP,    TRUE,  TRUE,  FALSE, "Pool properties"	},
129 	{DMU_BSWAP_ZAP,    TRUE,  TRUE,  FALSE, "DSL permissions"	},
130 	{DMU_BSWAP_ACL,    TRUE,  FALSE, TRUE,  "ZFS ACL"		},
131 	{DMU_BSWAP_UINT8,  TRUE,  FALSE, TRUE,  "ZFS SYSACL"		},
132 	{DMU_BSWAP_UINT8,  TRUE,  FALSE, TRUE,  "FUID table"		},
133 	{DMU_BSWAP_UINT64, TRUE,  FALSE, FALSE, "FUID table size"	},
134 	{DMU_BSWAP_ZAP,    TRUE,  TRUE,  FALSE, "DSL dataset next clones"},
135 	{DMU_BSWAP_ZAP,    TRUE,  FALSE, FALSE, "scan work queue"	},
136 	{DMU_BSWAP_ZAP,    TRUE,  FALSE, TRUE,  "ZFS user/group/project used" },
137 	{DMU_BSWAP_ZAP,    TRUE,  FALSE, TRUE,  "ZFS user/group/project quota"},
138 	{DMU_BSWAP_ZAP,    TRUE,  TRUE,  FALSE, "snapshot refcount tags"},
139 	{DMU_BSWAP_ZAP,    TRUE,  FALSE, FALSE, "DDT ZAP algorithm"	},
140 	{DMU_BSWAP_ZAP,    TRUE,  FALSE, FALSE, "DDT statistics"	},
141 	{DMU_BSWAP_UINT8,  TRUE,  FALSE, TRUE,	"System attributes"	},
142 	{DMU_BSWAP_ZAP,    TRUE,  FALSE, TRUE,	"SA master node"	},
143 	{DMU_BSWAP_ZAP,    TRUE,  FALSE, TRUE,	"SA attr registration"	},
144 	{DMU_BSWAP_ZAP,    TRUE,  FALSE, TRUE,	"SA attr layouts"	},
145 	{DMU_BSWAP_ZAP,    TRUE,  FALSE, FALSE, "scan translations"	},
146 	{DMU_BSWAP_UINT8,  FALSE, FALSE, TRUE,  "deduplicated block"	},
147 	{DMU_BSWAP_ZAP,    TRUE,  TRUE,  FALSE, "DSL deadlist map"	},
148 	{DMU_BSWAP_UINT64, TRUE,  TRUE,  FALSE, "DSL deadlist map hdr"	},
149 	{DMU_BSWAP_ZAP,    TRUE,  TRUE,  FALSE, "DSL dir clones"	},
150 	{DMU_BSWAP_UINT64, TRUE,  FALSE, FALSE, "bpobj subobj"		}
151 };
152 
153 dmu_object_byteswap_info_t dmu_ot_byteswap[DMU_BSWAP_NUMFUNCS] = {
154 	{	byteswap_uint8_array,	"uint8"		},
155 	{	byteswap_uint16_array,	"uint16"	},
156 	{	byteswap_uint32_array,	"uint32"	},
157 	{	byteswap_uint64_array,	"uint64"	},
158 	{	zap_byteswap,		"zap"		},
159 	{	dnode_buf_byteswap,	"dnode"		},
160 	{	dmu_objset_byteswap,	"objset"	},
161 	{	zfs_znode_byteswap,	"znode"		},
162 	{	zfs_oldacl_byteswap,	"oldacl"	},
163 	{	zfs_acl_byteswap,	"acl"		}
164 };
165 
166 int
dmu_buf_hold_noread_by_dnode(dnode_t * dn,uint64_t offset,const void * tag,dmu_buf_t ** dbp)167 dmu_buf_hold_noread_by_dnode(dnode_t *dn, uint64_t offset,
168     const void *tag, dmu_buf_t **dbp)
169 {
170 	uint64_t blkid;
171 	dmu_buf_impl_t *db;
172 
173 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
174 	blkid = dbuf_whichblock(dn, 0, offset);
175 	db = dbuf_hold(dn, blkid, tag);
176 	rw_exit(&dn->dn_struct_rwlock);
177 
178 	if (db == NULL) {
179 		*dbp = NULL;
180 		return (SET_ERROR(EIO));
181 	}
182 
183 	*dbp = &db->db;
184 	return (0);
185 }
186 
187 int
dmu_buf_hold_noread(objset_t * os,uint64_t object,uint64_t offset,const void * tag,dmu_buf_t ** dbp)188 dmu_buf_hold_noread(objset_t *os, uint64_t object, uint64_t offset,
189     const void *tag, dmu_buf_t **dbp)
190 {
191 	dnode_t *dn;
192 	uint64_t blkid;
193 	dmu_buf_impl_t *db;
194 	int err;
195 
196 	err = dnode_hold(os, object, FTAG, &dn);
197 	if (err)
198 		return (err);
199 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
200 	blkid = dbuf_whichblock(dn, 0, offset);
201 	db = dbuf_hold(dn, blkid, tag);
202 	rw_exit(&dn->dn_struct_rwlock);
203 	dnode_rele(dn, FTAG);
204 
205 	if (db == NULL) {
206 		*dbp = NULL;
207 		return (SET_ERROR(EIO));
208 	}
209 
210 	*dbp = &db->db;
211 	return (err);
212 }
213 
214 int
dmu_buf_hold_by_dnode(dnode_t * dn,uint64_t offset,const void * tag,dmu_buf_t ** dbp,dmu_flags_t flags)215 dmu_buf_hold_by_dnode(dnode_t *dn, uint64_t offset,
216     const void *tag, dmu_buf_t **dbp, dmu_flags_t flags)
217 {
218 	int err;
219 
220 	err = dmu_buf_hold_noread_by_dnode(dn, offset, tag, dbp);
221 	if (err == 0) {
222 		dmu_buf_impl_t *db = (dmu_buf_impl_t *)(*dbp);
223 		err = dbuf_read(db, NULL, flags | DB_RF_CANFAIL);
224 		if (err != 0) {
225 			dbuf_rele(db, tag);
226 			*dbp = NULL;
227 		}
228 	}
229 
230 	return (err);
231 }
232 
233 int
dmu_buf_hold(objset_t * os,uint64_t object,uint64_t offset,const void * tag,dmu_buf_t ** dbp,dmu_flags_t flags)234 dmu_buf_hold(objset_t *os, uint64_t object, uint64_t offset,
235     const void *tag, dmu_buf_t **dbp, dmu_flags_t flags)
236 {
237 	int err;
238 
239 	err = dmu_buf_hold_noread(os, object, offset, tag, dbp);
240 	if (err == 0) {
241 		dmu_buf_impl_t *db = (dmu_buf_impl_t *)(*dbp);
242 		err = dbuf_read(db, NULL, flags | DB_RF_CANFAIL);
243 		if (err != 0) {
244 			dbuf_rele(db, tag);
245 			*dbp = NULL;
246 		}
247 	}
248 
249 	return (err);
250 }
251 
252 int
dmu_bonus_max(void)253 dmu_bonus_max(void)
254 {
255 	return (DN_OLD_MAX_BONUSLEN);
256 }
257 
258 int
dmu_set_bonus(dmu_buf_t * db_fake,int newsize,dmu_tx_t * tx)259 dmu_set_bonus(dmu_buf_t *db_fake, int newsize, dmu_tx_t *tx)
260 {
261 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
262 	dnode_t *dn;
263 	int error;
264 
265 	if (newsize < 0 || newsize > db_fake->db_size)
266 		return (SET_ERROR(EINVAL));
267 
268 	DB_DNODE_ENTER(db);
269 	dn = DB_DNODE(db);
270 
271 	if (dn->dn_bonus != db) {
272 		error = SET_ERROR(EINVAL);
273 	} else {
274 		dnode_setbonuslen(dn, newsize, tx);
275 		error = 0;
276 	}
277 
278 	DB_DNODE_EXIT(db);
279 	return (error);
280 }
281 
282 int
dmu_set_bonustype(dmu_buf_t * db_fake,dmu_object_type_t type,dmu_tx_t * tx)283 dmu_set_bonustype(dmu_buf_t *db_fake, dmu_object_type_t type, dmu_tx_t *tx)
284 {
285 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
286 	dnode_t *dn;
287 	int error;
288 
289 	if (!DMU_OT_IS_VALID(type))
290 		return (SET_ERROR(EINVAL));
291 
292 	DB_DNODE_ENTER(db);
293 	dn = DB_DNODE(db);
294 
295 	if (dn->dn_bonus != db) {
296 		error = SET_ERROR(EINVAL);
297 	} else {
298 		dnode_setbonus_type(dn, type, tx);
299 		error = 0;
300 	}
301 
302 	DB_DNODE_EXIT(db);
303 	return (error);
304 }
305 
306 dmu_object_type_t
dmu_get_bonustype(dmu_buf_t * db_fake)307 dmu_get_bonustype(dmu_buf_t *db_fake)
308 {
309 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
310 	dmu_object_type_t type;
311 
312 	DB_DNODE_ENTER(db);
313 	type = DB_DNODE(db)->dn_bonustype;
314 	DB_DNODE_EXIT(db);
315 
316 	return (type);
317 }
318 
319 int
dmu_rm_spill(objset_t * os,uint64_t object,dmu_tx_t * tx)320 dmu_rm_spill(objset_t *os, uint64_t object, dmu_tx_t *tx)
321 {
322 	dnode_t *dn;
323 	int error;
324 
325 	error = dnode_hold(os, object, FTAG, &dn);
326 	dbuf_rm_spill(dn, tx);
327 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
328 	dnode_rm_spill(dn, tx);
329 	rw_exit(&dn->dn_struct_rwlock);
330 	dnode_rele(dn, FTAG);
331 	return (error);
332 }
333 
334 /*
335  * Lookup and hold the bonus buffer for the provided dnode.  If the dnode
336  * has not yet been allocated a new bonus dbuf a will be allocated.
337  * Returns ENOENT, EIO, or 0.
338  */
dmu_bonus_hold_by_dnode(dnode_t * dn,const void * tag,dmu_buf_t ** dbp,dmu_flags_t flags)339 int dmu_bonus_hold_by_dnode(dnode_t *dn, const void *tag, dmu_buf_t **dbp,
340     dmu_flags_t flags)
341 {
342 	dmu_buf_impl_t *db;
343 	int error;
344 
345 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
346 	if (dn->dn_bonus == NULL) {
347 		if (!rw_tryupgrade(&dn->dn_struct_rwlock)) {
348 			rw_exit(&dn->dn_struct_rwlock);
349 			rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
350 		}
351 		if (dn->dn_bonus == NULL)
352 			dbuf_create_bonus(dn);
353 	}
354 	db = dn->dn_bonus;
355 
356 	/* as long as the bonus buf is held, the dnode will be held */
357 	if (zfs_refcount_add(&db->db_holds, tag) == 1) {
358 		VERIFY(dnode_add_ref(dn, db));
359 		atomic_inc_32(&dn->dn_dbufs_count);
360 	}
361 
362 	/*
363 	 * Wait to drop dn_struct_rwlock until after adding the bonus dbuf's
364 	 * hold and incrementing the dbuf count to ensure that dnode_move() sees
365 	 * a dnode hold for every dbuf.
366 	 */
367 	rw_exit(&dn->dn_struct_rwlock);
368 
369 	error = dbuf_read(db, NULL, flags | DB_RF_CANFAIL);
370 	if (error) {
371 		dnode_evict_bonus(dn);
372 		dbuf_rele(db, tag);
373 		*dbp = NULL;
374 		return (error);
375 	}
376 
377 	*dbp = &db->db;
378 	return (0);
379 }
380 
381 int
dmu_bonus_hold(objset_t * os,uint64_t object,const void * tag,dmu_buf_t ** dbp)382 dmu_bonus_hold(objset_t *os, uint64_t object, const void *tag, dmu_buf_t **dbp)
383 {
384 	dnode_t *dn;
385 	int error;
386 
387 	error = dnode_hold(os, object, FTAG, &dn);
388 	if (error)
389 		return (error);
390 
391 	error = dmu_bonus_hold_by_dnode(dn, tag, dbp, DMU_READ_NO_PREFETCH);
392 	dnode_rele(dn, FTAG);
393 
394 	return (error);
395 }
396 
397 /*
398  * returns ENOENT, EIO, or 0.
399  *
400  * This interface will allocate a blank spill dbuf when a spill blk
401  * doesn't already exist on the dnode.
402  *
403  * if you only want to find an already existing spill db, then
404  * dmu_spill_hold_existing() should be used.
405  */
406 int
dmu_spill_hold_by_dnode(dnode_t * dn,dmu_flags_t flags,const void * tag,dmu_buf_t ** dbp)407 dmu_spill_hold_by_dnode(dnode_t *dn, dmu_flags_t flags, const void *tag,
408     dmu_buf_t **dbp)
409 {
410 	dmu_buf_impl_t *db = NULL;
411 	int err;
412 
413 	if ((flags & DB_RF_HAVESTRUCT) == 0)
414 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
415 
416 	db = dbuf_hold(dn, DMU_SPILL_BLKID, tag);
417 
418 	if ((flags & DB_RF_HAVESTRUCT) == 0)
419 		rw_exit(&dn->dn_struct_rwlock);
420 
421 	if (db == NULL) {
422 		*dbp = NULL;
423 		return (SET_ERROR(EIO));
424 	}
425 	err = dbuf_read(db, NULL, flags);
426 	if (err == 0)
427 		*dbp = &db->db;
428 	else {
429 		dbuf_rele(db, tag);
430 		*dbp = NULL;
431 	}
432 	return (err);
433 }
434 
435 int
dmu_spill_hold_existing(dmu_buf_t * bonus,const void * tag,dmu_buf_t ** dbp)436 dmu_spill_hold_existing(dmu_buf_t *bonus, const void *tag, dmu_buf_t **dbp)
437 {
438 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)bonus;
439 	dnode_t *dn;
440 	int err;
441 
442 	DB_DNODE_ENTER(db);
443 	dn = DB_DNODE(db);
444 
445 	if (spa_version(dn->dn_objset->os_spa) < SPA_VERSION_SA) {
446 		err = SET_ERROR(EINVAL);
447 	} else {
448 		rw_enter(&dn->dn_struct_rwlock, RW_READER);
449 
450 		if (!dn->dn_have_spill) {
451 			err = SET_ERROR(ENOENT);
452 		} else {
453 			err = dmu_spill_hold_by_dnode(dn,
454 			    DB_RF_HAVESTRUCT | DB_RF_CANFAIL, tag, dbp);
455 		}
456 
457 		rw_exit(&dn->dn_struct_rwlock);
458 	}
459 
460 	DB_DNODE_EXIT(db);
461 	return (err);
462 }
463 
464 int
dmu_spill_hold_by_bonus(dmu_buf_t * bonus,dmu_flags_t flags,const void * tag,dmu_buf_t ** dbp)465 dmu_spill_hold_by_bonus(dmu_buf_t *bonus, dmu_flags_t flags, const void *tag,
466     dmu_buf_t **dbp)
467 {
468 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)bonus;
469 	int err;
470 
471 	DB_DNODE_ENTER(db);
472 	err = dmu_spill_hold_by_dnode(DB_DNODE(db), flags, tag, dbp);
473 	DB_DNODE_EXIT(db);
474 
475 	return (err);
476 }
477 
478 /*
479  * Note: longer-term, we should modify all of the dmu_buf_*() interfaces
480  * to take a held dnode rather than <os, object> -- the lookup is wasteful,
481  * and can induce severe lock contention when writing to several files
482  * whose dnodes are in the same block.
483  */
484 int
dmu_buf_hold_array_by_dnode(dnode_t * dn,uint64_t offset,uint64_t length,boolean_t read,const void * tag,int * numbufsp,dmu_buf_t *** dbpp,dmu_flags_t flags)485 dmu_buf_hold_array_by_dnode(dnode_t *dn, uint64_t offset, uint64_t length,
486     boolean_t read, const void *tag, int *numbufsp, dmu_buf_t ***dbpp,
487     dmu_flags_t flags)
488 {
489 	dmu_buf_t **dbp;
490 	zstream_t *zs = NULL;
491 	uint64_t blkid, nblks, i;
492 	dmu_flags_t dbuf_flags;
493 	int err;
494 	zio_t *zio = NULL;
495 	boolean_t missed = B_FALSE;
496 
497 	ASSERT(!read || length <= DMU_MAX_ACCESS);
498 
499 	/*
500 	 * Note: We directly notify the prefetch code of this read, so that
501 	 * we can tell it about the multi-block read.  dbuf_read() only knows
502 	 * about the one block it is accessing.
503 	 */
504 	dbuf_flags = (flags & ~DMU_READ_PREFETCH) | DMU_READ_NO_PREFETCH |
505 	    DB_RF_CANFAIL | DB_RF_NEVERWAIT | DB_RF_HAVESTRUCT;
506 
507 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
508 	if (dn->dn_datablkshift) {
509 		int blkshift = dn->dn_datablkshift;
510 		nblks = (P2ROUNDUP(offset + length, 1ULL << blkshift) -
511 		    P2ALIGN_TYPED(offset, 1ULL << blkshift, uint64_t))
512 		    >> blkshift;
513 	} else {
514 		if (offset + length > dn->dn_datablksz) {
515 			zfs_panic_recover("zfs: accessing past end of object "
516 			    "%llx/%llx (size=%u access=%llu+%llu)",
517 			    (longlong_t)dn->dn_objset->
518 			    os_dsl_dataset->ds_object,
519 			    (longlong_t)dn->dn_object, dn->dn_datablksz,
520 			    (longlong_t)offset, (longlong_t)length);
521 			rw_exit(&dn->dn_struct_rwlock);
522 			return (SET_ERROR(EIO));
523 		}
524 		nblks = 1;
525 	}
526 	dbp = kmem_zalloc(sizeof (dmu_buf_t *) * nblks, KM_SLEEP);
527 
528 	if (read)
529 		zio = zio_root(dn->dn_objset->os_spa, NULL, NULL,
530 		    ZIO_FLAG_CANFAIL);
531 	blkid = dbuf_whichblock(dn, 0, offset);
532 	if ((flags & DMU_READ_NO_PREFETCH) == 0) {
533 		/*
534 		 * Prepare the zfetch before initiating the demand reads, so
535 		 * that if multiple threads block on same indirect block, we
536 		 * base predictions on the original less racy request order.
537 		 */
538 		zs = dmu_zfetch_prepare(&dn->dn_zfetch, blkid, nblks,
539 		    read && !(flags & DMU_DIRECTIO), B_TRUE);
540 	}
541 	for (i = 0; i < nblks; i++) {
542 		dmu_buf_impl_t *db = dbuf_hold(dn, blkid + i, tag);
543 		if (db == NULL) {
544 			if (zs) {
545 				dmu_zfetch_run(&dn->dn_zfetch, zs, missed,
546 				    B_TRUE, (flags & DMU_UNCACHEDIO));
547 			}
548 			rw_exit(&dn->dn_struct_rwlock);
549 			dmu_buf_rele_array(dbp, nblks, tag);
550 			if (read)
551 				zio_nowait(zio);
552 			return (SET_ERROR(EIO));
553 		}
554 
555 		/*
556 		 * Initiate async demand data read.
557 		 * We check the db_state after calling dbuf_read() because
558 		 * (1) dbuf_read() may change the state to CACHED due to a
559 		 * hit in the ARC, and (2) on a cache miss, a child will
560 		 * have been added to "zio" but not yet completed, so the
561 		 * state will not yet be CACHED.
562 		 */
563 		if (read) {
564 			if (i == nblks - 1 && blkid + i < dn->dn_maxblkid &&
565 			    offset + length < db->db.db_offset +
566 			    db->db.db_size) {
567 				if (offset <= db->db.db_offset)
568 					dbuf_flags |= DMU_PARTIAL_FIRST;
569 				else
570 					dbuf_flags |= DMU_PARTIAL_MORE;
571 			}
572 			(void) dbuf_read(db, zio, dbuf_flags);
573 			if (db->db_state != DB_CACHED)
574 				missed = B_TRUE;
575 		}
576 		dbp[i] = &db->db;
577 	}
578 
579 	/*
580 	 * If we are doing O_DIRECT we still hold the dbufs, even for reads,
581 	 * but we do not issue any reads here. We do not want to account for
582 	 * writes in this case.
583 	 *
584 	 * O_DIRECT write/read accounting takes place in
585 	 * dmu_{write/read}_abd().
586 	 */
587 	if (!read && ((flags & DMU_DIRECTIO) == 0))
588 		zfs_racct_write(dn->dn_objset->os_spa, length, nblks, flags);
589 
590 	if (zs) {
591 		dmu_zfetch_run(&dn->dn_zfetch, zs, missed, B_TRUE,
592 		    (flags & DMU_UNCACHEDIO));
593 	}
594 	rw_exit(&dn->dn_struct_rwlock);
595 
596 	if (read) {
597 		/* wait for async read i/o */
598 		err = zio_wait(zio);
599 		if (err) {
600 			dmu_buf_rele_array(dbp, nblks, tag);
601 			return (err);
602 		}
603 
604 		/* wait for other io to complete */
605 		for (i = 0; i < nblks; i++) {
606 			dmu_buf_impl_t *db = (dmu_buf_impl_t *)dbp[i];
607 			mutex_enter(&db->db_mtx);
608 			while (db->db_state == DB_READ ||
609 			    db->db_state == DB_FILL)
610 				cv_wait(&db->db_changed, &db->db_mtx);
611 			if (db->db_state == DB_UNCACHED)
612 				err = SET_ERROR(EIO);
613 			mutex_exit(&db->db_mtx);
614 			if (err) {
615 				dmu_buf_rele_array(dbp, nblks, tag);
616 				return (err);
617 			}
618 		}
619 	}
620 
621 	*numbufsp = nblks;
622 	*dbpp = dbp;
623 	return (0);
624 }
625 
626 int
dmu_buf_hold_array(objset_t * os,uint64_t object,uint64_t offset,uint64_t length,int read,const void * tag,int * numbufsp,dmu_buf_t *** dbpp,dmu_flags_t flags)627 dmu_buf_hold_array(objset_t *os, uint64_t object, uint64_t offset,
628     uint64_t length, int read, const void *tag, int *numbufsp,
629     dmu_buf_t ***dbpp, dmu_flags_t flags)
630 {
631 	dnode_t *dn;
632 	int err;
633 
634 	err = dnode_hold(os, object, FTAG, &dn);
635 	if (err)
636 		return (err);
637 
638 	err = dmu_buf_hold_array_by_dnode(dn, offset, length, read, tag,
639 	    numbufsp, dbpp, flags);
640 
641 	dnode_rele(dn, FTAG);
642 
643 	return (err);
644 }
645 
646 int
dmu_buf_hold_array_by_bonus(dmu_buf_t * db_fake,uint64_t offset,uint64_t length,boolean_t read,const void * tag,int * numbufsp,dmu_buf_t *** dbpp,dmu_flags_t flags)647 dmu_buf_hold_array_by_bonus(dmu_buf_t *db_fake, uint64_t offset,
648     uint64_t length, boolean_t read, const void *tag, int *numbufsp,
649     dmu_buf_t ***dbpp, dmu_flags_t flags)
650 {
651 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
652 	int err;
653 
654 	DB_DNODE_ENTER(db);
655 	err = dmu_buf_hold_array_by_dnode(DB_DNODE(db), offset, length, read,
656 	    tag, numbufsp, dbpp, flags);
657 	DB_DNODE_EXIT(db);
658 
659 	return (err);
660 }
661 
662 void
dmu_buf_rele_array(dmu_buf_t ** dbp_fake,int numbufs,const void * tag)663 dmu_buf_rele_array(dmu_buf_t **dbp_fake, int numbufs, const void *tag)
664 {
665 	int i;
666 	dmu_buf_impl_t **dbp = (dmu_buf_impl_t **)dbp_fake;
667 
668 	if (numbufs == 0)
669 		return;
670 
671 	for (i = 0; i < numbufs; i++) {
672 		if (dbp[i])
673 			dbuf_rele(dbp[i], tag);
674 	}
675 
676 	kmem_free(dbp, sizeof (dmu_buf_t *) * numbufs);
677 }
678 
679 /*
680  * Issue prefetch I/Os for the given blocks.  If level is greater than 0, the
681  * indirect blocks prefetched will be those that point to the blocks containing
682  * the data starting at offset, and continuing to offset + len.  If the range
683  * is too long, prefetch the first dmu_prefetch_max bytes as requested, while
684  * for the rest only a higher level, also fitting within dmu_prefetch_max.  It
685  * should primarily help random reads, since for long sequential reads there is
686  * a speculative prefetcher.
687  *
688  * Note that if the indirect blocks above the blocks being prefetched are not
689  * in cache, they will be asynchronously read in.  Dnode read by dnode_hold()
690  * is currently synchronous.
691  */
692 /*
693  * Outstanding bytes of explicit (user-requested) prefetch in flight, bounded
694  * by dmu_prefetch_user() so a large POSIX_FADV_WILLNEED hint cannot pin memory
695  * without limit and OOM the system (#15776).  Internal prefetch callers are
696  * not throttled.  Exported through the "dmustats" kstat.
697  */
698 static uint64_t dmu_prefetch_bytes_active;
699 
700 static struct {
701 	kstat_named_t prefetch_bytes_active;
702 } dmu_stats = {
703 	{ "prefetch_bytes_active",	KSTAT_DATA_UINT64 },
704 };
705 
706 static kstat_t *dmu_ksp;
707 
708 static int
dmu_kstats_update(kstat_t * ksp,int rw)709 dmu_kstats_update(kstat_t *ksp, int rw)
710 {
711 	(void) ksp;
712 	if (rw == KSTAT_WRITE)
713 		return (EACCES);
714 	dmu_stats.prefetch_bytes_active.value.ui64 =
715 	    atomic_load_64(&dmu_prefetch_bytes_active);
716 	return (0);
717 }
718 
719 static void dmu_prefetch_user_done(void *arg, uint64_t level, uint64_t blkid,
720     boolean_t issued);
721 static void dmu_prefetch_by_dnode_impl(dnode_t *dn, int64_t level,
722     uint64_t offset, uint64_t len, zio_priority_t pri, uint64_t maxbytes);
723 
724 void
dmu_prefetch(objset_t * os,uint64_t object,int64_t level,uint64_t offset,uint64_t len,zio_priority_t pri)725 dmu_prefetch(objset_t *os, uint64_t object, int64_t level, uint64_t offset,
726     uint64_t len, zio_priority_t pri)
727 {
728 	dnode_t *dn;
729 
730 	if (dmu_prefetch_max == 0 || len == 0) {
731 		dmu_prefetch_dnode(os, object, pri);
732 		return;
733 	}
734 
735 	if (dnode_hold(os, object, FTAG, &dn) != 0)
736 		return;
737 
738 	dmu_prefetch_by_dnode(dn, level, offset, len, pri);
739 
740 	dnode_rele(dn, FTAG);
741 }
742 
743 /*
744  * Like dmu_prefetch(), but for explicit user requests (e.g.
745  * POSIX_FADV_WILLNEED) that may span an arbitrarily large range.  Bound the
746  * outstanding prefetch so a large hint cannot pin memory without limit and OOM
747  * the system (#15776).  The budget is a quarter of arc_boot_target_bytes():
748  * the adaptive ARC target (arc_c) once the cache is warm, so it
749  * tightens under memory pressure; while the cache is still cold it uses the
750  * midpoint toward arc_c_max instead, so a hint issued right after boot -- when
751  * arc_c has not grown yet -- is not starved.
752  */
753 void
dmu_prefetch_user(objset_t * os,uint64_t object,int64_t level,uint64_t offset,uint64_t len,zio_priority_t pri)754 dmu_prefetch_user(objset_t *os, uint64_t object, int64_t level, uint64_t offset,
755     uint64_t len, zio_priority_t pri)
756 {
757 	dnode_t *dn;
758 
759 	if (dmu_prefetch_max == 0 || len == 0) {
760 		dmu_prefetch_dnode(os, object, pri);
761 		return;
762 	}
763 
764 	if (dnode_hold(os, object, FTAG, &dn) != 0)
765 		return;
766 
767 	uint64_t maxbytes = arc_boot_target_bytes() / 4;
768 	dmu_prefetch_by_dnode_impl(dn, level, offset, len, pri, maxbytes);
769 
770 	dnode_rele(dn, FTAG);
771 }
772 
773 static void
dmu_prefetch_user_done(void * arg,uint64_t level,uint64_t blkid,boolean_t issued)774 dmu_prefetch_user_done(void *arg, uint64_t level, uint64_t blkid,
775     boolean_t issued)
776 {
777 	(void) level, (void) blkid, (void) issued;
778 	atomic_add_64(&dmu_prefetch_bytes_active,
779 	    -(int64_t)(uintptr_t)arg);
780 }
781 
782 static void
dmu_prefetch_by_dnode_impl(dnode_t * dn,int64_t level,uint64_t offset,uint64_t len,zio_priority_t pri,uint64_t maxbytes)783 dmu_prefetch_by_dnode_impl(dnode_t *dn, int64_t level, uint64_t offset,
784     uint64_t len, zio_priority_t pri, uint64_t maxbytes)
785 {
786 	int64_t level2 = level;
787 	uint64_t start, end, start2, end2;
788 
789 	/*
790 	 * Depending on len we may do two prefetches: blocks [start, end) at
791 	 * level, and following blocks [start2, end2) at higher level2.
792 	 */
793 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
794 
795 	/*
796 	 * When bounding explicit prefetch (maxbytes != 0), take up to half the
797 	 * remaining budget for this request, so concurrent hints each get a
798 	 * slice instead of the first taking everything.  The resulting cap
799 	 * drives the block-range split below in place of dmu_prefetch_max, so a
800 	 * tight budget pushes more of the range up to the cheap indirect level
801 	 * -- prefetching all the indirects and only some data, which is what a
802 	 * following random-access pattern wants.  maxbytes == 0 is the
803 	 * unthrottled internal path and keeps the plain dmu_prefetch_max split.
804 	 */
805 	uint64_t cap = dmu_prefetch_max;
806 	if (maxbytes != 0) {
807 		uint64_t active = atomic_load_64(&dmu_prefetch_bytes_active);
808 		uint64_t headroom = maxbytes > active ? maxbytes - active : 0;
809 		cap = MIN(dmu_prefetch_max, headroom >> 1);
810 	}
811 
812 	if (dn->dn_datablkshift != 0) {
813 
814 		/*
815 		 * Limit prefetch to present blocks.
816 		 */
817 		uint64_t size = (dn->dn_maxblkid + 1) << dn->dn_datablkshift;
818 		if (offset >= size) {
819 			rw_exit(&dn->dn_struct_rwlock);
820 			return;
821 		}
822 		if (offset + len < offset || offset + len > size)
823 			len = size - offset;
824 
825 		/*
826 		 * The object has multiple blocks.  Calculate the full range
827 		 * of blocks [start, end2) and then split it into two parts,
828 		 * so that the first [start, end) fits into dmu_prefetch_max.
829 		 */
830 		start = dbuf_whichblock(dn, level, offset);
831 		end2 = dbuf_whichblock(dn, level, offset + len - 1) + 1;
832 		uint8_t ibs = dn->dn_indblkshift;
833 		uint8_t bs = (level == 0) ? dn->dn_datablkshift : ibs;
834 		uint_t limit = P2ROUNDUP(cap, 1 << bs) >> bs;
835 		start2 = end = MIN(end2, start + limit);
836 
837 		/*
838 		 * Find level2 where [start2, end2) fits into dmu_prefetch_max.
839 		 */
840 		uint8_t ibps = ibs - SPA_BLKPTRSHIFT;
841 		limit = P2ROUNDUP(cap, 1 << ibs) >> ibs;
842 		if (limit == 0)
843 			end2 = start2;
844 		do {
845 			level2++;
846 			start2 = P2ROUNDUP(start2, 1 << ibps) >> ibps;
847 			end2 = P2ROUNDUP(end2, 1 << ibps) >> ibps;
848 		} while (end2 - start2 > limit);
849 	} else {
850 		/* There is only one block.  Prefetch it or nothing. */
851 		start = start2 = end2 = 0;
852 		end = start + (level == 0 && offset < dn->dn_datablksz);
853 	}
854 
855 	/*
856 	 * Byte size of the blocks issued by each loop: data blocks (or
857 	 * indirects, if a higher level was requested) in the first, indirect
858 	 * blocks in the second.  Account the whole issued range against the
859 	 * budget in one shot up front -- one atomic add, not one per block --
860 	 * and let each block's completion callback release its own size, so the
861 	 * counter drains back as the reads complete.
862 	 */
863 	uint64_t blksz1 = (level == 0) ? dn->dn_datablksz :
864 	    (1ULL << dn->dn_indblkshift);
865 	uint64_t blksz2 = 1ULL << dn->dn_indblkshift;
866 	dbuf_prefetch_fn cb = NULL;
867 	if (maxbytes != 0) {
868 		uint64_t issued = (end - start) * blksz1 +
869 		    (end2 - start2) * blksz2;
870 		if (issued != 0) {
871 			atomic_add_64(&dmu_prefetch_bytes_active, issued);
872 			cb = dmu_prefetch_user_done;
873 		}
874 	}
875 
876 	for (uint64_t i = start; i < end; i++) {
877 		(void) dbuf_prefetch_impl(dn, level, i, pri, 0, cb,
878 		    (void *)(uintptr_t)blksz1);
879 	}
880 	for (uint64_t i = start2; i < end2; i++) {
881 		(void) dbuf_prefetch_impl(dn, level2, i, pri, 0, cb,
882 		    (void *)(uintptr_t)blksz2);
883 	}
884 	rw_exit(&dn->dn_struct_rwlock);
885 }
886 
887 void
dmu_prefetch_by_dnode(dnode_t * dn,int64_t level,uint64_t offset,uint64_t len,zio_priority_t pri)888 dmu_prefetch_by_dnode(dnode_t *dn, int64_t level, uint64_t offset,
889     uint64_t len, zio_priority_t pri)
890 {
891 	dmu_prefetch_by_dnode_impl(dn, level, offset, len, pri, 0);
892 }
893 
894 /*
895  * Prime a prefetch for sequential accesses from offset for at least len bytes.
896  */
897 void
dmu_prefetch_stream(objset_t * os,uint64_t object,uint64_t offset,uint64_t len,boolean_t start_now)898 dmu_prefetch_stream(objset_t *os, uint64_t object, uint64_t offset,
899     uint64_t len, boolean_t start_now)
900 {
901 	dnode_t *dn;
902 
903 	if (dnode_hold(os, object, FTAG, &dn) != 0)
904 		return;
905 	dmu_prefetch_stream_by_dnode(dn, offset, len, start_now);
906 	dnode_rele(dn, FTAG);
907 }
908 
909 void
dmu_prefetch_stream_by_dnode(dnode_t * dn,uint64_t offset,uint64_t len,boolean_t start_now)910 dmu_prefetch_stream_by_dnode(dnode_t *dn, uint64_t offset, uint64_t len,
911     boolean_t start_now)
912 {
913 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
914 	if (dn->dn_datablkshift != 0) {
915 		uint64_t start = dbuf_whichblock(dn, 0, offset);
916 		if (len == 0) {
917 			if (dmu_zfetch_prime(&dn->dn_zfetch, start, start) &&
918 			    start_now) {
919 				dmu_zfetch(&dn->dn_zfetch, start, 0, B_TRUE,
920 				    B_TRUE, B_TRUE, B_FALSE);
921 			}
922 		} else {
923 			uint64_t end = dbuf_whichblock(dn, 0, offset + len - 1);
924 			if (start == end) {
925 				if (start_now) {
926 					dbuf_prefetch(dn, 0, start,
927 					    ZIO_PRIORITY_ASYNC_READ, 0);
928 				}
929 			} else if (
930 			    dmu_zfetch_prime(&dn->dn_zfetch, start, end + 1) &&
931 			    start_now) {
932 				dmu_zfetch(&dn->dn_zfetch, start, 0, B_TRUE,
933 				    B_TRUE, B_TRUE, B_FALSE);
934 			}
935 		}
936 	} else if (offset < dn->dn_datablksz && start_now) {
937 		dbuf_prefetch(dn, 0, 0, ZIO_PRIORITY_ASYNC_READ, 0);
938 	}
939 	rw_exit(&dn->dn_struct_rwlock);
940 }
941 
942 typedef struct {
943 	kmutex_t	dpa_lock;
944 	kcondvar_t	dpa_cv;
945 	uint64_t	dpa_pending_io;
946 } dmu_prefetch_arg_t;
947 
948 static void
dmu_prefetch_done(void * arg,uint64_t level,uint64_t blkid,boolean_t issued)949 dmu_prefetch_done(void *arg, uint64_t level, uint64_t blkid, boolean_t issued)
950 {
951 	(void) level; (void) blkid; (void)issued;
952 	dmu_prefetch_arg_t *dpa = arg;
953 
954 	ASSERT0(level);
955 
956 	mutex_enter(&dpa->dpa_lock);
957 	ASSERT3U(dpa->dpa_pending_io, >, 0);
958 	if (--dpa->dpa_pending_io == 0)
959 		cv_broadcast(&dpa->dpa_cv);
960 	mutex_exit(&dpa->dpa_lock);
961 }
962 
963 static void
dmu_prefetch_wait_by_dnode(dnode_t * dn,uint64_t offset,uint64_t len)964 dmu_prefetch_wait_by_dnode(dnode_t *dn, uint64_t offset, uint64_t len)
965 {
966 	dmu_prefetch_arg_t dpa;
967 
968 	mutex_init(&dpa.dpa_lock, NULL, MUTEX_DEFAULT, NULL);
969 	cv_init(&dpa.dpa_cv, NULL, CV_DEFAULT, NULL);
970 
971 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
972 
973 	uint64_t start = dbuf_whichblock(dn, 0, offset);
974 	uint64_t end = dbuf_whichblock(dn, 0, offset + len - 1) + 1;
975 	dpa.dpa_pending_io = end - start;
976 
977 	for (uint64_t blk = start; blk < end; blk++) {
978 		(void) dbuf_prefetch_impl(dn, 0, blk, ZIO_PRIORITY_ASYNC_READ,
979 		    0, dmu_prefetch_done, &dpa);
980 	}
981 
982 	rw_exit(&dn->dn_struct_rwlock);
983 
984 	/* wait for prefetch L0 reads to finish */
985 	mutex_enter(&dpa.dpa_lock);
986 	while (dpa.dpa_pending_io > 0) {
987 		cv_wait(&dpa.dpa_cv, &dpa.dpa_lock);
988 
989 	}
990 	mutex_exit(&dpa.dpa_lock);
991 
992 	mutex_destroy(&dpa.dpa_lock);
993 	cv_destroy(&dpa.dpa_cv);
994 }
995 
996 /*
997  * Issue prefetch I/Os for the given L0 block range and wait for the I/O
998  * to complete. This does not enforce dmu_prefetch_max and will prefetch
999  * the entire range. The blocks are read from disk into the ARC but no
1000  * decompression occurs (i.e., the dbuf cache is not required).
1001  */
1002 int
dmu_prefetch_wait(objset_t * os,uint64_t object,uint64_t offset,uint64_t size)1003 dmu_prefetch_wait(objset_t *os, uint64_t object, uint64_t offset, uint64_t size)
1004 {
1005 	dnode_t *dn;
1006 	int err = 0;
1007 
1008 	err = dnode_hold(os, object, FTAG, &dn);
1009 	if (err != 0)
1010 		return (err);
1011 
1012 	/*
1013 	 * Chunk the requests (16 indirects worth) so that we can be
1014 	 * interrupted.  Prefetch at least SPA_MAXBLOCKSIZE at a time
1015 	 * to better utilize pools with smaller block sizes.
1016 	 */
1017 	uint64_t chunksize;
1018 	if (dn->dn_indblkshift) {
1019 		uint64_t nbps = bp_span_in_blocks(dn->dn_indblkshift, 1);
1020 		chunksize = (nbps * 16) << dn->dn_datablkshift;
1021 		chunksize = MAX(chunksize, SPA_MAXBLOCKSIZE);
1022 	} else {
1023 		chunksize = dn->dn_datablksz;
1024 	}
1025 
1026 	while (size > 0) {
1027 		uint64_t mylen = MIN(size, chunksize);
1028 
1029 		dmu_prefetch_wait_by_dnode(dn, offset, mylen);
1030 
1031 		offset += mylen;
1032 		size -= mylen;
1033 
1034 		if (issig()) {
1035 			err = SET_ERROR(EINTR);
1036 			break;
1037 		}
1038 	}
1039 
1040 	dnode_rele(dn, FTAG);
1041 
1042 	return (err);
1043 }
1044 
1045 /*
1046  * Issue prefetch I/Os for the given object's dnode.
1047  */
1048 void
dmu_prefetch_dnode(objset_t * os,uint64_t object,zio_priority_t pri)1049 dmu_prefetch_dnode(objset_t *os, uint64_t object, zio_priority_t pri)
1050 {
1051 	if (object == 0 || object >= DN_MAX_OBJECT)
1052 		return;
1053 
1054 	dnode_t *dn = DMU_META_DNODE(os);
1055 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
1056 	uint64_t blkid = dbuf_whichblock(dn, 0, object * sizeof (dnode_phys_t));
1057 	dbuf_prefetch(dn, 0, blkid, pri, 0);
1058 	rw_exit(&dn->dn_struct_rwlock);
1059 }
1060 
1061 /*
1062  * Advisory cache eviction for a byte range of an object.
1063  */
1064 void
dmu_evict_range(objset_t * os,uint64_t object,uint64_t offset,uint64_t len)1065 dmu_evict_range(objset_t *os, uint64_t object, uint64_t offset, uint64_t len)
1066 {
1067 	dnode_t *dn;
1068 
1069 	if (len == 0)
1070 		return;
1071 	if (dnode_hold(os, object, FTAG, &dn) != 0)
1072 		return;
1073 
1074 	/*
1075 	 * Exclude the last block if the range end is not block-aligned:
1076 	 * a sequential access may continue into that block.  The first
1077 	 * block is included even when partially covered since backwards
1078 	 * access patterns are rare.
1079 	 */
1080 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
1081 	uint64_t start, end;
1082 	if (dn->dn_datablkshift != 0) {
1083 		start = dbuf_whichblock(dn, 0, offset);
1084 		end = dbuf_whichblock(dn, 0, offset + len);
1085 	} else {
1086 		start = (offset >= dn->dn_datablksz);
1087 		end = (offset + len >= dn->dn_datablksz);
1088 	}
1089 	if (end > start)
1090 		dbuf_evict_range(dn, start, end - 1);
1091 	rw_exit(&dn->dn_struct_rwlock);
1092 
1093 	dnode_rele(dn, FTAG);
1094 }
1095 
1096 /*
1097  * Get the next "chunk" of file data to free.  We traverse the file from
1098  * the end so that the file gets shorter over time (if we crash in the
1099  * middle, this will leave us in a better state).  We find allocated file
1100  * data by simply searching the allocated level 1 indirects.
1101  *
1102  * On input, *start should be the first offset that does not need to be
1103  * freed (e.g. "offset + length").  On return, *start will be the first
1104  * offset that should be freed and l1blks is set to the number of level 1
1105  * indirect blocks found within the chunk.
1106  */
1107 static int
get_next_chunk(dnode_t * dn,uint64_t * start,uint64_t minimum,uint64_t * l1blks)1108 get_next_chunk(dnode_t *dn, uint64_t *start, uint64_t minimum, uint64_t *l1blks)
1109 {
1110 	uint64_t blks;
1111 	uint64_t maxblks = DMU_MAX_ACCESS >> (dn->dn_indblkshift + 1);
1112 	/* bytes of data covered by a level-1 indirect block */
1113 	uint64_t iblkrange = (uint64_t)dn->dn_datablksz *
1114 	    EPB(dn->dn_indblkshift, SPA_BLKPTRSHIFT);
1115 
1116 	ASSERT3U(minimum, <=, *start);
1117 
1118 	/* dn_nlevels == 1 means we don't have any L1 blocks */
1119 	if (dn->dn_nlevels <= 1) {
1120 		*l1blks = 0;
1121 		*start = minimum;
1122 		return (0);
1123 	}
1124 
1125 	/*
1126 	 * Check if we can free the entire range assuming that all of the
1127 	 * L1 blocks in this range have data. If we can, we use this
1128 	 * worst case value as an estimate so we can avoid having to look
1129 	 * at the object's actual data.
1130 	 */
1131 	uint64_t total_l1blks =
1132 	    (roundup(*start, iblkrange) - (minimum / iblkrange * iblkrange)) /
1133 	    iblkrange;
1134 	if (total_l1blks <= maxblks) {
1135 		*l1blks = total_l1blks;
1136 		*start = minimum;
1137 		return (0);
1138 	}
1139 	ASSERT(ISP2(iblkrange));
1140 
1141 	for (blks = 0; *start > minimum && blks < maxblks; blks++) {
1142 		int err;
1143 
1144 		/*
1145 		 * dnode_next_offset(BACKWARDS) will find an allocated L1
1146 		 * indirect block at or before the input offset.  We must
1147 		 * decrement *start so that it is at the end of the region
1148 		 * to search.
1149 		 */
1150 		(*start)--;
1151 
1152 		err = dnode_next_offset(dn,
1153 		    DNODE_FIND_BACKWARDS, start, 2, 1, 0);
1154 
1155 		/* if there are no indirect blocks before start, we are done */
1156 		if (err == ESRCH) {
1157 			*start = minimum;
1158 			break;
1159 		} else if (err != 0) {
1160 			*l1blks = blks;
1161 			return (err);
1162 		}
1163 
1164 		/* set start to the beginning of this L1 indirect */
1165 		*start = P2ALIGN_TYPED(*start, iblkrange, uint64_t);
1166 	}
1167 	if (*start < minimum)
1168 		*start = minimum;
1169 	*l1blks = blks;
1170 
1171 	return (0);
1172 }
1173 
1174 /*
1175  * If this objset is of type OST_ZFS return true if vfs's unmounted flag is set,
1176  * otherwise return false.
1177  * Used below in dmu_free_long_range_impl() to enable abort when unmounting
1178  */
1179 static boolean_t
dmu_objset_zfs_unmounting(objset_t * os)1180 dmu_objset_zfs_unmounting(objset_t *os)
1181 {
1182 #ifdef _KERNEL
1183 	if (dmu_objset_type(os) == DMU_OST_ZFS)
1184 		return (zfs_get_vfs_flag_unmounted(os));
1185 #else
1186 	(void) os;
1187 #endif
1188 	return (B_FALSE);
1189 }
1190 
1191 static int
dmu_free_long_range_impl(objset_t * os,dnode_t * dn,uint64_t offset,uint64_t length)1192 dmu_free_long_range_impl(objset_t *os, dnode_t *dn, uint64_t offset,
1193     uint64_t length)
1194 {
1195 	uint64_t object_size;
1196 	int err;
1197 	uint64_t dirty_frees_threshold;
1198 	dsl_pool_t *dp = dmu_objset_pool(os);
1199 
1200 	if (dn == NULL)
1201 		return (SET_ERROR(EINVAL));
1202 
1203 	object_size = (dn->dn_maxblkid + 1) * dn->dn_datablksz;
1204 	if (offset >= object_size)
1205 		return (0);
1206 
1207 	if (zfs_per_txg_dirty_frees_percent <= 100)
1208 		dirty_frees_threshold =
1209 		    zfs_per_txg_dirty_frees_percent * zfs_dirty_data_max / 100;
1210 	else
1211 		dirty_frees_threshold = zfs_dirty_data_max / 20;
1212 
1213 	if (length == DMU_OBJECT_END || offset + length > object_size)
1214 		length = object_size - offset;
1215 
1216 	while (length != 0) {
1217 		uint64_t chunk_end, chunk_begin, chunk_len;
1218 		uint64_t l1blks;
1219 		dmu_tx_t *tx;
1220 
1221 		if (dmu_objset_zfs_unmounting(dn->dn_objset))
1222 			return (SET_ERROR(EINTR));
1223 
1224 		chunk_end = chunk_begin = offset + length;
1225 
1226 		/* move chunk_begin backwards to the beginning of this chunk */
1227 		err = get_next_chunk(dn, &chunk_begin, offset, &l1blks);
1228 		if (err)
1229 			return (err);
1230 		ASSERT3U(chunk_begin, >=, offset);
1231 		ASSERT3U(chunk_begin, <=, chunk_end);
1232 
1233 		chunk_len = chunk_end - chunk_begin;
1234 
1235 		tx = dmu_tx_create(os);
1236 		dmu_tx_hold_free(tx, dn->dn_object, chunk_begin, chunk_len);
1237 
1238 		/*
1239 		 * Mark this transaction as typically resulting in a net
1240 		 * reduction in space used.
1241 		 */
1242 		dmu_tx_mark_netfree(tx);
1243 		err = dmu_tx_assign(tx, DMU_TX_WAIT);
1244 		if (err) {
1245 			dmu_tx_abort(tx);
1246 			return (err);
1247 		}
1248 
1249 		uint64_t txg = dmu_tx_get_txg(tx);
1250 
1251 		mutex_enter(&dp->dp_lock);
1252 		uint64_t long_free_dirty =
1253 		    dp->dp_long_free_dirty_pertxg[txg & TXG_MASK];
1254 		mutex_exit(&dp->dp_lock);
1255 
1256 		/*
1257 		 * To avoid filling up a TXG with just frees, wait for
1258 		 * the next TXG to open before freeing more chunks if
1259 		 * we have reached the threshold of frees.
1260 		 */
1261 		if (dirty_frees_threshold != 0 &&
1262 		    long_free_dirty >= dirty_frees_threshold) {
1263 			DMU_TX_STAT_BUMP(dmu_tx_dirty_frees_delay);
1264 			dmu_tx_commit(tx);
1265 			txg_wait_open(dp, 0, B_TRUE);
1266 			continue;
1267 		}
1268 
1269 		/*
1270 		 * In order to prevent unnecessary write throttling, for each
1271 		 * TXG, we track the cumulative size of L1 blocks being dirtied
1272 		 * in dnode_free_range() below. We compare this number to a
1273 		 * tunable threshold, past which we prevent new L1 dirty freeing
1274 		 * blocks from being added into the open TXG. See
1275 		 * dmu_free_long_range_impl() for details. The threshold
1276 		 * prevents write throttle activation due to dirty freeing L1
1277 		 * blocks taking up a large percentage of zfs_dirty_data_max.
1278 		 */
1279 		mutex_enter(&dp->dp_lock);
1280 		dp->dp_long_free_dirty_pertxg[txg & TXG_MASK] +=
1281 		    l1blks << dn->dn_indblkshift;
1282 		mutex_exit(&dp->dp_lock);
1283 		DTRACE_PROBE3(free__long__range,
1284 		    uint64_t, long_free_dirty, uint64_t, chunk_len,
1285 		    uint64_t, txg);
1286 		dnode_free_range(dn, chunk_begin, chunk_len, tx);
1287 
1288 		dmu_tx_commit(tx);
1289 
1290 		length -= chunk_len;
1291 	}
1292 	return (0);
1293 }
1294 
1295 int
dmu_free_long_range(objset_t * os,uint64_t object,uint64_t offset,uint64_t length)1296 dmu_free_long_range(objset_t *os, uint64_t object,
1297     uint64_t offset, uint64_t length)
1298 {
1299 	dnode_t *dn;
1300 	int err;
1301 
1302 	err = dnode_hold(os, object, FTAG, &dn);
1303 	if (err != 0)
1304 		return (err);
1305 	err = dmu_free_long_range_impl(os, dn, offset, length);
1306 
1307 	/*
1308 	 * It is important to zero out the maxblkid when freeing the entire
1309 	 * file, so that (a) subsequent calls to dmu_free_long_range_impl()
1310 	 * will take the fast path, and (b) dnode_reallocate() can verify
1311 	 * that the entire file has been freed.
1312 	 */
1313 	if (err == 0 && offset == 0 && length == DMU_OBJECT_END)
1314 		dn->dn_maxblkid = 0;
1315 
1316 	dnode_rele(dn, FTAG);
1317 	return (err);
1318 }
1319 
1320 int
dmu_free_long_object(objset_t * os,uint64_t object)1321 dmu_free_long_object(objset_t *os, uint64_t object)
1322 {
1323 	dmu_tx_t *tx;
1324 	int err;
1325 
1326 	err = dmu_free_long_range(os, object, 0, DMU_OBJECT_END);
1327 	if (err != 0)
1328 		return (err);
1329 
1330 	tx = dmu_tx_create(os);
1331 	dmu_tx_hold_bonus(tx, object);
1332 	dmu_tx_hold_free(tx, object, 0, DMU_OBJECT_END);
1333 	dmu_tx_mark_netfree(tx);
1334 	err = dmu_tx_assign(tx, DMU_TX_WAIT);
1335 	if (err == 0) {
1336 		err = dmu_object_free(os, object, tx);
1337 		dmu_tx_commit(tx);
1338 	} else {
1339 		dmu_tx_abort(tx);
1340 	}
1341 
1342 	return (err);
1343 }
1344 
1345 int
dmu_free_range(objset_t * os,uint64_t object,uint64_t offset,uint64_t size,dmu_tx_t * tx)1346 dmu_free_range(objset_t *os, uint64_t object, uint64_t offset,
1347     uint64_t size, dmu_tx_t *tx)
1348 {
1349 	dnode_t *dn;
1350 	int err = dnode_hold(os, object, FTAG, &dn);
1351 	if (err)
1352 		return (err);
1353 	ASSERT(offset < UINT64_MAX);
1354 	ASSERT(size == DMU_OBJECT_END || size <= UINT64_MAX - offset);
1355 	dnode_free_range(dn, offset, size, tx);
1356 	dnode_rele(dn, FTAG);
1357 	return (0);
1358 }
1359 
1360 static int
dmu_read_impl(dnode_t * dn,uint64_t offset,uint64_t size,void * buf,dmu_flags_t flags)1361 dmu_read_impl(dnode_t *dn, uint64_t offset, uint64_t size,
1362     void *buf, dmu_flags_t flags)
1363 {
1364 	dmu_buf_t **dbp;
1365 	int numbufs, err = 0;
1366 
1367 	/*
1368 	 * Deal with odd block sizes, where there can't be data past the first
1369 	 * block. If we ever do the tail block optimization, we will need to
1370 	 * handle that here as well.
1371 	 */
1372 	if (dn->dn_maxblkid == 0) {
1373 		uint64_t newsz = offset > dn->dn_datablksz ? 0 :
1374 		    MIN(size, dn->dn_datablksz - offset);
1375 		memset((char *)buf + newsz, 0, size - newsz);
1376 		size = newsz;
1377 	}
1378 
1379 	if (size == 0)
1380 		return (0);
1381 
1382 	/* Allow Direct I/O when requested and properly aligned */
1383 	if ((flags & DMU_DIRECTIO) && zfs_dio_page_aligned(buf) &&
1384 	    zfs_dio_aligned(offset, size, PAGESIZE)) {
1385 		abd_t *data = abd_get_from_buf(buf, size);
1386 		err = dmu_read_abd(dn, offset, size, data, flags);
1387 		abd_free(data);
1388 		return (err);
1389 	}
1390 	flags &= ~DMU_DIRECTIO;
1391 
1392 	while (size > 0) {
1393 		uint64_t mylen = MIN(size, DMU_MAX_ACCESS / 2);
1394 		int i;
1395 
1396 		/*
1397 		 * NB: we could do this block-at-a-time, but it's nice
1398 		 * to be reading in parallel.
1399 		 */
1400 		err = dmu_buf_hold_array_by_dnode(dn, offset, mylen,
1401 		    TRUE, FTAG, &numbufs, &dbp, flags);
1402 		if (err)
1403 			break;
1404 
1405 		for (i = 0; i < numbufs; i++) {
1406 			uint64_t tocpy;
1407 			int64_t bufoff;
1408 			dmu_buf_t *db = dbp[i];
1409 
1410 			ASSERT(size > 0);
1411 
1412 			bufoff = offset - db->db_offset;
1413 			tocpy = MIN(db->db_size - bufoff, size);
1414 
1415 			ASSERT(db->db_data != NULL);
1416 			(void) memcpy(buf, (char *)db->db_data + bufoff, tocpy);
1417 
1418 			offset += tocpy;
1419 			size -= tocpy;
1420 			buf = (char *)buf + tocpy;
1421 		}
1422 		dmu_buf_rele_array(dbp, numbufs, FTAG);
1423 	}
1424 	return (err);
1425 }
1426 
1427 int
dmu_read(objset_t * os,uint64_t object,uint64_t offset,uint64_t size,void * buf,dmu_flags_t flags)1428 dmu_read(objset_t *os, uint64_t object, uint64_t offset, uint64_t size,
1429     void *buf, dmu_flags_t flags)
1430 {
1431 	dnode_t *dn;
1432 	int err;
1433 
1434 	err = dnode_hold(os, object, FTAG, &dn);
1435 	if (err != 0)
1436 		return (err);
1437 
1438 	err = dmu_read_impl(dn, offset, size, buf, flags);
1439 	dnode_rele(dn, FTAG);
1440 	return (err);
1441 }
1442 
1443 int
dmu_read_by_dnode(dnode_t * dn,uint64_t offset,uint64_t size,void * buf,dmu_flags_t flags)1444 dmu_read_by_dnode(dnode_t *dn, uint64_t offset, uint64_t size, void *buf,
1445     dmu_flags_t flags)
1446 {
1447 	return (dmu_read_impl(dn, offset, size, buf, flags));
1448 }
1449 
1450 static void
dmu_write_impl(dmu_buf_t ** dbp,int numbufs,uint64_t offset,uint64_t size,const void * buf,dmu_tx_t * tx,dmu_flags_t flags)1451 dmu_write_impl(dmu_buf_t **dbp, int numbufs, uint64_t offset, uint64_t size,
1452     const void *buf, dmu_tx_t *tx, dmu_flags_t flags)
1453 {
1454 	int i;
1455 
1456 	for (i = 0; i < numbufs; i++) {
1457 		uint64_t tocpy;
1458 		int64_t bufoff;
1459 		dmu_buf_t *db = dbp[i];
1460 
1461 		ASSERT(size > 0);
1462 
1463 		bufoff = offset - db->db_offset;
1464 		tocpy = MIN(db->db_size - bufoff, size);
1465 
1466 		ASSERT(i == 0 || i == numbufs-1 || tocpy == db->db_size);
1467 
1468 		if (tocpy == db->db_size) {
1469 			dmu_buf_will_fill_flags(db, tx, B_FALSE, flags);
1470 		} else {
1471 			if (i == numbufs - 1 && bufoff + tocpy < db->db_size) {
1472 				if (bufoff == 0)
1473 					flags |= DMU_PARTIAL_FIRST;
1474 				else
1475 					flags |= DMU_PARTIAL_MORE;
1476 			}
1477 			dmu_buf_will_dirty_flags(db, tx, flags);
1478 		}
1479 
1480 		ASSERT(db->db_data != NULL);
1481 		(void) memcpy((char *)db->db_data + bufoff, buf, tocpy);
1482 
1483 		if (tocpy == db->db_size)
1484 			dmu_buf_fill_done(db, tx, B_FALSE);
1485 
1486 		offset += tocpy;
1487 		size -= tocpy;
1488 		buf = (char *)buf + tocpy;
1489 	}
1490 }
1491 
1492 void
dmu_write(objset_t * os,uint64_t object,uint64_t offset,uint64_t size,const void * buf,dmu_tx_t * tx,dmu_flags_t flags)1493 dmu_write(objset_t *os, uint64_t object, uint64_t offset, uint64_t size,
1494     const void *buf, dmu_tx_t *tx, dmu_flags_t flags)
1495 {
1496 	dmu_buf_t **dbp;
1497 	int numbufs;
1498 
1499 	if (size == 0)
1500 		return;
1501 
1502 	VERIFY0(dmu_buf_hold_array(os, object, offset, size,
1503 	    FALSE, FTAG, &numbufs, &dbp, flags));
1504 	dmu_write_impl(dbp, numbufs, offset, size, buf, tx, flags);
1505 	dmu_buf_rele_array(dbp, numbufs, FTAG);
1506 }
1507 
1508 int
dmu_write_by_dnode(dnode_t * dn,uint64_t offset,uint64_t size,const void * buf,dmu_tx_t * tx,dmu_flags_t flags)1509 dmu_write_by_dnode(dnode_t *dn, uint64_t offset, uint64_t size,
1510     const void *buf, dmu_tx_t *tx, dmu_flags_t flags)
1511 {
1512 	dmu_buf_t **dbp;
1513 	int numbufs;
1514 	int error;
1515 
1516 	if (size == 0)
1517 		return (0);
1518 
1519 	/* Allow Direct I/O when requested and properly aligned */
1520 	if ((flags & DMU_DIRECTIO) && zfs_dio_page_aligned((void *)buf) &&
1521 	    zfs_dio_aligned(offset, size, dn->dn_datablksz)) {
1522 		abd_t *data = abd_get_from_buf((void *)buf, size);
1523 		error = dmu_write_abd(dn, offset, size, data, flags, tx);
1524 		abd_free(data);
1525 		return (error);
1526 	}
1527 	flags &= ~DMU_DIRECTIO;
1528 
1529 	VERIFY0(dmu_buf_hold_array_by_dnode(dn, offset, size,
1530 	    FALSE, FTAG, &numbufs, &dbp, flags));
1531 	dmu_write_impl(dbp, numbufs, offset, size, buf, tx, flags);
1532 	dmu_buf_rele_array(dbp, numbufs, FTAG);
1533 	return (0);
1534 }
1535 
1536 void
dmu_prealloc(objset_t * os,uint64_t object,uint64_t offset,uint64_t size,dmu_tx_t * tx)1537 dmu_prealloc(objset_t *os, uint64_t object, uint64_t offset, uint64_t size,
1538     dmu_tx_t *tx)
1539 {
1540 	dmu_buf_t **dbp;
1541 	int numbufs, i;
1542 
1543 	if (size == 0)
1544 		return;
1545 
1546 	VERIFY0(dmu_buf_hold_array(os, object, offset, size,
1547 	    FALSE, FTAG, &numbufs, &dbp, DMU_READ_PREFETCH));
1548 
1549 	for (i = 0; i < numbufs; i++) {
1550 		dmu_buf_t *db = dbp[i];
1551 
1552 		dmu_buf_will_not_fill(db, tx);
1553 	}
1554 	dmu_buf_rele_array(dbp, numbufs, FTAG);
1555 }
1556 
1557 void
dmu_write_embedded(objset_t * os,uint64_t object,uint64_t offset,void * data,uint8_t etype,uint8_t comp,int uncompressed_size,int compressed_size,int byteorder,dmu_tx_t * tx)1558 dmu_write_embedded(objset_t *os, uint64_t object, uint64_t offset,
1559     void *data, uint8_t etype, uint8_t comp, int uncompressed_size,
1560     int compressed_size, int byteorder, dmu_tx_t *tx)
1561 {
1562 	dmu_buf_t *db;
1563 
1564 	ASSERT3U(etype, <, NUM_BP_EMBEDDED_TYPES);
1565 	ASSERT3U(comp, <, ZIO_COMPRESS_FUNCTIONS);
1566 	VERIFY0(dmu_buf_hold_noread(os, object, offset,
1567 	    FTAG, &db));
1568 
1569 	dmu_buf_write_embedded(db,
1570 	    data, (bp_embedded_type_t)etype, (enum zio_compress)comp,
1571 	    uncompressed_size, compressed_size, byteorder, tx);
1572 
1573 	dmu_buf_rele(db, FTAG);
1574 }
1575 
1576 void
dmu_redact(objset_t * os,uint64_t object,uint64_t offset,uint64_t size,dmu_tx_t * tx)1577 dmu_redact(objset_t *os, uint64_t object, uint64_t offset, uint64_t size,
1578     dmu_tx_t *tx)
1579 {
1580 	int numbufs, i;
1581 	dmu_buf_t **dbp;
1582 
1583 	VERIFY0(dmu_buf_hold_array(os, object, offset, size, FALSE, FTAG,
1584 	    &numbufs, &dbp, DMU_READ_PREFETCH));
1585 	for (i = 0; i < numbufs; i++)
1586 		dmu_buf_redact(dbp[i], tx);
1587 	dmu_buf_rele_array(dbp, numbufs, FTAG);
1588 }
1589 
1590 #ifdef _KERNEL
1591 int
dmu_read_uio_dnode(dnode_t * dn,zfs_uio_t * uio,uint64_t size,dmu_flags_t flags)1592 dmu_read_uio_dnode(dnode_t *dn, zfs_uio_t *uio, uint64_t size,
1593     dmu_flags_t flags)
1594 {
1595 	dmu_buf_t **dbp;
1596 	int numbufs, i, err;
1597 
1598 	if ((flags & DMU_DIRECTIO) && (uio->uio_extflg & UIO_DIRECT))
1599 		return (dmu_read_uio_direct(dn, uio, size, flags));
1600 	flags &= ~DMU_DIRECTIO;
1601 
1602 	/*
1603 	 * NB: we could do this block-at-a-time, but it's nice
1604 	 * to be reading in parallel.
1605 	 */
1606 	err = dmu_buf_hold_array_by_dnode(dn, zfs_uio_offset(uio), size,
1607 	    TRUE, FTAG, &numbufs, &dbp, flags);
1608 	if (err)
1609 		return (err);
1610 
1611 	for (i = 0; i < numbufs; i++) {
1612 		uint64_t tocpy;
1613 		int64_t bufoff;
1614 		dmu_buf_t *db = dbp[i];
1615 
1616 		ASSERT(size > 0);
1617 
1618 		bufoff = zfs_uio_offset(uio) - db->db_offset;
1619 		tocpy = MIN(db->db_size - bufoff, size);
1620 
1621 		ASSERT(db->db_data != NULL);
1622 		err = zfs_uio_fault_move((char *)db->db_data + bufoff, tocpy,
1623 		    UIO_READ, uio);
1624 
1625 		if (err)
1626 			break;
1627 
1628 		size -= tocpy;
1629 	}
1630 	dmu_buf_rele_array(dbp, numbufs, FTAG);
1631 
1632 	return (err);
1633 }
1634 
1635 /*
1636  * Read 'size' bytes into the uio buffer.
1637  * From object zdb->db_object.
1638  * Starting at zfs_uio_offset(uio).
1639  *
1640  * If the caller already has a dbuf in the target object
1641  * (e.g. its bonus buffer), this routine is faster than dmu_read_uio(),
1642  * because we don't have to find the dnode_t for the object.
1643  */
1644 int
dmu_read_uio_dbuf(dmu_buf_t * zdb,zfs_uio_t * uio,uint64_t size,dmu_flags_t flags)1645 dmu_read_uio_dbuf(dmu_buf_t *zdb, zfs_uio_t *uio, uint64_t size,
1646     dmu_flags_t flags)
1647 {
1648 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)zdb;
1649 	int err;
1650 
1651 	if (size == 0)
1652 		return (0);
1653 
1654 	DB_DNODE_ENTER(db);
1655 	err = dmu_read_uio_dnode(DB_DNODE(db), uio, size, flags);
1656 	DB_DNODE_EXIT(db);
1657 
1658 	return (err);
1659 }
1660 
1661 /*
1662  * Read 'size' bytes into the uio buffer.
1663  * From the specified object
1664  * Starting at offset zfs_uio_offset(uio).
1665  */
1666 int
dmu_read_uio(objset_t * os,uint64_t object,zfs_uio_t * uio,uint64_t size,dmu_flags_t flags)1667 dmu_read_uio(objset_t *os, uint64_t object, zfs_uio_t *uio, uint64_t size,
1668     dmu_flags_t flags)
1669 {
1670 	dnode_t *dn;
1671 	int err;
1672 
1673 	if (size == 0)
1674 		return (0);
1675 
1676 	err = dnode_hold(os, object, FTAG, &dn);
1677 	if (err)
1678 		return (err);
1679 
1680 	err = dmu_read_uio_dnode(dn, uio, size, flags);
1681 
1682 	dnode_rele(dn, FTAG);
1683 
1684 	return (err);
1685 }
1686 
1687 int
dmu_write_uio_dnode(dnode_t * dn,zfs_uio_t * uio,uint64_t size,dmu_tx_t * tx,dmu_flags_t flags)1688 dmu_write_uio_dnode(dnode_t *dn, zfs_uio_t *uio, uint64_t size, dmu_tx_t *tx,
1689     dmu_flags_t flags)
1690 {
1691 	dmu_buf_t **dbp;
1692 	int numbufs;
1693 	int err = 0;
1694 	uint64_t write_size;
1695 	dmu_flags_t oflags = flags;
1696 
1697 top:
1698 	write_size = size;
1699 
1700 	/*
1701 	 * We only allow Direct I/O writes to happen if we are block
1702 	 * sized aligned. Otherwise, we pass the write off to the ARC.
1703 	 */
1704 	if ((flags & DMU_DIRECTIO) && (uio->uio_extflg & UIO_DIRECT) &&
1705 	    (write_size >= dn->dn_datablksz)) {
1706 		if (zfs_dio_aligned(zfs_uio_offset(uio), write_size,
1707 		    dn->dn_datablksz)) {
1708 			return (dmu_write_uio_direct(dn, uio, size, flags, tx));
1709 		} else if (write_size > dn->dn_datablksz &&
1710 		    zfs_dio_offset_aligned(zfs_uio_offset(uio),
1711 		    dn->dn_datablksz)) {
1712 			write_size =
1713 			    dn->dn_datablksz * (write_size / dn->dn_datablksz);
1714 			err = dmu_write_uio_direct(dn, uio, write_size, flags,
1715 			    tx);
1716 			if (err == 0) {
1717 				size -= write_size;
1718 				goto top;
1719 			} else {
1720 				return (err);
1721 			}
1722 		} else {
1723 			write_size =
1724 			    P2PHASE(zfs_uio_offset(uio), dn->dn_datablksz);
1725 		}
1726 	}
1727 	flags &= ~DMU_DIRECTIO;
1728 
1729 	err = dmu_buf_hold_array_by_dnode(dn, zfs_uio_offset(uio), write_size,
1730 	    FALSE, FTAG, &numbufs, &dbp, flags);
1731 	if (err)
1732 		return (err);
1733 
1734 	for (int i = 0; i < numbufs; i++) {
1735 		uint64_t tocpy;
1736 		int64_t bufoff;
1737 		dmu_buf_t *db = dbp[i];
1738 
1739 		ASSERT(write_size > 0);
1740 
1741 		offset_t off = zfs_uio_offset(uio);
1742 		bufoff = off - db->db_offset;
1743 		tocpy = MIN(db->db_size - bufoff, write_size);
1744 
1745 		ASSERT(i == 0 || i == numbufs-1 || tocpy == db->db_size);
1746 
1747 		if (tocpy == db->db_size) {
1748 			dmu_buf_will_fill_flags(db, tx, B_TRUE, flags);
1749 		} else {
1750 			if (i == numbufs - 1 && bufoff + tocpy < db->db_size) {
1751 				if (bufoff == 0)
1752 					flags |= DMU_PARTIAL_FIRST;
1753 				else
1754 					flags |= DMU_PARTIAL_MORE;
1755 			}
1756 			dmu_buf_will_dirty_flags(db, tx, flags);
1757 		}
1758 
1759 		ASSERT(db->db_data != NULL);
1760 		err = zfs_uio_fault_move((char *)db->db_data + bufoff,
1761 		    tocpy, UIO_WRITE, uio);
1762 
1763 		if (tocpy == db->db_size && dmu_buf_fill_done(db, tx, err)) {
1764 			/* The fill was reverted.  Undo any uio progress. */
1765 			zfs_uio_advance(uio, off - zfs_uio_offset(uio));
1766 		}
1767 
1768 		if (err)
1769 			break;
1770 
1771 		write_size -= tocpy;
1772 		size -= tocpy;
1773 	}
1774 
1775 	IMPLY(err == 0, write_size == 0);
1776 
1777 	dmu_buf_rele_array(dbp, numbufs, FTAG);
1778 
1779 	if ((oflags & DMU_DIRECTIO) && (uio->uio_extflg & UIO_DIRECT) &&
1780 	    err == 0 && size > 0) {
1781 		flags = oflags;
1782 		goto top;
1783 	}
1784 	IMPLY(err == 0, size == 0);
1785 
1786 	return (err);
1787 }
1788 
1789 /*
1790  * Write 'size' bytes from the uio buffer.
1791  * To object zdb->db_object.
1792  * Starting at offset zfs_uio_offset(uio).
1793  *
1794  * If the caller already has a dbuf in the target object
1795  * (e.g. its bonus buffer), this routine is faster than dmu_write_uio(),
1796  * because we don't have to find the dnode_t for the object.
1797  */
1798 int
dmu_write_uio_dbuf(dmu_buf_t * zdb,zfs_uio_t * uio,uint64_t size,dmu_tx_t * tx,dmu_flags_t flags)1799 dmu_write_uio_dbuf(dmu_buf_t *zdb, zfs_uio_t *uio, uint64_t size,
1800     dmu_tx_t *tx, dmu_flags_t flags)
1801 {
1802 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)zdb;
1803 	int err;
1804 
1805 	if (size == 0)
1806 		return (0);
1807 
1808 	DB_DNODE_ENTER(db);
1809 	err = dmu_write_uio_dnode(DB_DNODE(db), uio, size, tx, flags);
1810 	DB_DNODE_EXIT(db);
1811 
1812 	return (err);
1813 }
1814 
1815 /*
1816  * Write 'size' bytes from the uio buffer.
1817  * To the specified object.
1818  * Starting at offset zfs_uio_offset(uio).
1819  */
1820 int
dmu_write_uio(objset_t * os,uint64_t object,zfs_uio_t * uio,uint64_t size,dmu_tx_t * tx,dmu_flags_t flags)1821 dmu_write_uio(objset_t *os, uint64_t object, zfs_uio_t *uio, uint64_t size,
1822     dmu_tx_t *tx, dmu_flags_t flags)
1823 {
1824 	dnode_t *dn;
1825 	int err;
1826 
1827 	if (size == 0)
1828 		return (0);
1829 
1830 	err = dnode_hold(os, object, FTAG, &dn);
1831 	if (err)
1832 		return (err);
1833 
1834 	err = dmu_write_uio_dnode(dn, uio, size, tx, flags);
1835 
1836 	dnode_rele(dn, FTAG);
1837 
1838 	return (err);
1839 }
1840 #endif /* _KERNEL */
1841 
1842 static void
dmu_cached_bps(spa_t * spa,blkptr_t * bps,uint_t nbps,uint64_t * l1sz,uint64_t * l2sz)1843 dmu_cached_bps(spa_t *spa, blkptr_t *bps, uint_t nbps,
1844     uint64_t *l1sz, uint64_t *l2sz)
1845 {
1846 	int cached_flags;
1847 
1848 	if (bps == NULL)
1849 		return;
1850 
1851 	for (size_t blk_off = 0; blk_off < nbps; blk_off++) {
1852 		blkptr_t *bp = &bps[blk_off];
1853 
1854 		if (BP_IS_HOLE(bp))
1855 			continue;
1856 
1857 		cached_flags = arc_cached(spa, bp);
1858 		if (cached_flags == 0)
1859 			continue;
1860 
1861 		if ((cached_flags & (ARC_CACHED_IN_L1 | ARC_CACHED_IN_L2)) ==
1862 		    ARC_CACHED_IN_L2)
1863 			*l2sz += BP_GET_LSIZE(bp);
1864 		else
1865 			*l1sz += BP_GET_LSIZE(bp);
1866 	}
1867 }
1868 
1869 /*
1870  * Estimate DMU object cached size.
1871  */
1872 int
dmu_object_cached_size(objset_t * os,uint64_t object,uint64_t * l1sz,uint64_t * l2sz)1873 dmu_object_cached_size(objset_t *os, uint64_t object,
1874     uint64_t *l1sz, uint64_t *l2sz)
1875 {
1876 	dnode_t *dn;
1877 	dmu_object_info_t doi;
1878 	int err = 0;
1879 
1880 	*l1sz = *l2sz = 0;
1881 
1882 	if (dnode_hold(os, object, FTAG, &dn) != 0)
1883 		return (0);
1884 
1885 	if (dn->dn_nlevels < 2) {
1886 		dnode_rele(dn, FTAG);
1887 		return (0);
1888 	}
1889 
1890 	dmu_object_info_from_dnode(dn, &doi);
1891 
1892 	for (uint64_t off = 0; off < doi.doi_max_offset &&
1893 	    dmu_prefetch_max > 0; off += dmu_prefetch_max) {
1894 		/* dbuf_read doesn't prefetch L1 blocks. */
1895 		dmu_prefetch_by_dnode(dn, 1, off,
1896 		    dmu_prefetch_max, ZIO_PRIORITY_SYNC_READ);
1897 	}
1898 
1899 	/*
1900 	 * Hold all valid L1 blocks, asking ARC the status of each BP
1901 	 * contained in each such L1 block.
1902 	 */
1903 	uint_t nbps = bp_span_in_blocks(dn->dn_indblkshift, 1);
1904 	uint64_t l1blks = 1 + (dn->dn_maxblkid / nbps);
1905 
1906 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
1907 	for (uint64_t blk = 0; blk < l1blks; blk++) {
1908 		dmu_buf_impl_t *db = NULL;
1909 
1910 		if (issig()) {
1911 			/*
1912 			 * On interrupt, get out, and bubble up EINTR
1913 			 */
1914 			err = EINTR;
1915 			break;
1916 		}
1917 
1918 		/*
1919 		 * If we get an i/o error here, the L1 can't be read,
1920 		 * and nothing under it could be cached, so we just
1921 		 * continue. Ignoring the error from dbuf_hold_impl
1922 		 * or from dbuf_read is then a reasonable choice.
1923 		 */
1924 		err = dbuf_hold_impl(dn, 1, blk, B_TRUE, B_FALSE, FTAG, &db);
1925 		if (err != 0) {
1926 			/*
1927 			 * ignore error and continue
1928 			 */
1929 			err = 0;
1930 			continue;
1931 		}
1932 
1933 		err = dbuf_read(db, NULL, DB_RF_CANFAIL);
1934 		if (err == 0) {
1935 			dmu_cached_bps(dmu_objset_spa(os), db->db.db_data,
1936 			    nbps, l1sz, l2sz);
1937 		}
1938 		/*
1939 		 * error may be ignored, and we continue
1940 		 */
1941 		err = 0;
1942 		dbuf_rele(db, FTAG);
1943 	}
1944 	rw_exit(&dn->dn_struct_rwlock);
1945 
1946 	dnode_rele(dn, FTAG);
1947 	return (err);
1948 }
1949 
1950 /*
1951  * Allocate a loaned anonymous arc buffer.
1952  */
1953 arc_buf_t *
dmu_request_arcbuf(dmu_buf_t * handle,int size)1954 dmu_request_arcbuf(dmu_buf_t *handle, int size)
1955 {
1956 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)handle;
1957 
1958 	return (arc_loan_buf(db->db_objset->os_spa, B_FALSE, size));
1959 }
1960 
1961 /*
1962  * Free a loaned arc buffer.
1963  */
1964 void
dmu_return_arcbuf(arc_buf_t * buf)1965 dmu_return_arcbuf(arc_buf_t *buf)
1966 {
1967 	arc_return_buf(buf, FTAG);
1968 	arc_buf_destroy(buf, FTAG);
1969 }
1970 
1971 /*
1972  * A "lightweight" write is faster than a regular write (e.g.
1973  * dmu_write_by_dnode() or dmu_assign_arcbuf_by_dnode()), because it avoids the
1974  * CPU cost of creating a dmu_buf_impl_t and arc_buf_[hdr_]_t.  However, the
1975  * data can not be read or overwritten until the transaction's txg has been
1976  * synced.  This makes it appropriate for workloads that are known to be
1977  * (temporarily) write-only, like "zfs receive".
1978  *
1979  * A single block is written, starting at the specified offset in bytes.  If
1980  * the call is successful, it returns 0 and the provided abd has been
1981  * consumed (the caller should not free it).
1982  */
1983 int
dmu_lightweight_write_by_dnode(dnode_t * dn,uint64_t offset,abd_t * abd,const zio_prop_t * zp,zio_flag_t flags,dmu_tx_t * tx)1984 dmu_lightweight_write_by_dnode(dnode_t *dn, uint64_t offset, abd_t *abd,
1985     const zio_prop_t *zp, zio_flag_t flags, dmu_tx_t *tx)
1986 {
1987 	dbuf_dirty_record_t *dr =
1988 	    dbuf_dirty_lightweight(dn, dbuf_whichblock(dn, 0, offset), tx);
1989 	if (dr == NULL)
1990 		return (SET_ERROR(EIO));
1991 	dr->dt.dll.dr_abd = abd;
1992 	dr->dt.dll.dr_props = *zp;
1993 	dr->dt.dll.dr_flags = flags;
1994 	return (0);
1995 }
1996 
1997 /*
1998  * When possible directly assign passed loaned arc buffer to a dbuf.
1999  * If this is not possible copy the contents of passed arc buf via
2000  * dmu_write().
2001  */
2002 int
dmu_assign_arcbuf_by_dnode(dnode_t * dn,uint64_t offset,arc_buf_t * buf,dmu_tx_t * tx,dmu_flags_t flags)2003 dmu_assign_arcbuf_by_dnode(dnode_t *dn, uint64_t offset, arc_buf_t *buf,
2004     dmu_tx_t *tx, dmu_flags_t flags)
2005 {
2006 	dmu_buf_impl_t *db;
2007 	objset_t *os = dn->dn_objset;
2008 	uint32_t blksz = (uint32_t)arc_buf_lsize(buf);
2009 	uint64_t blkid;
2010 
2011 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
2012 	blkid = dbuf_whichblock(dn, 0, offset);
2013 	db = dbuf_hold(dn, blkid, FTAG);
2014 	rw_exit(&dn->dn_struct_rwlock);
2015 	if (db == NULL)
2016 		return (SET_ERROR(EIO));
2017 
2018 	/*
2019 	 * We can only assign if the offset is aligned and the arc buf is the
2020 	 * same size as the dbuf.
2021 	 */
2022 	if (offset == db->db.db_offset && blksz == db->db.db_size) {
2023 		zfs_racct_write(os->os_spa, blksz, 1, flags);
2024 		dbuf_assign_arcbuf(db, buf, tx, flags);
2025 		dbuf_rele(db, FTAG);
2026 	} else {
2027 		/* compressed bufs must always be assignable to their dbuf */
2028 		ASSERT3U(arc_get_compression(buf), ==, ZIO_COMPRESS_OFF);
2029 		ASSERT(!(buf->b_flags & ARC_BUF_FLAG_COMPRESSED));
2030 
2031 		dbuf_rele(db, FTAG);
2032 		dmu_write_by_dnode(dn, offset, blksz, buf->b_data, tx, flags);
2033 		dmu_return_arcbuf(buf);
2034 	}
2035 
2036 	return (0);
2037 }
2038 
2039 int
dmu_assign_arcbuf_by_dbuf(dmu_buf_t * handle,uint64_t offset,arc_buf_t * buf,dmu_tx_t * tx,dmu_flags_t flags)2040 dmu_assign_arcbuf_by_dbuf(dmu_buf_t *handle, uint64_t offset, arc_buf_t *buf,
2041     dmu_tx_t *tx, dmu_flags_t flags)
2042 {
2043 	int err;
2044 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)handle;
2045 
2046 	DB_DNODE_ENTER(db);
2047 	err = dmu_assign_arcbuf_by_dnode(DB_DNODE(db), offset, buf, tx, flags);
2048 	DB_DNODE_EXIT(db);
2049 
2050 	return (err);
2051 }
2052 
2053 void
dmu_sync_ready(zio_t * zio,arc_buf_t * buf,void * varg)2054 dmu_sync_ready(zio_t *zio, arc_buf_t *buf, void *varg)
2055 {
2056 	(void) buf;
2057 	dmu_sync_arg_t *dsa = varg;
2058 
2059 	if (zio->io_error == 0) {
2060 		dbuf_dirty_record_t *dr = dsa->dsa_dr;
2061 		blkptr_t *bp = zio->io_bp;
2062 
2063 		if (BP_IS_HOLE(bp)) {
2064 			dmu_buf_t *db = NULL;
2065 			if (dr)
2066 				db = &(dr->dr_dbuf->db);
2067 			else
2068 				db = dsa->dsa_zgd->zgd_db;
2069 			/*
2070 			 * A block of zeros may compress to a hole, but the
2071 			 * block size still needs to be known for replay.
2072 			 */
2073 			BP_SET_LSIZE(bp, db->db_size);
2074 		} else if (!BP_IS_EMBEDDED(bp)) {
2075 			ASSERT0(BP_GET_LEVEL(bp));
2076 			BP_SET_FILL(bp, 1);
2077 		}
2078 	}
2079 }
2080 
2081 static void
dmu_sync_late_arrival_ready(zio_t * zio)2082 dmu_sync_late_arrival_ready(zio_t *zio)
2083 {
2084 	dmu_sync_ready(zio, NULL, zio->io_private);
2085 }
2086 
2087 void
dmu_sync_done(zio_t * zio,arc_buf_t * buf,void * varg)2088 dmu_sync_done(zio_t *zio, arc_buf_t *buf, void *varg)
2089 {
2090 	(void) buf;
2091 	dmu_sync_arg_t *dsa = varg;
2092 	dbuf_dirty_record_t *dr = dsa->dsa_dr;
2093 	dmu_buf_impl_t *db = dr->dr_dbuf;
2094 	zgd_t *zgd = dsa->dsa_zgd;
2095 
2096 	/*
2097 	 * Record the vdev(s) backing this blkptr so they can be flushed after
2098 	 * the writes for the lwb have completed.
2099 	 */
2100 	if (zgd && zio->io_error == 0) {
2101 		zil_lwb_add_block(zgd->zgd_lwb, zgd->zgd_bp);
2102 	}
2103 
2104 	mutex_enter(&db->db_mtx);
2105 	ASSERT(dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC);
2106 	if (zio->io_error == 0) {
2107 		ASSERT0(dr->dt.dl.dr_has_raw_params);
2108 		dr->dt.dl.dr_nopwrite = !!(zio->io_flags & ZIO_FLAG_NOPWRITE);
2109 		if (dr->dt.dl.dr_nopwrite) {
2110 			blkptr_t *bp = zio->io_bp;
2111 			blkptr_t *bp_orig = &zio->io_bp_orig;
2112 			uint8_t chksum = BP_GET_CHECKSUM(bp_orig);
2113 
2114 			ASSERT(BP_EQUAL(bp, bp_orig));
2115 			VERIFY(BP_EQUAL(bp, db->db_blkptr));
2116 			ASSERT(zio->io_prop.zp_compress != ZIO_COMPRESS_OFF);
2117 			VERIFY(zio_checksum_table[chksum].ci_flags &
2118 			    ZCHECKSUM_FLAG_NOPWRITE);
2119 		}
2120 		dr->dt.dl.dr_overridden_by = *zio->io_bp;
2121 		dr->dt.dl.dr_override_state = DR_OVERRIDDEN;
2122 		dr->dt.dl.dr_copies = zio->io_prop.zp_copies;
2123 		dr->dt.dl.dr_gang_copies = zio->io_prop.zp_gang_copies;
2124 
2125 		/*
2126 		 * Old style holes are filled with all zeros, whereas
2127 		 * new-style holes maintain their lsize, type, level,
2128 		 * and birth time (see zio_write_compress). While we
2129 		 * need to reset the BP_SET_LSIZE() call that happened
2130 		 * in dmu_sync_ready for old style holes, we do *not*
2131 		 * want to wipe out the information contained in new
2132 		 * style holes. Thus, only zero out the block pointer if
2133 		 * it's an old style hole.
2134 		 */
2135 		if (BP_IS_HOLE(&dr->dt.dl.dr_overridden_by) &&
2136 		    BP_GET_LOGICAL_BIRTH(&dr->dt.dl.dr_overridden_by) == 0)
2137 			BP_ZERO(&dr->dt.dl.dr_overridden_by);
2138 	} else {
2139 		dr->dt.dl.dr_override_state = DR_NOT_OVERRIDDEN;
2140 	}
2141 
2142 	cv_broadcast(&db->db_changed);
2143 	mutex_exit(&db->db_mtx);
2144 
2145 	if (dsa->dsa_done)
2146 		dsa->dsa_done(dsa->dsa_zgd, zio->io_error);
2147 
2148 	kmem_free(dsa, sizeof (*dsa));
2149 }
2150 
2151 static void
dmu_sync_late_arrival_done(zio_t * zio)2152 dmu_sync_late_arrival_done(zio_t *zio)
2153 {
2154 	blkptr_t *bp = zio->io_bp;
2155 	dmu_sync_arg_t *dsa = zio->io_private;
2156 	zgd_t *zgd = dsa->dsa_zgd;
2157 
2158 	if (zio->io_error == 0) {
2159 		/*
2160 		 * Record the vdev(s) backing this blkptr so they can be
2161 		 * flushed after the writes for the lwb have completed.
2162 		 */
2163 		zil_lwb_add_block(zgd->zgd_lwb, zgd->zgd_bp);
2164 
2165 		if (!BP_IS_HOLE(bp)) {
2166 			blkptr_t *bp_orig __maybe_unused = &zio->io_bp_orig;
2167 			ASSERT(!(zio->io_flags & ZIO_FLAG_NOPWRITE));
2168 			ASSERT(BP_IS_HOLE(bp_orig) || !BP_EQUAL(bp, bp_orig));
2169 			ASSERT(BP_GET_BIRTH(zio->io_bp) == zio->io_txg);
2170 			ASSERT(zio->io_txg > spa_syncing_txg(zio->io_spa));
2171 			zio_free(zio->io_spa, zio->io_txg, zio->io_bp);
2172 		}
2173 	}
2174 
2175 	dmu_tx_commit(dsa->dsa_tx);
2176 
2177 	dsa->dsa_done(dsa->dsa_zgd, zio->io_error);
2178 
2179 	abd_free(zio->io_abd);
2180 	kmem_free(dsa, sizeof (*dsa));
2181 }
2182 
2183 static int
dmu_sync_late_arrival(zio_t * pio,objset_t * os,dmu_sync_cb_t * done,zgd_t * zgd,zio_prop_t * zp,zbookmark_phys_t * zb)2184 dmu_sync_late_arrival(zio_t *pio, objset_t *os, dmu_sync_cb_t *done, zgd_t *zgd,
2185     zio_prop_t *zp, zbookmark_phys_t *zb)
2186 {
2187 	dmu_sync_arg_t *dsa;
2188 	dmu_tx_t *tx;
2189 	int error;
2190 
2191 	error = dbuf_read((dmu_buf_impl_t *)zgd->zgd_db, NULL,
2192 	    DB_RF_CANFAIL | DMU_READ_NO_PREFETCH | DMU_KEEP_CACHING);
2193 	if (error != 0)
2194 		return (error);
2195 
2196 	tx = dmu_tx_create(os);
2197 	dmu_tx_hold_space(tx, zgd->zgd_db->db_size);
2198 	/*
2199 	 * This transaction does not produce any dirty data or log blocks, so
2200 	 * it should not be throttled.  All other cases wait for TXG sync, by
2201 	 * which time the log block we are writing will be obsolete, so we can
2202 	 * skip waiting and just return error here instead.
2203 	 */
2204 	if (dmu_tx_assign(tx, DMU_TX_NOWAIT | DMU_TX_NOTHROTTLE) != 0) {
2205 		dmu_tx_abort(tx);
2206 		/* Make zl_get_data do txg_waited_synced() */
2207 		return (SET_ERROR(EIO));
2208 	}
2209 
2210 	/*
2211 	 * In order to prevent the zgd's lwb from being free'd prior to
2212 	 * dmu_sync_late_arrival_done() being called, we have to ensure
2213 	 * the lwb's "max txg" takes this tx's txg into account.
2214 	 */
2215 	zil_lwb_add_txg(zgd->zgd_lwb, dmu_tx_get_txg(tx));
2216 
2217 	dsa = kmem_alloc(sizeof (dmu_sync_arg_t), KM_SLEEP);
2218 	dsa->dsa_dr = NULL;
2219 	dsa->dsa_done = done;
2220 	dsa->dsa_zgd = zgd;
2221 	dsa->dsa_tx = tx;
2222 
2223 	/*
2224 	 * Since we are currently syncing this txg, it's nontrivial to
2225 	 * determine what BP to nopwrite against, so we disable nopwrite.
2226 	 *
2227 	 * When syncing, the db_blkptr is initially the BP of the previous
2228 	 * txg.  We can not nopwrite against it because it will be changed
2229 	 * (this is similar to the non-late-arrival case where the dbuf is
2230 	 * dirty in a future txg).
2231 	 *
2232 	 * Then dbuf_write_ready() sets bp_blkptr to the location we will write.
2233 	 * We can not nopwrite against it because although the BP will not
2234 	 * (typically) be changed, the data has not yet been persisted to this
2235 	 * location.
2236 	 *
2237 	 * Finally, when dbuf_write_done() is called, it is theoretically
2238 	 * possible to always nopwrite, because the data that was written in
2239 	 * this txg is the same data that we are trying to write.  However we
2240 	 * would need to check that this dbuf is not dirty in any future
2241 	 * txg's (as we do in the normal dmu_sync() path). For simplicity, we
2242 	 * don't nopwrite in this case.
2243 	 */
2244 	zp->zp_nopwrite = B_FALSE;
2245 
2246 	zio_nowait(zio_write(pio, os->os_spa, dmu_tx_get_txg(tx), zgd->zgd_bp,
2247 	    abd_get_from_buf(zgd->zgd_db->db_data, zgd->zgd_db->db_size),
2248 	    zgd->zgd_db->db_size, zgd->zgd_db->db_size, zp,
2249 	    dmu_sync_late_arrival_ready, NULL, dmu_sync_late_arrival_done,
2250 	    dsa, ZIO_PRIORITY_SYNC_WRITE, ZIO_FLAG_CANFAIL, zb));
2251 
2252 	return (0);
2253 }
2254 
2255 /*
2256  * Intent log support: sync the block associated with db to disk.
2257  * N.B. and XXX: the caller is responsible for making sure that the
2258  * data isn't changing while dmu_sync() is writing it.
2259  *
2260  * Return values:
2261  *
2262  *	EEXIST: this txg has already been synced, so there's nothing to do.
2263  *		The caller should not log the write.
2264  *
2265  *	ENOENT: the block was dbuf_free_range()'d, so there's nothing to do.
2266  *		The caller should not log the write.
2267  *
2268  *	EALREADY: this block is already in the process of being synced.
2269  *		The caller should track its progress (somehow).
2270  *
2271  *	EIO: could not do the I/O.
2272  *		The caller should do a txg_wait_synced().
2273  *
2274  *	0: the I/O has been initiated.
2275  *		The caller should log this blkptr in the done callback.
2276  *		It is possible that the I/O will fail, in which case
2277  *		the error will be reported to the done callback and
2278  *		propagated to pio from zio_done().
2279  */
2280 int
dmu_sync(zio_t * pio,uint64_t txg,dmu_sync_cb_t * done,zgd_t * zgd)2281 dmu_sync(zio_t *pio, uint64_t txg, dmu_sync_cb_t *done, zgd_t *zgd)
2282 {
2283 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)zgd->zgd_db;
2284 	objset_t *os = db->db_objset;
2285 	dsl_dataset_t *ds = os->os_dsl_dataset;
2286 	dbuf_dirty_record_t *dr, *dr_next;
2287 	dmu_sync_arg_t *dsa;
2288 	zbookmark_phys_t zb;
2289 	zio_prop_t zp;
2290 
2291 	ASSERT(pio != NULL);
2292 	ASSERT(txg != 0);
2293 
2294 	SET_BOOKMARK(&zb, ds->ds_object,
2295 	    db->db.db_object, db->db_level, db->db_blkid);
2296 
2297 	DB_DNODE_ENTER(db);
2298 	dmu_write_policy(os, DB_DNODE(db), db->db_level, WP_DMU_SYNC, &zp);
2299 	DB_DNODE_EXIT(db);
2300 
2301 	/*
2302 	 * If we're frozen (running ziltest), we always need to generate a bp.
2303 	 */
2304 	if (txg > spa_freeze_txg(os->os_spa))
2305 		return (dmu_sync_late_arrival(pio, os, done, zgd, &zp, &zb));
2306 
2307 	/*
2308 	 * Grabbing db_mtx now provides a barrier between dbuf_sync_leaf()
2309 	 * and us.  If we determine that this txg is not yet syncing,
2310 	 * but it begins to sync a moment later, that's OK because the
2311 	 * sync thread will block in dbuf_sync_leaf() until we drop db_mtx.
2312 	 */
2313 	mutex_enter(&db->db_mtx);
2314 
2315 	if (txg <= spa_last_synced_txg(os->os_spa)) {
2316 		/*
2317 		 * This txg has already synced.  There's nothing to do.
2318 		 */
2319 		mutex_exit(&db->db_mtx);
2320 		return (SET_ERROR(EEXIST));
2321 	}
2322 
2323 	if (txg <= spa_syncing_txg(os->os_spa)) {
2324 		/*
2325 		 * This txg is currently syncing, so we can't mess with
2326 		 * the dirty record anymore; just write a new log block.
2327 		 */
2328 		mutex_exit(&db->db_mtx);
2329 		return (dmu_sync_late_arrival(pio, os, done, zgd, &zp, &zb));
2330 	}
2331 
2332 	dr = dbuf_find_dirty_eq(db, txg);
2333 
2334 	if (dr == NULL) {
2335 		/*
2336 		 * There's no dr for this dbuf, so it must have been freed.
2337 		 * There's no need to log writes to freed blocks, so we're done.
2338 		 */
2339 		mutex_exit(&db->db_mtx);
2340 		return (SET_ERROR(ENOENT));
2341 	}
2342 
2343 	dr_next = list_next(&db->db_dirty_records, dr);
2344 	ASSERT(dr_next == NULL || dr_next->dr_txg < txg);
2345 
2346 	if (db->db_blkptr != NULL) {
2347 		/*
2348 		 * We need to fill in zgd_bp with the current blkptr so that
2349 		 * the nopwrite code can check if we're writing the same
2350 		 * data that's already on disk.  We can only nopwrite if we
2351 		 * are sure that after making the copy, db_blkptr will not
2352 		 * change until our i/o completes.  We ensure this by
2353 		 * holding the db_mtx, and only allowing nopwrite if the
2354 		 * block is not already dirty (see below).  This is verified
2355 		 * by dmu_sync_done(), which VERIFYs that the db_blkptr has
2356 		 * not changed.
2357 		 */
2358 		*zgd->zgd_bp = *db->db_blkptr;
2359 	}
2360 
2361 	/*
2362 	 * Assume the on-disk data is X, the current syncing data (in
2363 	 * txg - 1) is Y, and the current in-memory data is Z (currently
2364 	 * in dmu_sync).
2365 	 *
2366 	 * We usually want to perform a nopwrite if X and Z are the
2367 	 * same.  However, if Y is different (i.e. the BP is going to
2368 	 * change before this write takes effect), then a nopwrite will
2369 	 * be incorrect - we would override with X, which could have
2370 	 * been freed when Y was written.
2371 	 *
2372 	 * (Note that this is not a concern when we are nop-writing from
2373 	 * syncing context, because X and Y must be identical, because
2374 	 * all previous txgs have been synced.)
2375 	 *
2376 	 * Therefore, we disable nopwrite if the current BP could change
2377 	 * before this TXG.  There are two ways it could change: by
2378 	 * being dirty (dr_next is non-NULL), or by being freed
2379 	 * (dnode_block_freed()).  This behavior is verified by
2380 	 * zio_done(), which VERIFYs that the override BP is identical
2381 	 * to the on-disk BP.
2382 	 */
2383 	if (dr_next != NULL) {
2384 		zp.zp_nopwrite = B_FALSE;
2385 	} else {
2386 		DB_DNODE_ENTER(db);
2387 		if (dnode_block_freed(DB_DNODE(db), db->db_blkid))
2388 			zp.zp_nopwrite = B_FALSE;
2389 		DB_DNODE_EXIT(db);
2390 	}
2391 
2392 	ASSERT(dr->dr_txg == txg);
2393 	if (dr->dt.dl.dr_override_state == DR_IN_DMU_SYNC ||
2394 	    dr->dt.dl.dr_override_state == DR_OVERRIDDEN) {
2395 		/*
2396 		 * We have already issued a sync write for this buffer,
2397 		 * or this buffer has already been synced.  It could not
2398 		 * have been dirtied since, or we would have cleared the state.
2399 		 */
2400 		mutex_exit(&db->db_mtx);
2401 		return (SET_ERROR(EALREADY));
2402 	}
2403 
2404 	ASSERT0(dr->dt.dl.dr_has_raw_params);
2405 	ASSERT(dr->dt.dl.dr_override_state == DR_NOT_OVERRIDDEN);
2406 	dr->dt.dl.dr_override_state = DR_IN_DMU_SYNC;
2407 	mutex_exit(&db->db_mtx);
2408 
2409 	dsa = kmem_alloc(sizeof (dmu_sync_arg_t), KM_SLEEP);
2410 	dsa->dsa_dr = dr;
2411 	dsa->dsa_done = done;
2412 	dsa->dsa_zgd = zgd;
2413 	dsa->dsa_tx = NULL;
2414 
2415 	zio_nowait(arc_write(pio, os->os_spa, txg, zgd->zgd_bp,
2416 	    dr->dt.dl.dr_data, !DBUF_IS_CACHEABLE(db),
2417 	    dbuf_is_l2cacheable(db, NULL), &zp, dmu_sync_ready, NULL,
2418 	    dmu_sync_done, dsa, ZIO_PRIORITY_SYNC_WRITE, ZIO_FLAG_CANFAIL,
2419 	    &zb));
2420 
2421 	return (0);
2422 }
2423 
2424 int
dmu_object_set_nlevels(objset_t * os,uint64_t object,int nlevels,dmu_tx_t * tx)2425 dmu_object_set_nlevels(objset_t *os, uint64_t object, int nlevels, dmu_tx_t *tx)
2426 {
2427 	dnode_t *dn;
2428 	int err;
2429 
2430 	err = dnode_hold(os, object, FTAG, &dn);
2431 	if (err)
2432 		return (err);
2433 	err = dnode_set_nlevels(dn, nlevels, tx);
2434 	dnode_rele(dn, FTAG);
2435 	return (err);
2436 }
2437 
2438 int
dmu_object_set_blocksize(objset_t * os,uint64_t object,uint64_t size,int ibs,dmu_tx_t * tx)2439 dmu_object_set_blocksize(objset_t *os, uint64_t object, uint64_t size, int ibs,
2440     dmu_tx_t *tx)
2441 {
2442 	dnode_t *dn;
2443 	int err;
2444 
2445 	err = dnode_hold(os, object, FTAG, &dn);
2446 	if (err)
2447 		return (err);
2448 	err = dnode_set_blksz(dn, size, ibs, tx);
2449 	dnode_rele(dn, FTAG);
2450 	return (err);
2451 }
2452 
2453 int
dmu_object_set_maxblkid(objset_t * os,uint64_t object,uint64_t maxblkid,dmu_tx_t * tx)2454 dmu_object_set_maxblkid(objset_t *os, uint64_t object, uint64_t maxblkid,
2455     dmu_tx_t *tx)
2456 {
2457 	dnode_t *dn;
2458 	int err;
2459 
2460 	err = dnode_hold(os, object, FTAG, &dn);
2461 	if (err)
2462 		return (err);
2463 	rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
2464 	dnode_new_blkid(dn, maxblkid, tx, B_FALSE, B_TRUE);
2465 	rw_exit(&dn->dn_struct_rwlock);
2466 	dnode_rele(dn, FTAG);
2467 	return (0);
2468 }
2469 
2470 void
dmu_object_set_checksum(objset_t * os,uint64_t object,uint8_t checksum,dmu_tx_t * tx)2471 dmu_object_set_checksum(objset_t *os, uint64_t object, uint8_t checksum,
2472     dmu_tx_t *tx)
2473 {
2474 	dnode_t *dn;
2475 
2476 	/*
2477 	 * Send streams include each object's checksum function.  This
2478 	 * check ensures that the receiving system can understand the
2479 	 * checksum function transmitted.
2480 	 */
2481 	ASSERT3U(checksum, <, ZIO_CHECKSUM_LEGACY_FUNCTIONS);
2482 
2483 	VERIFY0(dnode_hold(os, object, FTAG, &dn));
2484 	ASSERT3U(checksum, <, ZIO_CHECKSUM_FUNCTIONS);
2485 	dn->dn_checksum = checksum;
2486 	dnode_setdirty(dn, tx);
2487 	dnode_rele(dn, FTAG);
2488 }
2489 
2490 void
dmu_object_set_compress(objset_t * os,uint64_t object,uint8_t compress,dmu_tx_t * tx)2491 dmu_object_set_compress(objset_t *os, uint64_t object, uint8_t compress,
2492     dmu_tx_t *tx)
2493 {
2494 	dnode_t *dn;
2495 
2496 	/*
2497 	 * Send streams include each object's compression function.  This
2498 	 * check ensures that the receiving system can understand the
2499 	 * compression function transmitted.
2500 	 */
2501 	ASSERT3U(compress, <, ZIO_COMPRESS_LEGACY_FUNCTIONS);
2502 
2503 	VERIFY0(dnode_hold(os, object, FTAG, &dn));
2504 	dn->dn_compress = compress;
2505 	dnode_setdirty(dn, tx);
2506 	dnode_rele(dn, FTAG);
2507 }
2508 
2509 /*
2510  * When the "redundant_metadata" property is set to "most", only indirect
2511  * blocks of this level and higher will have an additional ditto block.
2512  */
2513 static const int zfs_redundant_metadata_most_ditto_level = 2;
2514 
2515 void
dmu_write_policy(objset_t * os,dnode_t * dn,int level,int wp,zio_prop_t * zp)2516 dmu_write_policy(objset_t *os, dnode_t *dn, int level, int wp, zio_prop_t *zp)
2517 {
2518 	dmu_object_type_t type = dn ? dn->dn_type : DMU_OT_OBJSET;
2519 	boolean_t ismd = (level > 0 || DMU_OT_IS_METADATA(type) ||
2520 	    (wp & WP_SPILL));
2521 	enum zio_checksum checksum = os->os_checksum;
2522 	enum zio_compress compress = os->os_compress;
2523 	uint8_t complevel = os->os_complevel;
2524 	enum zio_checksum dedup_checksum = os->os_dedup_checksum;
2525 	boolean_t dedup = B_FALSE;
2526 	boolean_t nopwrite = B_FALSE;
2527 	boolean_t dedup_verify = os->os_dedup_verify;
2528 	boolean_t encrypt = B_FALSE;
2529 	int copies = os->os_copies;
2530 	int gang_copies = os->os_copies;
2531 
2532 	/*
2533 	 * We maintain different write policies for each of the following
2534 	 * types of data:
2535 	 *	 1. metadata
2536 	 *	 2. preallocated blocks (i.e. level-0 blocks of a dump device)
2537 	 *	 3. all other level 0 blocks
2538 	 */
2539 	if (ismd) {
2540 		/*
2541 		 * XXX -- we should design a compression algorithm
2542 		 * that specializes in arrays of bps.
2543 		 */
2544 		compress = zio_compress_select(os->os_spa,
2545 		    ZIO_COMPRESS_ON, ZIO_COMPRESS_ON);
2546 
2547 		/*
2548 		 * Metadata always gets checksummed.  If the data
2549 		 * checksum is multi-bit correctable, and it's not a
2550 		 * ZBT-style checksum, then it's suitable for metadata
2551 		 * as well.  Otherwise, the metadata checksum defaults
2552 		 * to fletcher4.
2553 		 */
2554 		if (!(zio_checksum_table[checksum].ci_flags &
2555 		    ZCHECKSUM_FLAG_METADATA) ||
2556 		    (zio_checksum_table[checksum].ci_flags &
2557 		    ZCHECKSUM_FLAG_EMBEDDED))
2558 			checksum = ZIO_CHECKSUM_FLETCHER_4;
2559 
2560 		switch (os->os_redundant_metadata) {
2561 		case ZFS_REDUNDANT_METADATA_ALL:
2562 			copies++;
2563 			gang_copies++;
2564 			break;
2565 		case ZFS_REDUNDANT_METADATA_MOST:
2566 			if (level >= zfs_redundant_metadata_most_ditto_level ||
2567 			    DMU_OT_IS_METADATA(type) || (wp & WP_SPILL))
2568 				copies++;
2569 			if (level + 1 >=
2570 			    zfs_redundant_metadata_most_ditto_level ||
2571 			    DMU_OT_IS_METADATA(type) || (wp & WP_SPILL))
2572 				gang_copies++;
2573 			break;
2574 		case ZFS_REDUNDANT_METADATA_SOME:
2575 			if (DMU_OT_IS_CRITICAL(type, level)) {
2576 				copies++;
2577 				gang_copies++;
2578 			} else if (DMU_OT_IS_METADATA(type)) {
2579 				gang_copies++;
2580 			}
2581 			break;
2582 		case ZFS_REDUNDANT_METADATA_NONE:
2583 			break;
2584 		}
2585 
2586 		if (dmu_ddt_copies > 0) {
2587 			/*
2588 			 * If this tunable is set, and this is a write for a
2589 			 * dedup entry store (zap or log), then we treat it
2590 			 * something like ZFS_REDUNDANT_METADATA_MOST on a
2591 			 * regular dataset: this many copies, and one more for
2592 			 * "higher" indirect blocks. This specific exception is
2593 			 * necessary because dedup objects are stored in the
2594 			 * MOS, which always has the highest possible copies.
2595 			 */
2596 			dmu_object_type_t stype =
2597 			    dn ? dn->dn_storage_type : DMU_OT_NONE;
2598 			if (stype == DMU_OT_NONE)
2599 				stype = type;
2600 			if (stype == DMU_OT_DDT_ZAP) {
2601 				copies = dmu_ddt_copies;
2602 				if (level >=
2603 				    zfs_redundant_metadata_most_ditto_level)
2604 					copies++;
2605 			}
2606 		}
2607 	} else if (wp & WP_NOFILL) {
2608 		ASSERT0(level);
2609 
2610 		/*
2611 		 * If we're writing preallocated blocks, we aren't actually
2612 		 * writing them so don't set any policy properties.  These
2613 		 * blocks are currently only used by an external subsystem
2614 		 * outside of zfs (i.e. dump) and not written by the zio
2615 		 * pipeline.
2616 		 */
2617 		compress = ZIO_COMPRESS_OFF;
2618 		checksum = ZIO_CHECKSUM_OFF;
2619 	} else {
2620 		compress = zio_compress_select(os->os_spa, dn->dn_compress,
2621 		    compress);
2622 		complevel = zio_complevel_select(os->os_spa, compress,
2623 		    complevel, complevel);
2624 
2625 		/*
2626 		 * Storing many references to an all zeros block in the dedup
2627 		 * table would be expensive.  Instead, if dedup is enabled,
2628 		 * store them as holes even if compression is not enabled.
2629 		 */
2630 		if (compress == ZIO_COMPRESS_OFF &&
2631 		    dedup_checksum != ZIO_CHECKSUM_OFF)
2632 			compress = ZIO_COMPRESS_EMPTY;
2633 
2634 		checksum = (dedup_checksum == ZIO_CHECKSUM_OFF) ?
2635 		    zio_checksum_select(dn->dn_checksum, checksum) :
2636 		    dedup_checksum;
2637 
2638 		/*
2639 		 * Determine dedup setting.  If we are in dmu_sync(),
2640 		 * we won't actually dedup now because that's all
2641 		 * done in syncing context; but we do want to use the
2642 		 * dedup checksum.  If the checksum is not strong
2643 		 * enough to ensure unique signatures, force
2644 		 * dedup_verify.
2645 		 */
2646 		if (dedup_checksum != ZIO_CHECKSUM_OFF) {
2647 			dedup = (wp & WP_DMU_SYNC) ? B_FALSE : B_TRUE;
2648 			if (!(zio_checksum_table[checksum].ci_flags &
2649 			    ZCHECKSUM_FLAG_DEDUP))
2650 				dedup_verify = B_TRUE;
2651 		}
2652 
2653 		/*
2654 		 * Enable nopwrite if we have secure enough checksum
2655 		 * algorithm (see comment in zio_nop_write) and
2656 		 * compression is enabled.  We don't enable nopwrite if
2657 		 * dedup is enabled as the two features are mutually
2658 		 * exclusive.
2659 		 */
2660 		nopwrite = (!dedup && (zio_checksum_table[checksum].ci_flags &
2661 		    ZCHECKSUM_FLAG_NOPWRITE) &&
2662 		    compress != ZIO_COMPRESS_OFF && zfs_nopwrite_enabled);
2663 
2664 		if (os->os_redundant_metadata == ZFS_REDUNDANT_METADATA_ALL ||
2665 		    (os->os_redundant_metadata ==
2666 		    ZFS_REDUNDANT_METADATA_MOST &&
2667 		    zfs_redundant_metadata_most_ditto_level <= 1))
2668 			gang_copies++;
2669 	}
2670 
2671 	/*
2672 	 * All objects in an encrypted objset are protected from modification
2673 	 * via a MAC. Encrypted objects store their IV and salt in the last DVA
2674 	 * in the bp, so we cannot use all copies. Encrypted objects are also
2675 	 * not subject to nopwrite since writing the same data will still
2676 	 * result in a new ciphertext. Only encrypted blocks can be dedup'd
2677 	 * to avoid ambiguity in the dedup code since the DDT does not store
2678 	 * object types.
2679 	 */
2680 	if (os->os_encrypted && (wp & WP_NOFILL) == 0) {
2681 		encrypt = B_TRUE;
2682 
2683 		if (DMU_OT_IS_ENCRYPTED(type)) {
2684 			copies = MIN(copies, SPA_DVAS_PER_BP - 1);
2685 			gang_copies = MIN(gang_copies, SPA_DVAS_PER_BP - 1);
2686 			nopwrite = B_FALSE;
2687 		} else {
2688 			dedup = B_FALSE;
2689 		}
2690 
2691 		if (level <= 0 &&
2692 		    (type == DMU_OT_DNODE || type == DMU_OT_OBJSET)) {
2693 			compress = ZIO_COMPRESS_EMPTY;
2694 		}
2695 	}
2696 
2697 	zp->zp_compress = compress;
2698 	zp->zp_complevel = complevel;
2699 	zp->zp_checksum = checksum;
2700 	zp->zp_type = (wp & WP_SPILL) ? dn->dn_bonustype : type;
2701 	zp->zp_level = level;
2702 	zp->zp_copies = MIN(copies, spa_max_replication(os->os_spa));
2703 	zp->zp_gang_copies = MIN(MAX(gang_copies, copies),
2704 	    spa_max_replication(os->os_spa));
2705 	zp->zp_dedup = dedup;
2706 	zp->zp_dedup_verify = dedup && dedup_verify;
2707 	zp->zp_nopwrite = nopwrite;
2708 	zp->zp_encrypt = encrypt;
2709 	zp->zp_byteorder = ZFS_HOST_BYTEORDER;
2710 	zp->zp_direct_write = (wp & WP_DIRECT_WR) ? B_TRUE : B_FALSE;
2711 	zp->zp_rewrite = B_FALSE;
2712 	memset(zp->zp_salt, 0, ZIO_DATA_SALT_LEN);
2713 	memset(zp->zp_iv, 0, ZIO_DATA_IV_LEN);
2714 	memset(zp->zp_mac, 0, ZIO_DATA_MAC_LEN);
2715 	zp->zp_zpl_smallblk = os->os_zpl_special_smallblock;
2716 	zp->zp_storage_type = dn ? dn->dn_storage_type : DMU_OT_NONE;
2717 
2718 	ASSERT3U(zp->zp_compress, !=, ZIO_COMPRESS_INHERIT);
2719 }
2720 
2721 /*
2722  * Reports the location of data and holes in an object.  In order to
2723  * accurately report holes all dirty data must be synced to disk.  This
2724  * causes extremely poor performance when seeking for holes in a dirty file.
2725  * As a compromise, only provide hole data when the dnode is clean.  When
2726  * a dnode is dirty report the dnode as having no holes by returning EBUSY
2727  * which is always safe to do.
2728  */
2729 int
dmu_offset_next(objset_t * os,uint64_t object,boolean_t hole,uint64_t * off)2730 dmu_offset_next(objset_t *os, uint64_t object, boolean_t hole, uint64_t *off)
2731 {
2732 	dnode_t *dn;
2733 	uint64_t txg, maxtxg = 0;
2734 	int err;
2735 
2736 restart:
2737 	err = dnode_hold(os, object, FTAG, &dn);
2738 	if (err)
2739 		return (err);
2740 
2741 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
2742 
2743 	if (dnode_is_dirty(dn)) {
2744 		/*
2745 		 * If the zfs_dmu_offset_next_sync module option is enabled
2746 		 * then hole reporting has been requested.  Dirty dnodes
2747 		 * must be synced to disk to accurately report holes.
2748 		 *
2749 		 * Provided a RL_READER rangelock spanning 0-UINT64_MAX is
2750 		 * held by the caller only limited restarts will be required.
2751 		 * We tolerate callers which do not hold the rangelock by
2752 		 * returning EBUSY and not reporting holes after at most
2753 		 * TXG_CONCURRENT_STATES (3) restarts.
2754 		 */
2755 		if (zfs_dmu_offset_next_sync) {
2756 			rw_exit(&dn->dn_struct_rwlock);
2757 			dnode_rele(dn, FTAG);
2758 
2759 			if (maxtxg == 0) {
2760 				txg = spa_last_synced_txg(dmu_objset_spa(os));
2761 				maxtxg = txg + TXG_CONCURRENT_STATES;
2762 			} else if (txg >= maxtxg)
2763 				return (SET_ERROR(EBUSY));
2764 
2765 			txg_wait_synced(dmu_objset_pool(os), ++txg);
2766 			goto restart;
2767 		}
2768 
2769 		err = SET_ERROR(EBUSY);
2770 	} else {
2771 		err = dnode_next_offset(dn, DNODE_FIND_HAVELOCK |
2772 		    (hole ? DNODE_FIND_HOLE : 0), off, 1, 1, 0);
2773 	}
2774 
2775 	rw_exit(&dn->dn_struct_rwlock);
2776 	dnode_rele(dn, FTAG);
2777 
2778 	return (err);
2779 }
2780 
2781 int
dmu_read_l0_bps(objset_t * os,uint64_t object,uint64_t offset,uint64_t length,blkptr_t * bps,size_t * nbpsp)2782 dmu_read_l0_bps(objset_t *os, uint64_t object, uint64_t offset, uint64_t length,
2783     blkptr_t *bps, size_t *nbpsp)
2784 {
2785 	dmu_buf_t **dbp, *dbuf;
2786 	dmu_buf_impl_t *db;
2787 	blkptr_t *bp;
2788 	int error, numbufs;
2789 
2790 	error = dmu_buf_hold_array(os, object, offset, length, FALSE, FTAG,
2791 	    &numbufs, &dbp, DMU_READ_PREFETCH);
2792 	if (error != 0) {
2793 		if (error == ESRCH) {
2794 			error = SET_ERROR(ENXIO);
2795 		}
2796 		return (error);
2797 	}
2798 
2799 	ASSERT3U(numbufs, <=, *nbpsp);
2800 
2801 	for (int i = 0; i < numbufs; i++) {
2802 		dbuf = dbp[i];
2803 		db = (dmu_buf_impl_t *)dbuf;
2804 
2805 		mutex_enter(&db->db_mtx);
2806 
2807 		if (!list_is_empty(&db->db_dirty_records)) {
2808 			dbuf_dirty_record_t *dr;
2809 
2810 			dr = list_head(&db->db_dirty_records);
2811 			if (dr->dt.dl.dr_brtwrite) {
2812 				/*
2813 				 * This is very special case where we clone a
2814 				 * block and in the same transaction group we
2815 				 * read its BP (most likely to clone the clone).
2816 				 */
2817 				bp = &dr->dt.dl.dr_overridden_by;
2818 			} else {
2819 				/*
2820 				 * The block was modified in the same
2821 				 * transaction group.
2822 				 */
2823 				mutex_exit(&db->db_mtx);
2824 				error = SET_ERROR(EAGAIN);
2825 				goto out;
2826 			}
2827 		} else {
2828 			bp = db->db_blkptr;
2829 		}
2830 
2831 		mutex_exit(&db->db_mtx);
2832 
2833 		if (bp == NULL) {
2834 			/*
2835 			 * The file size was increased, but the block was never
2836 			 * written, otherwise we would either have the block
2837 			 * pointer or the dirty record and would not get here.
2838 			 * It is effectively a hole, so report it as such.
2839 			 */
2840 			BP_ZERO(&bps[i]);
2841 			continue;
2842 		}
2843 		/*
2844 		 * Make sure we clone only data blocks.
2845 		 */
2846 		if (BP_IS_METADATA(bp) && !BP_IS_HOLE(bp)) {
2847 			error = SET_ERROR(EINVAL);
2848 			goto out;
2849 		}
2850 
2851 		/*
2852 		 * If the block was allocated in transaction group that is not
2853 		 * yet synced, we could clone it, but we couldn't write this
2854 		 * operation into ZIL, or it may be impossible to replay, since
2855 		 * the block may appear not yet allocated at that point.
2856 		 */
2857 		if (BP_GET_PHYSICAL_BIRTH(bp) > spa_freeze_txg(os->os_spa)) {
2858 			error = SET_ERROR(EINVAL);
2859 			goto out;
2860 		}
2861 		if (BP_GET_PHYSICAL_BIRTH(bp) >
2862 		    spa_last_synced_txg(os->os_spa)) {
2863 			error = SET_ERROR(EAGAIN);
2864 			goto out;
2865 		}
2866 
2867 		bps[i] = *bp;
2868 	}
2869 
2870 	*nbpsp = numbufs;
2871 out:
2872 	dmu_buf_rele_array(dbp, numbufs, FTAG);
2873 
2874 	return (error);
2875 }
2876 
2877 int
dmu_brt_clone(objset_t * os,uint64_t object,uint64_t offset,uint64_t length,dmu_tx_t * tx,const blkptr_t * bps,size_t nbps)2878 dmu_brt_clone(objset_t *os, uint64_t object, uint64_t offset, uint64_t length,
2879     dmu_tx_t *tx, const blkptr_t *bps, size_t nbps)
2880 {
2881 	spa_t *spa;
2882 	dmu_buf_t **dbp, *dbuf;
2883 	dmu_buf_impl_t *db;
2884 	struct dirty_leaf *dl;
2885 	dbuf_dirty_record_t *dr;
2886 	const blkptr_t *bp;
2887 	int error = 0, i, numbufs;
2888 
2889 	spa = os->os_spa;
2890 
2891 	VERIFY0(dmu_buf_hold_array(os, object, offset, length, FALSE, FTAG,
2892 	    &numbufs, &dbp, DMU_READ_PREFETCH));
2893 	ASSERT3U(nbps, ==, numbufs);
2894 
2895 	/*
2896 	 * Before we start cloning make sure that the dbufs sizes match new BPs
2897 	 * sizes. If they don't, that's a no-go, as we are not able to shrink
2898 	 * dbufs.
2899 	 */
2900 	for (i = 0; i < numbufs; i++) {
2901 		dbuf = dbp[i];
2902 		db = (dmu_buf_impl_t *)dbuf;
2903 		bp = &bps[i];
2904 
2905 		ASSERT3U(db->db.db_object, !=, DMU_META_DNODE_OBJECT);
2906 		ASSERT0(db->db_level);
2907 		ASSERT(db->db_blkid != DMU_BONUS_BLKID);
2908 		ASSERT(db->db_blkid != DMU_SPILL_BLKID);
2909 
2910 		if (!BP_IS_HOLE(bp) && BP_GET_LSIZE(bp) != dbuf->db_size) {
2911 			error = SET_ERROR(EXDEV);
2912 			goto out;
2913 		}
2914 	}
2915 
2916 	for (i = 0; i < numbufs; i++) {
2917 		dbuf = dbp[i];
2918 		db = (dmu_buf_impl_t *)dbuf;
2919 		bp = &bps[i];
2920 
2921 		dmu_buf_will_clone_or_dio(dbuf, tx);
2922 
2923 		mutex_enter(&db->db_mtx);
2924 
2925 		dr = list_head(&db->db_dirty_records);
2926 		VERIFY(dr != NULL);
2927 		ASSERT3U(dr->dr_txg, ==, tx->tx_txg);
2928 		dl = &dr->dt.dl;
2929 		ASSERT0(dl->dr_has_raw_params);
2930 		dl->dr_overridden_by = *bp;
2931 		if (!BP_IS_HOLE(bp) || BP_GET_LOGICAL_BIRTH(bp) != 0) {
2932 			if (!BP_IS_EMBEDDED(bp)) {
2933 				BP_SET_BIRTH(&dl->dr_overridden_by, dr->dr_txg,
2934 				    BP_GET_PHYSICAL_BIRTH(bp));
2935 				BP_SET_REWRITE(&dl->dr_overridden_by, 0);
2936 			} else {
2937 				BP_SET_LOGICAL_BIRTH(&dl->dr_overridden_by,
2938 				    dr->dr_txg);
2939 			}
2940 		}
2941 		dl->dr_brtwrite = B_TRUE;
2942 		dl->dr_override_state = DR_OVERRIDDEN;
2943 
2944 		mutex_exit(&db->db_mtx);
2945 
2946 		/*
2947 		 * When data in embedded into BP there is no need to create
2948 		 * BRT entry as there is no data block. Just copy the BP as
2949 		 * it contains the data.
2950 		 */
2951 		if (!BP_IS_HOLE(bp) && !BP_IS_EMBEDDED(bp)) {
2952 			brt_pending_add(spa, bp, tx);
2953 		}
2954 	}
2955 out:
2956 	dmu_buf_rele_array(dbp, numbufs, FTAG);
2957 
2958 	return (error);
2959 }
2960 
2961 void
__dmu_object_info_from_dnode(dnode_t * dn,dmu_object_info_t * doi)2962 __dmu_object_info_from_dnode(dnode_t *dn, dmu_object_info_t *doi)
2963 {
2964 	dnode_phys_t *dnp = dn->dn_phys;
2965 
2966 	doi->doi_data_block_size = dn->dn_datablksz;
2967 	doi->doi_metadata_block_size = dn->dn_indblkshift ?
2968 	    1ULL << dn->dn_indblkshift : 0;
2969 	doi->doi_type = dn->dn_type;
2970 	doi->doi_bonus_type = dn->dn_bonustype;
2971 	doi->doi_bonus_size = dn->dn_bonuslen;
2972 	doi->doi_dnodesize = dn->dn_num_slots << DNODE_SHIFT;
2973 	doi->doi_indirection = dn->dn_nlevels;
2974 	doi->doi_checksum = dn->dn_checksum;
2975 	doi->doi_compress = dn->dn_compress;
2976 	doi->doi_nblkptr = dn->dn_nblkptr;
2977 	doi->doi_physical_blocks_512 = (DN_USED_BYTES(dnp) + 256) >> 9;
2978 	doi->doi_max_offset = (dn->dn_maxblkid + 1) * dn->dn_datablksz;
2979 	doi->doi_fill_count = 0;
2980 	for (int i = 0; i < dnp->dn_nblkptr; i++)
2981 		doi->doi_fill_count += BP_GET_FILL(&dnp->dn_blkptr[i]);
2982 }
2983 
2984 void
dmu_object_info_from_dnode(dnode_t * dn,dmu_object_info_t * doi)2985 dmu_object_info_from_dnode(dnode_t *dn, dmu_object_info_t *doi)
2986 {
2987 	rw_enter(&dn->dn_struct_rwlock, RW_READER);
2988 	mutex_enter(&dn->dn_mtx);
2989 
2990 	__dmu_object_info_from_dnode(dn, doi);
2991 
2992 	mutex_exit(&dn->dn_mtx);
2993 	rw_exit(&dn->dn_struct_rwlock);
2994 }
2995 
2996 /*
2997  * Get information on a DMU object.
2998  * If doi is NULL, just indicates whether the object exists.
2999  */
3000 int
dmu_object_info(objset_t * os,uint64_t object,dmu_object_info_t * doi)3001 dmu_object_info(objset_t *os, uint64_t object, dmu_object_info_t *doi)
3002 {
3003 	dnode_t *dn;
3004 	int err = dnode_hold(os, object, FTAG, &dn);
3005 
3006 	if (err)
3007 		return (err);
3008 
3009 	if (doi != NULL)
3010 		dmu_object_info_from_dnode(dn, doi);
3011 
3012 	dnode_rele(dn, FTAG);
3013 	return (0);
3014 }
3015 
3016 /*
3017  * As above, but faster; can be used when you have a held dbuf in hand.
3018  */
3019 void
dmu_object_info_from_db(dmu_buf_t * db_fake,dmu_object_info_t * doi)3020 dmu_object_info_from_db(dmu_buf_t *db_fake, dmu_object_info_t *doi)
3021 {
3022 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3023 
3024 	DB_DNODE_ENTER(db);
3025 	dmu_object_info_from_dnode(DB_DNODE(db), doi);
3026 	DB_DNODE_EXIT(db);
3027 }
3028 
3029 /*
3030  * Faster still when you only care about the size.
3031  */
3032 void
dmu_object_size_from_db(dmu_buf_t * db_fake,uint32_t * blksize,u_longlong_t * nblk512)3033 dmu_object_size_from_db(dmu_buf_t *db_fake, uint32_t *blksize,
3034     u_longlong_t *nblk512)
3035 {
3036 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3037 	dnode_t *dn;
3038 
3039 	DB_DNODE_ENTER(db);
3040 	dn = DB_DNODE(db);
3041 
3042 	*blksize = dn->dn_datablksz;
3043 	/* add in number of slots used for the dnode itself */
3044 	*nblk512 = ((DN_USED_BYTES(dn->dn_phys) + SPA_MINBLOCKSIZE/2) >>
3045 	    SPA_MINBLOCKSHIFT) + dn->dn_num_slots;
3046 	DB_DNODE_EXIT(db);
3047 }
3048 
3049 void
dmu_object_dnsize_from_db(dmu_buf_t * db_fake,int * dnsize)3050 dmu_object_dnsize_from_db(dmu_buf_t *db_fake, int *dnsize)
3051 {
3052 	dmu_buf_impl_t *db = (dmu_buf_impl_t *)db_fake;
3053 
3054 	DB_DNODE_ENTER(db);
3055 	*dnsize = DB_DNODE(db)->dn_num_slots << DNODE_SHIFT;
3056 	DB_DNODE_EXIT(db);
3057 }
3058 
3059 void
byteswap_uint64_array(void * vbuf,size_t size)3060 byteswap_uint64_array(void *vbuf, size_t size)
3061 {
3062 	uint64_t *buf = vbuf;
3063 	size_t count = size >> 3;
3064 	int i;
3065 
3066 	ASSERT0((size & 7));
3067 
3068 	for (i = 0; i < count; i++)
3069 		buf[i] = BSWAP_64(buf[i]);
3070 }
3071 
3072 void
byteswap_uint32_array(void * vbuf,size_t size)3073 byteswap_uint32_array(void *vbuf, size_t size)
3074 {
3075 	uint32_t *buf = vbuf;
3076 	size_t count = size >> 2;
3077 	int i;
3078 
3079 	ASSERT0((size & 3));
3080 
3081 	for (i = 0; i < count; i++)
3082 		buf[i] = BSWAP_32(buf[i]);
3083 }
3084 
3085 void
byteswap_uint16_array(void * vbuf,size_t size)3086 byteswap_uint16_array(void *vbuf, size_t size)
3087 {
3088 	uint16_t *buf = vbuf;
3089 	size_t count = size >> 1;
3090 	int i;
3091 
3092 	ASSERT0((size & 1));
3093 
3094 	for (i = 0; i < count; i++)
3095 		buf[i] = BSWAP_16(buf[i]);
3096 }
3097 
3098 void
byteswap_uint8_array(void * vbuf,size_t size)3099 byteswap_uint8_array(void *vbuf, size_t size)
3100 {
3101 	(void) vbuf, (void) size;
3102 }
3103 
3104 void
dmu_init(void)3105 dmu_init(void)
3106 {
3107 	abd_init();
3108 	zfs_dbgmsg_init();
3109 	sa_cache_init();
3110 	dmu_objset_init();
3111 	dnode_init();
3112 	zfetch_init();
3113 	dmu_tx_init();
3114 	l2arc_init();
3115 	arc_init();
3116 	dbuf_init();
3117 
3118 	dmu_ksp = kstat_create("zfs", 0, "dmustats", "misc",
3119 	    KSTAT_TYPE_NAMED,
3120 	    sizeof (dmu_stats) / sizeof (kstat_named_t),
3121 	    KSTAT_FLAG_VIRTUAL);
3122 	if (dmu_ksp != NULL) {
3123 		dmu_ksp->ks_data = &dmu_stats;
3124 		dmu_ksp->ks_update = dmu_kstats_update;
3125 		kstat_install(dmu_ksp);
3126 	}
3127 }
3128 
3129 void
dmu_fini(void)3130 dmu_fini(void)
3131 {
3132 	arc_fini(); /* arc depends on l2arc, so arc must go first */
3133 	l2arc_fini();
3134 	dmu_tx_fini();
3135 	zfetch_fini();
3136 	dbuf_fini();
3137 	dnode_fini();
3138 	dmu_objset_fini();
3139 	sa_cache_fini();
3140 	zfs_dbgmsg_fini();
3141 
3142 	if (dmu_ksp != NULL) {
3143 		kstat_delete(dmu_ksp);
3144 		dmu_ksp = NULL;
3145 	}
3146 	ASSERT0(atomic_load_64(&dmu_prefetch_bytes_active));
3147 
3148 	abd_fini();
3149 }
3150 
3151 EXPORT_SYMBOL(dmu_bonus_hold);
3152 EXPORT_SYMBOL(dmu_bonus_hold_by_dnode);
3153 EXPORT_SYMBOL(dmu_buf_hold_array_by_bonus);
3154 EXPORT_SYMBOL(dmu_buf_rele_array);
3155 EXPORT_SYMBOL(dmu_prefetch);
3156 EXPORT_SYMBOL(dmu_prefetch_by_dnode);
3157 EXPORT_SYMBOL(dmu_prefetch_dnode);
3158 EXPORT_SYMBOL(dmu_prefetch_stream);
3159 EXPORT_SYMBOL(dmu_prefetch_stream_by_dnode);
3160 EXPORT_SYMBOL(dmu_free_range);
3161 EXPORT_SYMBOL(dmu_free_long_range);
3162 EXPORT_SYMBOL(dmu_free_long_object);
3163 EXPORT_SYMBOL(dmu_read);
3164 EXPORT_SYMBOL(dmu_read_by_dnode);
3165 EXPORT_SYMBOL(dmu_read_uio);
3166 EXPORT_SYMBOL(dmu_read_uio_dbuf);
3167 EXPORT_SYMBOL(dmu_read_uio_dnode);
3168 EXPORT_SYMBOL(dmu_write);
3169 EXPORT_SYMBOL(dmu_write_by_dnode);
3170 EXPORT_SYMBOL(dmu_write_uio);
3171 EXPORT_SYMBOL(dmu_write_uio_dbuf);
3172 EXPORT_SYMBOL(dmu_write_uio_dnode);
3173 EXPORT_SYMBOL(dmu_prealloc);
3174 EXPORT_SYMBOL(dmu_object_info);
3175 EXPORT_SYMBOL(dmu_object_info_from_dnode);
3176 EXPORT_SYMBOL(dmu_object_info_from_db);
3177 EXPORT_SYMBOL(dmu_object_size_from_db);
3178 EXPORT_SYMBOL(dmu_object_dnsize_from_db);
3179 EXPORT_SYMBOL(dmu_object_set_nlevels);
3180 EXPORT_SYMBOL(dmu_object_set_blocksize);
3181 EXPORT_SYMBOL(dmu_object_set_maxblkid);
3182 EXPORT_SYMBOL(dmu_object_set_checksum);
3183 EXPORT_SYMBOL(dmu_object_set_compress);
3184 EXPORT_SYMBOL(dmu_offset_next);
3185 EXPORT_SYMBOL(dmu_write_policy);
3186 EXPORT_SYMBOL(dmu_sync);
3187 EXPORT_SYMBOL(dmu_request_arcbuf);
3188 EXPORT_SYMBOL(dmu_return_arcbuf);
3189 EXPORT_SYMBOL(dmu_assign_arcbuf_by_dnode);
3190 EXPORT_SYMBOL(dmu_assign_arcbuf_by_dbuf);
3191 EXPORT_SYMBOL(dmu_buf_hold);
3192 EXPORT_SYMBOL(dmu_ot);
3193 
3194 ZFS_MODULE_PARAM(zfs, zfs_, nopwrite_enabled, INT, ZMOD_RW,
3195 	"Enable NOP writes");
3196 
3197 ZFS_MODULE_PARAM(zfs, zfs_, per_txg_dirty_frees_percent, UINT, ZMOD_RW,
3198 	"Percentage of dirtied blocks from frees in one TXG");
3199 
3200 ZFS_MODULE_PARAM(zfs, zfs_, dmu_offset_next_sync, INT, ZMOD_RW,
3201 	"Enable forcing txg sync to find holes");
3202 
3203 ZFS_MODULE_PARAM(zfs, , dmu_prefetch_max, UINT, ZMOD_RW,
3204 	"Limit one prefetch call to this size");
3205 
3206 ZFS_MODULE_PARAM(zfs, , dmu_ddt_copies, UINT, ZMOD_RW,
3207 	"Override copies= for dedup objects");
3208