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