1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2012, 2016 by Delphix. All rights reserved.
24  * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
25  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
26  * Copyright (c) 2014 Spectra Logic Corporation, All rights reserved.
27  * Copyright 2015 Nexenta Systems, Inc. All rights reserved.
28  * Copyright (c) 2015, STRATO AG, Inc. All rights reserved.
29  * Copyright (c) 2014 Integros [integros.com]
30  */
31 
32 /* Portions Copyright 2010 Robert Milkowski */
33 
34 #include <sys/cred.h>
35 #include <sys/zfs_context.h>
36 #include <sys/dmu_objset.h>
37 #include <sys/dsl_dir.h>
38 #include <sys/dsl_dataset.h>
39 #include <sys/dsl_prop.h>
40 #include <sys/dsl_pool.h>
41 #include <sys/dsl_synctask.h>
42 #include <sys/dsl_deleg.h>
43 #include <sys/dnode.h>
44 #include <sys/dbuf.h>
45 #include <sys/zvol.h>
46 #include <sys/dmu_tx.h>
47 #include <sys/zap.h>
48 #include <sys/zil.h>
49 #include <sys/dmu_impl.h>
50 #include <sys/zfs_ioctl.h>
51 #include <sys/sa.h>
52 #include <sys/zfs_onexit.h>
53 #include <sys/dsl_destroy.h>
54 #include <sys/vdev.h>
55 
56 /*
57  * Needed to close a window in dnode_move() that allows the objset to be freed
58  * before it can be safely accessed.
59  */
60 krwlock_t os_lock;
61 
62 /*
63  * Tunable to overwrite the maximum number of threads for the parallization
64  * of dmu_objset_find_dp, needed to speed up the import of pools with many
65  * datasets.
66  * Default is 4 times the number of leaf vdevs.
67  */
68 int dmu_find_threads = 0;
69 
70 static void dmu_objset_find_dp_cb(void *arg);
71 
72 void
dmu_objset_init(void)73 dmu_objset_init(void)
74 {
75 	rw_init(&os_lock, NULL, RW_DEFAULT, NULL);
76 }
77 
78 void
dmu_objset_fini(void)79 dmu_objset_fini(void)
80 {
81 	rw_destroy(&os_lock);
82 }
83 
84 spa_t *
dmu_objset_spa(objset_t * os)85 dmu_objset_spa(objset_t *os)
86 {
87 	return (os->os_spa);
88 }
89 
90 zilog_t *
dmu_objset_zil(objset_t * os)91 dmu_objset_zil(objset_t *os)
92 {
93 	return (os->os_zil);
94 }
95 
96 dsl_pool_t *
dmu_objset_pool(objset_t * os)97 dmu_objset_pool(objset_t *os)
98 {
99 	dsl_dataset_t *ds;
100 
101 	if ((ds = os->os_dsl_dataset) != NULL && ds->ds_dir)
102 		return (ds->ds_dir->dd_pool);
103 	else
104 		return (spa_get_dsl(os->os_spa));
105 }
106 
107 dsl_dataset_t *
dmu_objset_ds(objset_t * os)108 dmu_objset_ds(objset_t *os)
109 {
110 	return (os->os_dsl_dataset);
111 }
112 
113 dmu_objset_type_t
dmu_objset_type(objset_t * os)114 dmu_objset_type(objset_t *os)
115 {
116 	return (os->os_phys->os_type);
117 }
118 
119 void
dmu_objset_name(objset_t * os,char * buf)120 dmu_objset_name(objset_t *os, char *buf)
121 {
122 	dsl_dataset_name(os->os_dsl_dataset, buf);
123 }
124 
125 uint64_t
dmu_objset_id(objset_t * os)126 dmu_objset_id(objset_t *os)
127 {
128 	dsl_dataset_t *ds = os->os_dsl_dataset;
129 
130 	return (ds ? ds->ds_object : 0);
131 }
132 
133 zfs_sync_type_t
dmu_objset_syncprop(objset_t * os)134 dmu_objset_syncprop(objset_t *os)
135 {
136 	return (os->os_sync);
137 }
138 
139 zfs_logbias_op_t
dmu_objset_logbias(objset_t * os)140 dmu_objset_logbias(objset_t *os)
141 {
142 	return (os->os_logbias);
143 }
144 
145 static void
checksum_changed_cb(void * arg,uint64_t newval)146 checksum_changed_cb(void *arg, uint64_t newval)
147 {
148 	objset_t *os = arg;
149 
150 	/*
151 	 * Inheritance should have been done by now.
152 	 */
153 	ASSERT(newval != ZIO_CHECKSUM_INHERIT);
154 
155 	os->os_checksum = zio_checksum_select(newval, ZIO_CHECKSUM_ON_VALUE);
156 }
157 
158 static void
compression_changed_cb(void * arg,uint64_t newval)159 compression_changed_cb(void *arg, uint64_t newval)
160 {
161 	objset_t *os = arg;
162 
163 	/*
164 	 * Inheritance and range checking should have been done by now.
165 	 */
166 	ASSERT(newval != ZIO_COMPRESS_INHERIT);
167 
168 	os->os_compress = zio_compress_select(os->os_spa, newval,
169 	    ZIO_COMPRESS_ON);
170 }
171 
172 static void
copies_changed_cb(void * arg,uint64_t newval)173 copies_changed_cb(void *arg, uint64_t newval)
174 {
175 	objset_t *os = arg;
176 
177 	/*
178 	 * Inheritance and range checking should have been done by now.
179 	 */
180 	ASSERT(newval > 0);
181 	ASSERT(newval <= spa_max_replication(os->os_spa));
182 
183 	os->os_copies = newval;
184 }
185 
186 static void
dedup_changed_cb(void * arg,uint64_t newval)187 dedup_changed_cb(void *arg, uint64_t newval)
188 {
189 	objset_t *os = arg;
190 	spa_t *spa = os->os_spa;
191 	enum zio_checksum checksum;
192 
193 	/*
194 	 * Inheritance should have been done by now.
195 	 */
196 	ASSERT(newval != ZIO_CHECKSUM_INHERIT);
197 
198 	checksum = zio_checksum_dedup_select(spa, newval, ZIO_CHECKSUM_OFF);
199 
200 	os->os_dedup_checksum = checksum & ZIO_CHECKSUM_MASK;
201 	os->os_dedup_verify = !!(checksum & ZIO_CHECKSUM_VERIFY);
202 }
203 
204 static void
primary_cache_changed_cb(void * arg,uint64_t newval)205 primary_cache_changed_cb(void *arg, uint64_t newval)
206 {
207 	objset_t *os = arg;
208 
209 	/*
210 	 * Inheritance and range checking should have been done by now.
211 	 */
212 	ASSERT(newval == ZFS_CACHE_ALL || newval == ZFS_CACHE_NONE ||
213 	    newval == ZFS_CACHE_METADATA);
214 
215 	os->os_primary_cache = newval;
216 }
217 
218 static void
secondary_cache_changed_cb(void * arg,uint64_t newval)219 secondary_cache_changed_cb(void *arg, uint64_t newval)
220 {
221 	objset_t *os = arg;
222 
223 	/*
224 	 * Inheritance and range checking should have been done by now.
225 	 */
226 	ASSERT(newval == ZFS_CACHE_ALL || newval == ZFS_CACHE_NONE ||
227 	    newval == ZFS_CACHE_METADATA);
228 
229 	os->os_secondary_cache = newval;
230 }
231 
232 static void
sync_changed_cb(void * arg,uint64_t newval)233 sync_changed_cb(void *arg, uint64_t newval)
234 {
235 	objset_t *os = arg;
236 
237 	/*
238 	 * Inheritance and range checking should have been done by now.
239 	 */
240 	ASSERT(newval == ZFS_SYNC_STANDARD || newval == ZFS_SYNC_ALWAYS ||
241 	    newval == ZFS_SYNC_DISABLED);
242 
243 	os->os_sync = newval;
244 	if (os->os_zil)
245 		zil_set_sync(os->os_zil, newval);
246 }
247 
248 static void
redundant_metadata_changed_cb(void * arg,uint64_t newval)249 redundant_metadata_changed_cb(void *arg, uint64_t newval)
250 {
251 	objset_t *os = arg;
252 
253 	/*
254 	 * Inheritance and range checking should have been done by now.
255 	 */
256 	ASSERT(newval == ZFS_REDUNDANT_METADATA_ALL ||
257 	    newval == ZFS_REDUNDANT_METADATA_MOST);
258 
259 	os->os_redundant_metadata = newval;
260 }
261 
262 static void
logbias_changed_cb(void * arg,uint64_t newval)263 logbias_changed_cb(void *arg, uint64_t newval)
264 {
265 	objset_t *os = arg;
266 
267 	ASSERT(newval == ZFS_LOGBIAS_LATENCY ||
268 	    newval == ZFS_LOGBIAS_THROUGHPUT);
269 	os->os_logbias = newval;
270 	if (os->os_zil)
271 		zil_set_logbias(os->os_zil, newval);
272 }
273 
274 static void
recordsize_changed_cb(void * arg,uint64_t newval)275 recordsize_changed_cb(void *arg, uint64_t newval)
276 {
277 	objset_t *os = arg;
278 
279 	os->os_recordsize = newval;
280 }
281 
282 void
dmu_objset_byteswap(void * buf,size_t size)283 dmu_objset_byteswap(void *buf, size_t size)
284 {
285 	objset_phys_t *osp = buf;
286 
287 	ASSERT(size == OBJSET_OLD_PHYS_SIZE || size == sizeof (objset_phys_t));
288 	dnode_byteswap(&osp->os_meta_dnode);
289 	byteswap_uint64_array(&osp->os_zil_header, sizeof (zil_header_t));
290 	osp->os_type = BSWAP_64(osp->os_type);
291 	osp->os_flags = BSWAP_64(osp->os_flags);
292 	if (size == sizeof (objset_phys_t)) {
293 		dnode_byteswap(&osp->os_userused_dnode);
294 		dnode_byteswap(&osp->os_groupused_dnode);
295 	}
296 }
297 
298 int
dmu_objset_open_impl(spa_t * spa,dsl_dataset_t * ds,blkptr_t * bp,objset_t ** osp)299 dmu_objset_open_impl(spa_t *spa, dsl_dataset_t *ds, blkptr_t *bp,
300     objset_t **osp)
301 {
302 	objset_t *os;
303 	int i, err;
304 
305 	ASSERT(ds == NULL || MUTEX_HELD(&ds->ds_opening_lock));
306 
307 	os = kmem_zalloc(sizeof (objset_t), KM_SLEEP);
308 	os->os_dsl_dataset = ds;
309 	os->os_spa = spa;
310 	os->os_rootbp = bp;
311 	if (!BP_IS_HOLE(os->os_rootbp)) {
312 		arc_flags_t aflags = ARC_FLAG_WAIT;
313 		zbookmark_phys_t zb;
314 		SET_BOOKMARK(&zb, ds ? ds->ds_object : DMU_META_OBJSET,
315 		    ZB_ROOT_OBJECT, ZB_ROOT_LEVEL, ZB_ROOT_BLKID);
316 
317 		if (DMU_OS_IS_L2CACHEABLE(os))
318 			aflags |= ARC_FLAG_L2CACHE;
319 
320 		dprintf_bp(os->os_rootbp, "reading %s", "");
321 		err = arc_read(NULL, spa, os->os_rootbp,
322 		    arc_getbuf_func, &os->os_phys_buf,
323 		    ZIO_PRIORITY_SYNC_READ, ZIO_FLAG_CANFAIL, &aflags, &zb);
324 		if (err != 0) {
325 			kmem_free(os, sizeof (objset_t));
326 			/* convert checksum errors into IO errors */
327 			if (err == ECKSUM)
328 				err = SET_ERROR(EIO);
329 			return (err);
330 		}
331 
332 		/* Increase the blocksize if we are permitted. */
333 		if (spa_version(spa) >= SPA_VERSION_USERSPACE &&
334 		    arc_buf_size(os->os_phys_buf) < sizeof (objset_phys_t)) {
335 			arc_buf_t *buf = arc_alloc_buf(spa,
336 			    sizeof (objset_phys_t), &os->os_phys_buf,
337 			    ARC_BUFC_METADATA);
338 			bzero(buf->b_data, sizeof (objset_phys_t));
339 			bcopy(os->os_phys_buf->b_data, buf->b_data,
340 			    arc_buf_size(os->os_phys_buf));
341 			arc_buf_destroy(os->os_phys_buf, &os->os_phys_buf);
342 			os->os_phys_buf = buf;
343 		}
344 
345 		os->os_phys = os->os_phys_buf->b_data;
346 		os->os_flags = os->os_phys->os_flags;
347 	} else {
348 		int size = spa_version(spa) >= SPA_VERSION_USERSPACE ?
349 		    sizeof (objset_phys_t) : OBJSET_OLD_PHYS_SIZE;
350 		os->os_phys_buf = arc_alloc_buf(spa, size,
351 		    &os->os_phys_buf, ARC_BUFC_METADATA);
352 		os->os_phys = os->os_phys_buf->b_data;
353 		bzero(os->os_phys, size);
354 	}
355 
356 	/*
357 	 * Note: the changed_cb will be called once before the register
358 	 * func returns, thus changing the checksum/compression from the
359 	 * default (fletcher2/off).  Snapshots don't need to know about
360 	 * checksum/compression/copies.
361 	 */
362 	if (ds != NULL) {
363 		boolean_t needlock = B_FALSE;
364 
365 		/*
366 		 * Note: it's valid to open the objset if the dataset is
367 		 * long-held, in which case the pool_config lock will not
368 		 * be held.
369 		 */
370 		if (!dsl_pool_config_held(dmu_objset_pool(os))) {
371 			needlock = B_TRUE;
372 			dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
373 		}
374 		err = dsl_prop_register(ds,
375 		    zfs_prop_to_name(ZFS_PROP_PRIMARYCACHE),
376 		    primary_cache_changed_cb, os);
377 		if (err == 0) {
378 			err = dsl_prop_register(ds,
379 			    zfs_prop_to_name(ZFS_PROP_SECONDARYCACHE),
380 			    secondary_cache_changed_cb, os);
381 		}
382 		if (!ds->ds_is_snapshot) {
383 			if (err == 0) {
384 				err = dsl_prop_register(ds,
385 				    zfs_prop_to_name(ZFS_PROP_CHECKSUM),
386 				    checksum_changed_cb, os);
387 			}
388 			if (err == 0) {
389 				err = dsl_prop_register(ds,
390 				    zfs_prop_to_name(ZFS_PROP_COMPRESSION),
391 				    compression_changed_cb, os);
392 			}
393 			if (err == 0) {
394 				err = dsl_prop_register(ds,
395 				    zfs_prop_to_name(ZFS_PROP_COPIES),
396 				    copies_changed_cb, os);
397 			}
398 			if (err == 0) {
399 				err = dsl_prop_register(ds,
400 				    zfs_prop_to_name(ZFS_PROP_DEDUP),
401 				    dedup_changed_cb, os);
402 			}
403 			if (err == 0) {
404 				err = dsl_prop_register(ds,
405 				    zfs_prop_to_name(ZFS_PROP_LOGBIAS),
406 				    logbias_changed_cb, os);
407 			}
408 			if (err == 0) {
409 				err = dsl_prop_register(ds,
410 				    zfs_prop_to_name(ZFS_PROP_SYNC),
411 				    sync_changed_cb, os);
412 			}
413 			if (err == 0) {
414 				err = dsl_prop_register(ds,
415 				    zfs_prop_to_name(
416 				    ZFS_PROP_REDUNDANT_METADATA),
417 				    redundant_metadata_changed_cb, os);
418 			}
419 			if (err == 0) {
420 				err = dsl_prop_register(ds,
421 				    zfs_prop_to_name(ZFS_PROP_RECORDSIZE),
422 				    recordsize_changed_cb, os);
423 			}
424 		}
425 		if (needlock)
426 			dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
427 		if (err != 0) {
428 			arc_buf_destroy(os->os_phys_buf, &os->os_phys_buf);
429 			kmem_free(os, sizeof (objset_t));
430 			return (err);
431 		}
432 	} else {
433 		/* It's the meta-objset. */
434 		os->os_checksum = ZIO_CHECKSUM_FLETCHER_4;
435 		os->os_compress = ZIO_COMPRESS_ON;
436 		os->os_copies = spa_max_replication(spa);
437 		os->os_dedup_checksum = ZIO_CHECKSUM_OFF;
438 		os->os_dedup_verify = B_FALSE;
439 		os->os_logbias = ZFS_LOGBIAS_LATENCY;
440 		os->os_sync = ZFS_SYNC_STANDARD;
441 		os->os_primary_cache = ZFS_CACHE_ALL;
442 		os->os_secondary_cache = ZFS_CACHE_ALL;
443 	}
444 
445 	if (ds == NULL || !ds->ds_is_snapshot)
446 		os->os_zil_header = os->os_phys->os_zil_header;
447 	os->os_zil = zil_alloc(os, &os->os_zil_header);
448 
449 	for (i = 0; i < TXG_SIZE; i++) {
450 		list_create(&os->os_dirty_dnodes[i], sizeof (dnode_t),
451 		    offsetof(dnode_t, dn_dirty_link[i]));
452 		list_create(&os->os_free_dnodes[i], sizeof (dnode_t),
453 		    offsetof(dnode_t, dn_dirty_link[i]));
454 	}
455 	list_create(&os->os_dnodes, sizeof (dnode_t),
456 	    offsetof(dnode_t, dn_link));
457 	list_create(&os->os_downgraded_dbufs, sizeof (dmu_buf_impl_t),
458 	    offsetof(dmu_buf_impl_t, db_link));
459 
460 	mutex_init(&os->os_lock, NULL, MUTEX_DEFAULT, NULL);
461 	mutex_init(&os->os_obj_lock, NULL, MUTEX_DEFAULT, NULL);
462 	mutex_init(&os->os_user_ptr_lock, NULL, MUTEX_DEFAULT, NULL);
463 
464 	dnode_special_open(os, &os->os_phys->os_meta_dnode,
465 	    DMU_META_DNODE_OBJECT, &os->os_meta_dnode);
466 	if (arc_buf_size(os->os_phys_buf) >= sizeof (objset_phys_t)) {
467 		dnode_special_open(os, &os->os_phys->os_userused_dnode,
468 		    DMU_USERUSED_OBJECT, &os->os_userused_dnode);
469 		dnode_special_open(os, &os->os_phys->os_groupused_dnode,
470 		    DMU_GROUPUSED_OBJECT, &os->os_groupused_dnode);
471 	}
472 
473 	*osp = os;
474 	return (0);
475 }
476 
477 int
dmu_objset_from_ds(dsl_dataset_t * ds,objset_t ** osp)478 dmu_objset_from_ds(dsl_dataset_t *ds, objset_t **osp)
479 {
480 	int err = 0;
481 
482 	/*
483 	 * We shouldn't be doing anything with dsl_dataset_t's unless the
484 	 * pool_config lock is held, or the dataset is long-held.
485 	 */
486 	ASSERT(dsl_pool_config_held(ds->ds_dir->dd_pool) ||
487 	    dsl_dataset_long_held(ds));
488 
489 	mutex_enter(&ds->ds_opening_lock);
490 	if (ds->ds_objset == NULL) {
491 		objset_t *os;
492 		rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
493 		err = dmu_objset_open_impl(dsl_dataset_get_spa(ds),
494 		    ds, dsl_dataset_get_blkptr(ds), &os);
495 		rrw_exit(&ds->ds_bp_rwlock, FTAG);
496 
497 		if (err == 0) {
498 			mutex_enter(&ds->ds_lock);
499 			ASSERT(ds->ds_objset == NULL);
500 			ds->ds_objset = os;
501 			mutex_exit(&ds->ds_lock);
502 		}
503 	}
504 	*osp = ds->ds_objset;
505 	mutex_exit(&ds->ds_opening_lock);
506 	return (err);
507 }
508 
509 /*
510  * Holds the pool while the objset is held.  Therefore only one objset
511  * can be held at a time.
512  */
513 int
dmu_objset_hold(const char * name,void * tag,objset_t ** osp)514 dmu_objset_hold(const char *name, void *tag, objset_t **osp)
515 {
516 	dsl_pool_t *dp;
517 	dsl_dataset_t *ds;
518 	int err;
519 
520 	err = dsl_pool_hold(name, tag, &dp);
521 	if (err != 0)
522 		return (err);
523 	err = dsl_dataset_hold(dp, name, tag, &ds);
524 	if (err != 0) {
525 		dsl_pool_rele(dp, tag);
526 		return (err);
527 	}
528 
529 	err = dmu_objset_from_ds(ds, osp);
530 	if (err != 0) {
531 		dsl_dataset_rele(ds, tag);
532 		dsl_pool_rele(dp, tag);
533 	}
534 
535 	return (err);
536 }
537 
538 static int
dmu_objset_own_impl(dsl_dataset_t * ds,dmu_objset_type_t type,boolean_t readonly,void * tag,objset_t ** osp)539 dmu_objset_own_impl(dsl_dataset_t *ds, dmu_objset_type_t type,
540     boolean_t readonly, void *tag, objset_t **osp)
541 {
542 	int err;
543 
544 	err = dmu_objset_from_ds(ds, osp);
545 	if (err != 0) {
546 		dsl_dataset_disown(ds, tag);
547 	} else if (type != DMU_OST_ANY && type != (*osp)->os_phys->os_type) {
548 		dsl_dataset_disown(ds, tag);
549 		return (SET_ERROR(EINVAL));
550 	} else if (!readonly && dsl_dataset_is_snapshot(ds)) {
551 		dsl_dataset_disown(ds, tag);
552 		return (SET_ERROR(EROFS));
553 	}
554 	return (err);
555 }
556 
557 /*
558  * dsl_pool must not be held when this is called.
559  * Upon successful return, there will be a longhold on the dataset,
560  * and the dsl_pool will not be held.
561  */
562 int
dmu_objset_own(const char * name,dmu_objset_type_t type,boolean_t readonly,void * tag,objset_t ** osp)563 dmu_objset_own(const char *name, dmu_objset_type_t type,
564     boolean_t readonly, void *tag, objset_t **osp)
565 {
566 	dsl_pool_t *dp;
567 	dsl_dataset_t *ds;
568 	int err;
569 
570 	err = dsl_pool_hold(name, FTAG, &dp);
571 	if (err != 0)
572 		return (err);
573 	err = dsl_dataset_own(dp, name, tag, &ds);
574 	if (err != 0) {
575 		dsl_pool_rele(dp, FTAG);
576 		return (err);
577 	}
578 	err = dmu_objset_own_impl(ds, type, readonly, tag, osp);
579 	dsl_pool_rele(dp, FTAG);
580 
581 	return (err);
582 }
583 
584 int
dmu_objset_own_obj(dsl_pool_t * dp,uint64_t obj,dmu_objset_type_t type,boolean_t readonly,void * tag,objset_t ** osp)585 dmu_objset_own_obj(dsl_pool_t *dp, uint64_t obj, dmu_objset_type_t type,
586     boolean_t readonly, void *tag, objset_t **osp)
587 {
588 	dsl_dataset_t *ds;
589 	int err;
590 
591 	err = dsl_dataset_own_obj(dp, obj, tag, &ds);
592 	if (err != 0)
593 		return (err);
594 
595 	return (dmu_objset_own_impl(ds, type, readonly, tag, osp));
596 }
597 
598 void
dmu_objset_rele(objset_t * os,void * tag)599 dmu_objset_rele(objset_t *os, void *tag)
600 {
601 	dsl_pool_t *dp = dmu_objset_pool(os);
602 	dsl_dataset_rele(os->os_dsl_dataset, tag);
603 	dsl_pool_rele(dp, tag);
604 }
605 
606 /*
607  * When we are called, os MUST refer to an objset associated with a dataset
608  * that is owned by 'tag'; that is, is held and long held by 'tag' and ds_owner
609  * == tag.  We will then release and reacquire ownership of the dataset while
610  * holding the pool config_rwlock to avoid intervening namespace or ownership
611  * changes may occur.
612  *
613  * This exists solely to accommodate zfs_ioc_userspace_upgrade()'s desire to
614  * release the hold on its dataset and acquire a new one on the dataset of the
615  * same name so that it can be partially torn down and reconstructed.
616  */
617 void
dmu_objset_refresh_ownership(objset_t * os,void * tag)618 dmu_objset_refresh_ownership(objset_t *os, void *tag)
619 {
620 	dsl_pool_t *dp;
621 	dsl_dataset_t *ds, *newds;
622 	char name[ZFS_MAX_DATASET_NAME_LEN];
623 
624 	ds = os->os_dsl_dataset;
625 	VERIFY3P(ds, !=, NULL);
626 	VERIFY3P(ds->ds_owner, ==, tag);
627 	VERIFY(dsl_dataset_long_held(ds));
628 
629 	dsl_dataset_name(ds, name);
630 	dp = dmu_objset_pool(os);
631 	dsl_pool_config_enter(dp, FTAG);
632 	dmu_objset_disown(os, tag);
633 	VERIFY0(dsl_dataset_own(dp, name, tag, &newds));
634 	VERIFY3P(newds, ==, os->os_dsl_dataset);
635 	dsl_pool_config_exit(dp, FTAG);
636 }
637 
638 void
dmu_objset_disown(objset_t * os,void * tag)639 dmu_objset_disown(objset_t *os, void *tag)
640 {
641 	dsl_dataset_disown(os->os_dsl_dataset, tag);
642 }
643 
644 void
dmu_objset_evict_dbufs(objset_t * os)645 dmu_objset_evict_dbufs(objset_t *os)
646 {
647 	dnode_t dn_marker;
648 	dnode_t *dn;
649 
650 	mutex_enter(&os->os_lock);
651 	dn = list_head(&os->os_dnodes);
652 	while (dn != NULL) {
653 		/*
654 		 * Skip dnodes without holds.  We have to do this dance
655 		 * because dnode_add_ref() only works if there is already a
656 		 * hold.  If the dnode has no holds, then it has no dbufs.
657 		 */
658 		if (dnode_add_ref(dn, FTAG)) {
659 			list_insert_after(&os->os_dnodes, dn, &dn_marker);
660 			mutex_exit(&os->os_lock);
661 
662 			dnode_evict_dbufs(dn);
663 			dnode_rele(dn, FTAG);
664 
665 			mutex_enter(&os->os_lock);
666 			dn = list_next(&os->os_dnodes, &dn_marker);
667 			list_remove(&os->os_dnodes, &dn_marker);
668 		} else {
669 			dn = list_next(&os->os_dnodes, dn);
670 		}
671 	}
672 	mutex_exit(&os->os_lock);
673 
674 	if (DMU_USERUSED_DNODE(os) != NULL) {
675 		dnode_evict_dbufs(DMU_GROUPUSED_DNODE(os));
676 		dnode_evict_dbufs(DMU_USERUSED_DNODE(os));
677 	}
678 	dnode_evict_dbufs(DMU_META_DNODE(os));
679 }
680 
681 /*
682  * Objset eviction processing is split into into two pieces.
683  * The first marks the objset as evicting, evicts any dbufs that
684  * have a refcount of zero, and then queues up the objset for the
685  * second phase of eviction.  Once os->os_dnodes has been cleared by
686  * dnode_buf_pageout()->dnode_destroy(), the second phase is executed.
687  * The second phase closes the special dnodes, dequeues the objset from
688  * the list of those undergoing eviction, and finally frees the objset.
689  *
690  * NOTE: Due to asynchronous eviction processing (invocation of
691  *       dnode_buf_pageout()), it is possible for the meta dnode for the
692  *       objset to have no holds even though os->os_dnodes is not empty.
693  */
694 void
dmu_objset_evict(objset_t * os)695 dmu_objset_evict(objset_t *os)
696 {
697 	dsl_dataset_t *ds = os->os_dsl_dataset;
698 
699 	for (int t = 0; t < TXG_SIZE; t++)
700 		ASSERT(!dmu_objset_is_dirty(os, t));
701 
702 	if (ds)
703 		dsl_prop_unregister_all(ds, os);
704 
705 	if (os->os_sa)
706 		sa_tear_down(os);
707 
708 	dmu_objset_evict_dbufs(os);
709 
710 	mutex_enter(&os->os_lock);
711 	spa_evicting_os_register(os->os_spa, os);
712 	if (list_is_empty(&os->os_dnodes)) {
713 		mutex_exit(&os->os_lock);
714 		dmu_objset_evict_done(os);
715 	} else {
716 		mutex_exit(&os->os_lock);
717 	}
718 }
719 
720 void
dmu_objset_evict_done(objset_t * os)721 dmu_objset_evict_done(objset_t *os)
722 {
723 	ASSERT3P(list_head(&os->os_dnodes), ==, NULL);
724 
725 	dnode_special_close(&os->os_meta_dnode);
726 	if (DMU_USERUSED_DNODE(os)) {
727 		dnode_special_close(&os->os_userused_dnode);
728 		dnode_special_close(&os->os_groupused_dnode);
729 	}
730 	zil_free(os->os_zil);
731 
732 	arc_buf_destroy(os->os_phys_buf, &os->os_phys_buf);
733 
734 	/*
735 	 * This is a barrier to prevent the objset from going away in
736 	 * dnode_move() until we can safely ensure that the objset is still in
737 	 * use. We consider the objset valid before the barrier and invalid
738 	 * after the barrier.
739 	 */
740 	rw_enter(&os_lock, RW_READER);
741 	rw_exit(&os_lock);
742 
743 	mutex_destroy(&os->os_lock);
744 	mutex_destroy(&os->os_obj_lock);
745 	mutex_destroy(&os->os_user_ptr_lock);
746 	spa_evicting_os_deregister(os->os_spa, os);
747 	kmem_free(os, sizeof (objset_t));
748 }
749 
750 timestruc_t
dmu_objset_snap_cmtime(objset_t * os)751 dmu_objset_snap_cmtime(objset_t *os)
752 {
753 	return (dsl_dir_snap_cmtime(os->os_dsl_dataset->ds_dir));
754 }
755 
756 /* called from dsl for meta-objset */
757 objset_t *
dmu_objset_create_impl(spa_t * spa,dsl_dataset_t * ds,blkptr_t * bp,dmu_objset_type_t type,dmu_tx_t * tx)758 dmu_objset_create_impl(spa_t *spa, dsl_dataset_t *ds, blkptr_t *bp,
759     dmu_objset_type_t type, dmu_tx_t *tx)
760 {
761 	objset_t *os;
762 	dnode_t *mdn;
763 
764 	ASSERT(dmu_tx_is_syncing(tx));
765 
766 	if (ds != NULL)
767 		VERIFY0(dmu_objset_from_ds(ds, &os));
768 	else
769 		VERIFY0(dmu_objset_open_impl(spa, NULL, bp, &os));
770 
771 	mdn = DMU_META_DNODE(os);
772 
773 	dnode_allocate(mdn, DMU_OT_DNODE, 1 << DNODE_BLOCK_SHIFT,
774 	    DN_MAX_INDBLKSHIFT, DMU_OT_NONE, 0, tx);
775 
776 	/*
777 	 * We don't want to have to increase the meta-dnode's nlevels
778 	 * later, because then we could do it in quescing context while
779 	 * we are also accessing it in open context.
780 	 *
781 	 * This precaution is not necessary for the MOS (ds == NULL),
782 	 * because the MOS is only updated in syncing context.
783 	 * This is most fortunate: the MOS is the only objset that
784 	 * needs to be synced multiple times as spa_sync() iterates
785 	 * to convergence, so minimizing its dn_nlevels matters.
786 	 */
787 	if (ds != NULL) {
788 		int levels = 1;
789 
790 		/*
791 		 * Determine the number of levels necessary for the meta-dnode
792 		 * to contain DN_MAX_OBJECT dnodes.  Note that in order to
793 		 * ensure that we do not overflow 64 bits, there has to be
794 		 * a nlevels that gives us a number of blocks > DN_MAX_OBJECT
795 		 * but < 2^64.  Therefore,
796 		 * (mdn->dn_indblkshift - SPA_BLKPTRSHIFT) (10) must be
797 		 * less than (64 - log2(DN_MAX_OBJECT)) (16).
798 		 */
799 		while ((uint64_t)mdn->dn_nblkptr <<
800 		    (mdn->dn_datablkshift - DNODE_SHIFT +
801 		    (levels - 1) * (mdn->dn_indblkshift - SPA_BLKPTRSHIFT)) <
802 		    DN_MAX_OBJECT)
803 			levels++;
804 
805 		mdn->dn_next_nlevels[tx->tx_txg & TXG_MASK] =
806 		    mdn->dn_nlevels = levels;
807 	}
808 
809 	ASSERT(type != DMU_OST_NONE);
810 	ASSERT(type != DMU_OST_ANY);
811 	ASSERT(type < DMU_OST_NUMTYPES);
812 	os->os_phys->os_type = type;
813 	if (dmu_objset_userused_enabled(os)) {
814 		os->os_phys->os_flags |= OBJSET_FLAG_USERACCOUNTING_COMPLETE;
815 		os->os_flags = os->os_phys->os_flags;
816 	}
817 
818 	dsl_dataset_dirty(ds, tx);
819 
820 	return (os);
821 }
822 
823 typedef struct dmu_objset_create_arg {
824 	const char *doca_name;
825 	cred_t *doca_cred;
826 	void (*doca_userfunc)(objset_t *os, void *arg,
827 	    cred_t *cr, dmu_tx_t *tx);
828 	void *doca_userarg;
829 	dmu_objset_type_t doca_type;
830 	uint64_t doca_flags;
831 } dmu_objset_create_arg_t;
832 
833 /*ARGSUSED*/
834 static int
dmu_objset_create_check(void * arg,dmu_tx_t * tx)835 dmu_objset_create_check(void *arg, dmu_tx_t *tx)
836 {
837 	dmu_objset_create_arg_t *doca = arg;
838 	dsl_pool_t *dp = dmu_tx_pool(tx);
839 	dsl_dir_t *pdd;
840 	const char *tail;
841 	int error;
842 
843 	if (strchr(doca->doca_name, '@') != NULL)
844 		return (SET_ERROR(EINVAL));
845 
846 	if (strlen(doca->doca_name) >= ZFS_MAX_DATASET_NAME_LEN)
847 		return (SET_ERROR(ENAMETOOLONG));
848 
849 	error = dsl_dir_hold(dp, doca->doca_name, FTAG, &pdd, &tail);
850 	if (error != 0)
851 		return (error);
852 	if (tail == NULL) {
853 		dsl_dir_rele(pdd, FTAG);
854 		return (SET_ERROR(EEXIST));
855 	}
856 	error = dsl_fs_ss_limit_check(pdd, 1, ZFS_PROP_FILESYSTEM_LIMIT, NULL,
857 	    doca->doca_cred);
858 	dsl_dir_rele(pdd, FTAG);
859 
860 	return (error);
861 }
862 
863 static void
dmu_objset_create_sync(void * arg,dmu_tx_t * tx)864 dmu_objset_create_sync(void *arg, dmu_tx_t *tx)
865 {
866 	dmu_objset_create_arg_t *doca = arg;
867 	dsl_pool_t *dp = dmu_tx_pool(tx);
868 	dsl_dir_t *pdd;
869 	const char *tail;
870 	dsl_dataset_t *ds;
871 	uint64_t obj;
872 	blkptr_t *bp;
873 	objset_t *os;
874 
875 	VERIFY0(dsl_dir_hold(dp, doca->doca_name, FTAG, &pdd, &tail));
876 
877 	obj = dsl_dataset_create_sync(pdd, tail, NULL, doca->doca_flags,
878 	    doca->doca_cred, tx);
879 
880 	VERIFY0(dsl_dataset_hold_obj(pdd->dd_pool, obj, FTAG, &ds));
881 	rrw_enter(&ds->ds_bp_rwlock, RW_READER, FTAG);
882 	bp = dsl_dataset_get_blkptr(ds);
883 	os = dmu_objset_create_impl(pdd->dd_pool->dp_spa,
884 	    ds, bp, doca->doca_type, tx);
885 	rrw_exit(&ds->ds_bp_rwlock, FTAG);
886 
887 	if (doca->doca_userfunc != NULL) {
888 		doca->doca_userfunc(os, doca->doca_userarg,
889 		    doca->doca_cred, tx);
890 	}
891 
892 	spa_history_log_internal_ds(ds, "create", tx, "");
893 	dsl_dataset_rele(ds, FTAG);
894 	dsl_dir_rele(pdd, FTAG);
895 }
896 
897 int
dmu_objset_create(const char * name,dmu_objset_type_t type,uint64_t flags,void (* func)(objset_t * os,void * arg,cred_t * cr,dmu_tx_t * tx),void * arg)898 dmu_objset_create(const char *name, dmu_objset_type_t type, uint64_t flags,
899     void (*func)(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx), void *arg)
900 {
901 	dmu_objset_create_arg_t doca;
902 
903 	doca.doca_name = name;
904 	doca.doca_cred = CRED();
905 	doca.doca_flags = flags;
906 	doca.doca_userfunc = func;
907 	doca.doca_userarg = arg;
908 	doca.doca_type = type;
909 
910 	return (dsl_sync_task(name,
911 	    dmu_objset_create_check, dmu_objset_create_sync, &doca,
912 	    5, ZFS_SPACE_CHECK_NORMAL));
913 }
914 
915 typedef struct dmu_objset_clone_arg {
916 	const char *doca_clone;
917 	const char *doca_origin;
918 	cred_t *doca_cred;
919 } dmu_objset_clone_arg_t;
920 
921 /*ARGSUSED*/
922 static int
dmu_objset_clone_check(void * arg,dmu_tx_t * tx)923 dmu_objset_clone_check(void *arg, dmu_tx_t *tx)
924 {
925 	dmu_objset_clone_arg_t *doca = arg;
926 	dsl_dir_t *pdd;
927 	const char *tail;
928 	int error;
929 	dsl_dataset_t *origin;
930 	dsl_pool_t *dp = dmu_tx_pool(tx);
931 
932 	if (strchr(doca->doca_clone, '@') != NULL)
933 		return (SET_ERROR(EINVAL));
934 
935 	if (strlen(doca->doca_clone) >= ZFS_MAX_DATASET_NAME_LEN)
936 		return (SET_ERROR(ENAMETOOLONG));
937 
938 	error = dsl_dir_hold(dp, doca->doca_clone, FTAG, &pdd, &tail);
939 	if (error != 0)
940 		return (error);
941 	if (tail == NULL) {
942 		dsl_dir_rele(pdd, FTAG);
943 		return (SET_ERROR(EEXIST));
944 	}
945 
946 	error = dsl_fs_ss_limit_check(pdd, 1, ZFS_PROP_FILESYSTEM_LIMIT, NULL,
947 	    doca->doca_cred);
948 	if (error != 0) {
949 		dsl_dir_rele(pdd, FTAG);
950 		return (SET_ERROR(EDQUOT));
951 	}
952 	dsl_dir_rele(pdd, FTAG);
953 
954 	error = dsl_dataset_hold(dp, doca->doca_origin, FTAG, &origin);
955 	if (error != 0)
956 		return (error);
957 
958 	/* You can only clone snapshots, not the head datasets. */
959 	if (!origin->ds_is_snapshot) {
960 		dsl_dataset_rele(origin, FTAG);
961 		return (SET_ERROR(EINVAL));
962 	}
963 	dsl_dataset_rele(origin, FTAG);
964 
965 	return (0);
966 }
967 
968 static void
dmu_objset_clone_sync(void * arg,dmu_tx_t * tx)969 dmu_objset_clone_sync(void *arg, dmu_tx_t *tx)
970 {
971 	dmu_objset_clone_arg_t *doca = arg;
972 	dsl_pool_t *dp = dmu_tx_pool(tx);
973 	dsl_dir_t *pdd;
974 	const char *tail;
975 	dsl_dataset_t *origin, *ds;
976 	uint64_t obj;
977 	char namebuf[ZFS_MAX_DATASET_NAME_LEN];
978 
979 	VERIFY0(dsl_dir_hold(dp, doca->doca_clone, FTAG, &pdd, &tail));
980 	VERIFY0(dsl_dataset_hold(dp, doca->doca_origin, FTAG, &origin));
981 
982 	obj = dsl_dataset_create_sync(pdd, tail, origin, 0,
983 	    doca->doca_cred, tx);
984 
985 	VERIFY0(dsl_dataset_hold_obj(pdd->dd_pool, obj, FTAG, &ds));
986 	dsl_dataset_name(origin, namebuf);
987 	spa_history_log_internal_ds(ds, "clone", tx,
988 	    "origin=%s (%llu)", namebuf, origin->ds_object);
989 	dsl_dataset_rele(ds, FTAG);
990 	dsl_dataset_rele(origin, FTAG);
991 	dsl_dir_rele(pdd, FTAG);
992 }
993 
994 int
dmu_objset_clone(const char * clone,const char * origin)995 dmu_objset_clone(const char *clone, const char *origin)
996 {
997 	dmu_objset_clone_arg_t doca;
998 
999 	doca.doca_clone = clone;
1000 	doca.doca_origin = origin;
1001 	doca.doca_cred = CRED();
1002 
1003 	return (dsl_sync_task(clone,
1004 	    dmu_objset_clone_check, dmu_objset_clone_sync, &doca,
1005 	    5, ZFS_SPACE_CHECK_NORMAL));
1006 }
1007 
1008 int
dmu_objset_snapshot_one(const char * fsname,const char * snapname)1009 dmu_objset_snapshot_one(const char *fsname, const char *snapname)
1010 {
1011 	int err;
1012 	char *longsnap = kmem_asprintf("%s@%s", fsname, snapname);
1013 	nvlist_t *snaps = fnvlist_alloc();
1014 
1015 	fnvlist_add_boolean(snaps, longsnap);
1016 	strfree(longsnap);
1017 	err = dsl_dataset_snapshot(snaps, NULL, NULL);
1018 	fnvlist_free(snaps);
1019 	return (err);
1020 }
1021 
1022 static void
dmu_objset_sync_dnodes(list_t * list,list_t * newlist,dmu_tx_t * tx)1023 dmu_objset_sync_dnodes(list_t *list, list_t *newlist, dmu_tx_t *tx)
1024 {
1025 	dnode_t *dn;
1026 
1027 	while (dn = list_head(list)) {
1028 		ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
1029 		ASSERT(dn->dn_dbuf->db_data_pending);
1030 		/*
1031 		 * Initialize dn_zio outside dnode_sync() because the
1032 		 * meta-dnode needs to set it ouside dnode_sync().
1033 		 */
1034 		dn->dn_zio = dn->dn_dbuf->db_data_pending->dr_zio;
1035 		ASSERT(dn->dn_zio);
1036 
1037 		ASSERT3U(dn->dn_nlevels, <=, DN_MAX_LEVELS);
1038 		list_remove(list, dn);
1039 
1040 		if (newlist) {
1041 			(void) dnode_add_ref(dn, newlist);
1042 			list_insert_tail(newlist, dn);
1043 		}
1044 
1045 		dnode_sync(dn, tx);
1046 	}
1047 }
1048 
1049 /* ARGSUSED */
1050 static void
dmu_objset_write_ready(zio_t * zio,arc_buf_t * abuf,void * arg)1051 dmu_objset_write_ready(zio_t *zio, arc_buf_t *abuf, void *arg)
1052 {
1053 	blkptr_t *bp = zio->io_bp;
1054 	objset_t *os = arg;
1055 	dnode_phys_t *dnp = &os->os_phys->os_meta_dnode;
1056 
1057 	ASSERT(!BP_IS_EMBEDDED(bp));
1058 	ASSERT3U(BP_GET_TYPE(bp), ==, DMU_OT_OBJSET);
1059 	ASSERT0(BP_GET_LEVEL(bp));
1060 
1061 	/*
1062 	 * Update rootbp fill count: it should be the number of objects
1063 	 * allocated in the object set (not counting the "special"
1064 	 * objects that are stored in the objset_phys_t -- the meta
1065 	 * dnode and user/group accounting objects).
1066 	 */
1067 	bp->blk_fill = 0;
1068 	for (int i = 0; i < dnp->dn_nblkptr; i++)
1069 		bp->blk_fill += BP_GET_FILL(&dnp->dn_blkptr[i]);
1070 	if (os->os_dsl_dataset != NULL)
1071 		rrw_enter(&os->os_dsl_dataset->ds_bp_rwlock, RW_WRITER, FTAG);
1072 	*os->os_rootbp = *bp;
1073 	if (os->os_dsl_dataset != NULL)
1074 		rrw_exit(&os->os_dsl_dataset->ds_bp_rwlock, FTAG);
1075 }
1076 
1077 /* ARGSUSED */
1078 static void
dmu_objset_write_done(zio_t * zio,arc_buf_t * abuf,void * arg)1079 dmu_objset_write_done(zio_t *zio, arc_buf_t *abuf, void *arg)
1080 {
1081 	blkptr_t *bp = zio->io_bp;
1082 	blkptr_t *bp_orig = &zio->io_bp_orig;
1083 	objset_t *os = arg;
1084 
1085 	if (zio->io_flags & ZIO_FLAG_IO_REWRITE) {
1086 		ASSERT(BP_EQUAL(bp, bp_orig));
1087 	} else {
1088 		dsl_dataset_t *ds = os->os_dsl_dataset;
1089 		dmu_tx_t *tx = os->os_synctx;
1090 
1091 		(void) dsl_dataset_block_kill(ds, bp_orig, tx, B_TRUE);
1092 		dsl_dataset_block_born(ds, bp, tx);
1093 	}
1094 	kmem_free(bp, sizeof (*bp));
1095 }
1096 
1097 /* called from dsl */
1098 void
dmu_objset_sync(objset_t * os,zio_t * pio,dmu_tx_t * tx)1099 dmu_objset_sync(objset_t *os, zio_t *pio, dmu_tx_t *tx)
1100 {
1101 	int txgoff;
1102 	zbookmark_phys_t zb;
1103 	zio_prop_t zp;
1104 	zio_t *zio;
1105 	list_t *list;
1106 	list_t *newlist = NULL;
1107 	dbuf_dirty_record_t *dr;
1108 	blkptr_t *blkptr_copy = kmem_alloc(sizeof (*os->os_rootbp), KM_SLEEP);
1109 	*blkptr_copy = *os->os_rootbp;
1110 
1111 	dprintf_ds(os->os_dsl_dataset, "txg=%llu\n", tx->tx_txg);
1112 
1113 	ASSERT(dmu_tx_is_syncing(tx));
1114 	/* XXX the write_done callback should really give us the tx... */
1115 	os->os_synctx = tx;
1116 
1117 	if (os->os_dsl_dataset == NULL) {
1118 		/*
1119 		 * This is the MOS.  If we have upgraded,
1120 		 * spa_max_replication() could change, so reset
1121 		 * os_copies here.
1122 		 */
1123 		os->os_copies = spa_max_replication(os->os_spa);
1124 	}
1125 
1126 	/*
1127 	 * Create the root block IO
1128 	 */
1129 	SET_BOOKMARK(&zb, os->os_dsl_dataset ?
1130 	    os->os_dsl_dataset->ds_object : DMU_META_OBJSET,
1131 	    ZB_ROOT_OBJECT, ZB_ROOT_LEVEL, ZB_ROOT_BLKID);
1132 	arc_release(os->os_phys_buf, &os->os_phys_buf);
1133 
1134 	dmu_write_policy(os, NULL, 0, 0, &zp);
1135 
1136 	zio = arc_write(pio, os->os_spa, tx->tx_txg,
1137 	    blkptr_copy, os->os_phys_buf, DMU_OS_IS_L2CACHEABLE(os),
1138 	    &zp, dmu_objset_write_ready, NULL, NULL, dmu_objset_write_done,
1139 	    os, ZIO_PRIORITY_ASYNC_WRITE, ZIO_FLAG_MUSTSUCCEED, &zb);
1140 
1141 	/*
1142 	 * Sync special dnodes - the parent IO for the sync is the root block
1143 	 */
1144 	DMU_META_DNODE(os)->dn_zio = zio;
1145 	dnode_sync(DMU_META_DNODE(os), tx);
1146 
1147 	os->os_phys->os_flags = os->os_flags;
1148 
1149 	if (DMU_USERUSED_DNODE(os) &&
1150 	    DMU_USERUSED_DNODE(os)->dn_type != DMU_OT_NONE) {
1151 		DMU_USERUSED_DNODE(os)->dn_zio = zio;
1152 		dnode_sync(DMU_USERUSED_DNODE(os), tx);
1153 		DMU_GROUPUSED_DNODE(os)->dn_zio = zio;
1154 		dnode_sync(DMU_GROUPUSED_DNODE(os), tx);
1155 	}
1156 
1157 	txgoff = tx->tx_txg & TXG_MASK;
1158 
1159 	if (dmu_objset_userused_enabled(os)) {
1160 		newlist = &os->os_synced_dnodes;
1161 		/*
1162 		 * We must create the list here because it uses the
1163 		 * dn_dirty_link[] of this txg.
1164 		 */
1165 		list_create(newlist, sizeof (dnode_t),
1166 		    offsetof(dnode_t, dn_dirty_link[txgoff]));
1167 	}
1168 
1169 	dmu_objset_sync_dnodes(&os->os_free_dnodes[txgoff], newlist, tx);
1170 	dmu_objset_sync_dnodes(&os->os_dirty_dnodes[txgoff], newlist, tx);
1171 
1172 	list = &DMU_META_DNODE(os)->dn_dirty_records[txgoff];
1173 	while (dr = list_head(list)) {
1174 		ASSERT0(dr->dr_dbuf->db_level);
1175 		list_remove(list, dr);
1176 		if (dr->dr_zio)
1177 			zio_nowait(dr->dr_zio);
1178 	}
1179 	/*
1180 	 * Free intent log blocks up to this tx.
1181 	 */
1182 	zil_sync(os->os_zil, tx);
1183 	os->os_phys->os_zil_header = os->os_zil_header;
1184 	zio_nowait(zio);
1185 }
1186 
1187 boolean_t
dmu_objset_is_dirty(objset_t * os,uint64_t txg)1188 dmu_objset_is_dirty(objset_t *os, uint64_t txg)
1189 {
1190 	return (!list_is_empty(&os->os_dirty_dnodes[txg & TXG_MASK]) ||
1191 	    !list_is_empty(&os->os_free_dnodes[txg & TXG_MASK]));
1192 }
1193 
1194 static objset_used_cb_t *used_cbs[DMU_OST_NUMTYPES];
1195 
1196 void
dmu_objset_register_type(dmu_objset_type_t ost,objset_used_cb_t * cb)1197 dmu_objset_register_type(dmu_objset_type_t ost, objset_used_cb_t *cb)
1198 {
1199 	used_cbs[ost] = cb;
1200 }
1201 
1202 boolean_t
dmu_objset_userused_enabled(objset_t * os)1203 dmu_objset_userused_enabled(objset_t *os)
1204 {
1205 	return (spa_version(os->os_spa) >= SPA_VERSION_USERSPACE &&
1206 	    used_cbs[os->os_phys->os_type] != NULL &&
1207 	    DMU_USERUSED_DNODE(os) != NULL);
1208 }
1209 
1210 typedef struct userquota_node {
1211 	uint64_t uqn_id;
1212 	int64_t uqn_delta;
1213 	avl_node_t uqn_node;
1214 } userquota_node_t;
1215 
1216 typedef struct userquota_cache {
1217 	avl_tree_t uqc_user_deltas;
1218 	avl_tree_t uqc_group_deltas;
1219 } userquota_cache_t;
1220 
1221 static int
userquota_compare(const void * l,const void * r)1222 userquota_compare(const void *l, const void *r)
1223 {
1224 	const userquota_node_t *luqn = l;
1225 	const userquota_node_t *ruqn = r;
1226 
1227 	if (luqn->uqn_id < ruqn->uqn_id)
1228 		return (-1);
1229 	if (luqn->uqn_id > ruqn->uqn_id)
1230 		return (1);
1231 	return (0);
1232 }
1233 
1234 static void
do_userquota_cacheflush(objset_t * os,userquota_cache_t * cache,dmu_tx_t * tx)1235 do_userquota_cacheflush(objset_t *os, userquota_cache_t *cache, dmu_tx_t *tx)
1236 {
1237 	void *cookie;
1238 	userquota_node_t *uqn;
1239 
1240 	ASSERT(dmu_tx_is_syncing(tx));
1241 
1242 	cookie = NULL;
1243 	while ((uqn = avl_destroy_nodes(&cache->uqc_user_deltas,
1244 	    &cookie)) != NULL) {
1245 		VERIFY0(zap_increment_int(os, DMU_USERUSED_OBJECT,
1246 		    uqn->uqn_id, uqn->uqn_delta, tx));
1247 		kmem_free(uqn, sizeof (*uqn));
1248 	}
1249 	avl_destroy(&cache->uqc_user_deltas);
1250 
1251 	cookie = NULL;
1252 	while ((uqn = avl_destroy_nodes(&cache->uqc_group_deltas,
1253 	    &cookie)) != NULL) {
1254 		VERIFY0(zap_increment_int(os, DMU_GROUPUSED_OBJECT,
1255 		    uqn->uqn_id, uqn->uqn_delta, tx));
1256 		kmem_free(uqn, sizeof (*uqn));
1257 	}
1258 	avl_destroy(&cache->uqc_group_deltas);
1259 }
1260 
1261 static void
userquota_update_cache(avl_tree_t * avl,uint64_t id,int64_t delta)1262 userquota_update_cache(avl_tree_t *avl, uint64_t id, int64_t delta)
1263 {
1264 	userquota_node_t search = { .uqn_id = id };
1265 	avl_index_t idx;
1266 
1267 	userquota_node_t *uqn = avl_find(avl, &search, &idx);
1268 	if (uqn == NULL) {
1269 		uqn = kmem_zalloc(sizeof (*uqn), KM_SLEEP);
1270 		uqn->uqn_id = id;
1271 		avl_insert(avl, uqn, idx);
1272 	}
1273 	uqn->uqn_delta += delta;
1274 }
1275 
1276 static void
do_userquota_update(userquota_cache_t * cache,uint64_t used,uint64_t flags,uint64_t user,uint64_t group,boolean_t subtract)1277 do_userquota_update(userquota_cache_t *cache, uint64_t used, uint64_t flags,
1278     uint64_t user, uint64_t group, boolean_t subtract)
1279 {
1280 	if ((flags & DNODE_FLAG_USERUSED_ACCOUNTED)) {
1281 		int64_t delta = DNODE_SIZE + used;
1282 		if (subtract)
1283 			delta = -delta;
1284 
1285 		userquota_update_cache(&cache->uqc_user_deltas, user, delta);
1286 		userquota_update_cache(&cache->uqc_group_deltas, group, delta);
1287 	}
1288 }
1289 
1290 void
dmu_objset_do_userquota_updates(objset_t * os,dmu_tx_t * tx)1291 dmu_objset_do_userquota_updates(objset_t *os, dmu_tx_t *tx)
1292 {
1293 	dnode_t *dn;
1294 	list_t *list = &os->os_synced_dnodes;
1295 	userquota_cache_t cache = { 0 };
1296 
1297 	ASSERT(list_head(list) == NULL || dmu_objset_userused_enabled(os));
1298 
1299 	avl_create(&cache.uqc_user_deltas, userquota_compare,
1300 	    sizeof (userquota_node_t), offsetof(userquota_node_t, uqn_node));
1301 	avl_create(&cache.uqc_group_deltas, userquota_compare,
1302 	    sizeof (userquota_node_t), offsetof(userquota_node_t, uqn_node));
1303 
1304 	while (dn = list_head(list)) {
1305 		int flags;
1306 		ASSERT(!DMU_OBJECT_IS_SPECIAL(dn->dn_object));
1307 		ASSERT(dn->dn_phys->dn_type == DMU_OT_NONE ||
1308 		    dn->dn_phys->dn_flags &
1309 		    DNODE_FLAG_USERUSED_ACCOUNTED);
1310 
1311 		/* Allocate the user/groupused objects if necessary. */
1312 		if (DMU_USERUSED_DNODE(os)->dn_type == DMU_OT_NONE) {
1313 			VERIFY0(zap_create_claim(os,
1314 			    DMU_USERUSED_OBJECT,
1315 			    DMU_OT_USERGROUP_USED, DMU_OT_NONE, 0, tx));
1316 			VERIFY0(zap_create_claim(os,
1317 			    DMU_GROUPUSED_OBJECT,
1318 			    DMU_OT_USERGROUP_USED, DMU_OT_NONE, 0, tx));
1319 		}
1320 
1321 		flags = dn->dn_id_flags;
1322 		ASSERT(flags);
1323 		if (flags & DN_ID_OLD_EXIST)  {
1324 			do_userquota_update(&cache,
1325 			    dn->dn_oldused, dn->dn_oldflags,
1326 			    dn->dn_olduid, dn->dn_oldgid, B_TRUE);
1327 		}
1328 		if (flags & DN_ID_NEW_EXIST) {
1329 			do_userquota_update(&cache,
1330 			    DN_USED_BYTES(dn->dn_phys),
1331 			    dn->dn_phys->dn_flags,  dn->dn_newuid,
1332 			    dn->dn_newgid, B_FALSE);
1333 		}
1334 
1335 		mutex_enter(&dn->dn_mtx);
1336 		dn->dn_oldused = 0;
1337 		dn->dn_oldflags = 0;
1338 		if (dn->dn_id_flags & DN_ID_NEW_EXIST) {
1339 			dn->dn_olduid = dn->dn_newuid;
1340 			dn->dn_oldgid = dn->dn_newgid;
1341 			dn->dn_id_flags |= DN_ID_OLD_EXIST;
1342 			if (dn->dn_bonuslen == 0)
1343 				dn->dn_id_flags |= DN_ID_CHKED_SPILL;
1344 			else
1345 				dn->dn_id_flags |= DN_ID_CHKED_BONUS;
1346 		}
1347 		dn->dn_id_flags &= ~(DN_ID_NEW_EXIST);
1348 		mutex_exit(&dn->dn_mtx);
1349 
1350 		list_remove(list, dn);
1351 		dnode_rele(dn, list);
1352 	}
1353 	do_userquota_cacheflush(os, &cache, tx);
1354 }
1355 
1356 /*
1357  * Returns a pointer to data to find uid/gid from
1358  *
1359  * If a dirty record for transaction group that is syncing can't
1360  * be found then NULL is returned.  In the NULL case it is assumed
1361  * the uid/gid aren't changing.
1362  */
1363 static void *
dmu_objset_userquota_find_data(dmu_buf_impl_t * db,dmu_tx_t * tx)1364 dmu_objset_userquota_find_data(dmu_buf_impl_t *db, dmu_tx_t *tx)
1365 {
1366 	dbuf_dirty_record_t *dr, **drp;
1367 	void *data;
1368 
1369 	if (db->db_dirtycnt == 0)
1370 		return (db->db.db_data);  /* Nothing is changing */
1371 
1372 	for (drp = &db->db_last_dirty; (dr = *drp) != NULL; drp = &dr->dr_next)
1373 		if (dr->dr_txg == tx->tx_txg)
1374 			break;
1375 
1376 	if (dr == NULL) {
1377 		data = NULL;
1378 	} else {
1379 		dnode_t *dn;
1380 
1381 		DB_DNODE_ENTER(dr->dr_dbuf);
1382 		dn = DB_DNODE(dr->dr_dbuf);
1383 
1384 		if (dn->dn_bonuslen == 0 &&
1385 		    dr->dr_dbuf->db_blkid == DMU_SPILL_BLKID)
1386 			data = dr->dt.dl.dr_data->b_data;
1387 		else
1388 			data = dr->dt.dl.dr_data;
1389 
1390 		DB_DNODE_EXIT(dr->dr_dbuf);
1391 	}
1392 
1393 	return (data);
1394 }
1395 
1396 void
dmu_objset_userquota_get_ids(dnode_t * dn,boolean_t before,dmu_tx_t * tx)1397 dmu_objset_userquota_get_ids(dnode_t *dn, boolean_t before, dmu_tx_t *tx)
1398 {
1399 	objset_t *os = dn->dn_objset;
1400 	void *data = NULL;
1401 	dmu_buf_impl_t *db = NULL;
1402 	uint64_t *user = NULL;
1403 	uint64_t *group = NULL;
1404 	int flags = dn->dn_id_flags;
1405 	int error;
1406 	boolean_t have_spill = B_FALSE;
1407 
1408 	if (!dmu_objset_userused_enabled(dn->dn_objset))
1409 		return;
1410 
1411 	if (before && (flags & (DN_ID_CHKED_BONUS|DN_ID_OLD_EXIST|
1412 	    DN_ID_CHKED_SPILL)))
1413 		return;
1414 
1415 	if (before && dn->dn_bonuslen != 0)
1416 		data = DN_BONUS(dn->dn_phys);
1417 	else if (!before && dn->dn_bonuslen != 0) {
1418 		if (dn->dn_bonus) {
1419 			db = dn->dn_bonus;
1420 			mutex_enter(&db->db_mtx);
1421 			data = dmu_objset_userquota_find_data(db, tx);
1422 		} else {
1423 			data = DN_BONUS(dn->dn_phys);
1424 		}
1425 	} else if (dn->dn_bonuslen == 0 && dn->dn_bonustype == DMU_OT_SA) {
1426 			int rf = 0;
1427 
1428 			if (RW_WRITE_HELD(&dn->dn_struct_rwlock))
1429 				rf |= DB_RF_HAVESTRUCT;
1430 			error = dmu_spill_hold_by_dnode(dn,
1431 			    rf | DB_RF_MUST_SUCCEED,
1432 			    FTAG, (dmu_buf_t **)&db);
1433 			ASSERT(error == 0);
1434 			mutex_enter(&db->db_mtx);
1435 			data = (before) ? db->db.db_data :
1436 			    dmu_objset_userquota_find_data(db, tx);
1437 			have_spill = B_TRUE;
1438 	} else {
1439 		mutex_enter(&dn->dn_mtx);
1440 		dn->dn_id_flags |= DN_ID_CHKED_BONUS;
1441 		mutex_exit(&dn->dn_mtx);
1442 		return;
1443 	}
1444 
1445 	if (before) {
1446 		ASSERT(data);
1447 		user = &dn->dn_olduid;
1448 		group = &dn->dn_oldgid;
1449 	} else if (data) {
1450 		user = &dn->dn_newuid;
1451 		group = &dn->dn_newgid;
1452 	}
1453 
1454 	/*
1455 	 * Must always call the callback in case the object
1456 	 * type has changed and that type isn't an object type to track
1457 	 */
1458 	error = used_cbs[os->os_phys->os_type](dn->dn_bonustype, data,
1459 	    user, group);
1460 
1461 	/*
1462 	 * Preserve existing uid/gid when the callback can't determine
1463 	 * what the new uid/gid are and the callback returned EEXIST.
1464 	 * The EEXIST error tells us to just use the existing uid/gid.
1465 	 * If we don't know what the old values are then just assign
1466 	 * them to 0, since that is a new file  being created.
1467 	 */
1468 	if (!before && data == NULL && error == EEXIST) {
1469 		if (flags & DN_ID_OLD_EXIST) {
1470 			dn->dn_newuid = dn->dn_olduid;
1471 			dn->dn_newgid = dn->dn_oldgid;
1472 		} else {
1473 			dn->dn_newuid = 0;
1474 			dn->dn_newgid = 0;
1475 		}
1476 		error = 0;
1477 	}
1478 
1479 	if (db)
1480 		mutex_exit(&db->db_mtx);
1481 
1482 	mutex_enter(&dn->dn_mtx);
1483 	if (error == 0 && before)
1484 		dn->dn_id_flags |= DN_ID_OLD_EXIST;
1485 	if (error == 0 && !before)
1486 		dn->dn_id_flags |= DN_ID_NEW_EXIST;
1487 
1488 	if (have_spill) {
1489 		dn->dn_id_flags |= DN_ID_CHKED_SPILL;
1490 	} else {
1491 		dn->dn_id_flags |= DN_ID_CHKED_BONUS;
1492 	}
1493 	mutex_exit(&dn->dn_mtx);
1494 	if (have_spill)
1495 		dmu_buf_rele((dmu_buf_t *)db, FTAG);
1496 }
1497 
1498 boolean_t
dmu_objset_userspace_present(objset_t * os)1499 dmu_objset_userspace_present(objset_t *os)
1500 {
1501 	return (os->os_phys->os_flags &
1502 	    OBJSET_FLAG_USERACCOUNTING_COMPLETE);
1503 }
1504 
1505 int
dmu_objset_userspace_upgrade(objset_t * os)1506 dmu_objset_userspace_upgrade(objset_t *os)
1507 {
1508 	uint64_t obj;
1509 	int err = 0;
1510 
1511 	if (dmu_objset_userspace_present(os))
1512 		return (0);
1513 	if (!dmu_objset_userused_enabled(os))
1514 		return (SET_ERROR(ENOTSUP));
1515 	if (dmu_objset_is_snapshot(os))
1516 		return (SET_ERROR(EINVAL));
1517 
1518 	/*
1519 	 * We simply need to mark every object dirty, so that it will be
1520 	 * synced out and now accounted.  If this is called
1521 	 * concurrently, or if we already did some work before crashing,
1522 	 * that's fine, since we track each object's accounted state
1523 	 * independently.
1524 	 */
1525 
1526 	for (obj = 0; err == 0; err = dmu_object_next(os, &obj, FALSE, 0)) {
1527 		dmu_tx_t *tx;
1528 		dmu_buf_t *db;
1529 		int objerr;
1530 
1531 		if (issig(JUSTLOOKING) && issig(FORREAL))
1532 			return (SET_ERROR(EINTR));
1533 
1534 		objerr = dmu_bonus_hold(os, obj, FTAG, &db);
1535 		if (objerr != 0)
1536 			continue;
1537 		tx = dmu_tx_create(os);
1538 		dmu_tx_hold_bonus(tx, obj);
1539 		objerr = dmu_tx_assign(tx, TXG_WAIT);
1540 		if (objerr != 0) {
1541 			dmu_tx_abort(tx);
1542 			continue;
1543 		}
1544 		dmu_buf_will_dirty(db, tx);
1545 		dmu_buf_rele(db, FTAG);
1546 		dmu_tx_commit(tx);
1547 	}
1548 
1549 	os->os_flags |= OBJSET_FLAG_USERACCOUNTING_COMPLETE;
1550 	txg_wait_synced(dmu_objset_pool(os), 0);
1551 	return (0);
1552 }
1553 
1554 void
dmu_objset_space(objset_t * os,uint64_t * refdbytesp,uint64_t * availbytesp,uint64_t * usedobjsp,uint64_t * availobjsp)1555 dmu_objset_space(objset_t *os, uint64_t *refdbytesp, uint64_t *availbytesp,
1556     uint64_t *usedobjsp, uint64_t *availobjsp)
1557 {
1558 	dsl_dataset_space(os->os_dsl_dataset, refdbytesp, availbytesp,
1559 	    usedobjsp, availobjsp);
1560 }
1561 
1562 uint64_t
dmu_objset_fsid_guid(objset_t * os)1563 dmu_objset_fsid_guid(objset_t *os)
1564 {
1565 	return (dsl_dataset_fsid_guid(os->os_dsl_dataset));
1566 }
1567 
1568 void
dmu_objset_fast_stat(objset_t * os,dmu_objset_stats_t * stat)1569 dmu_objset_fast_stat(objset_t *os, dmu_objset_stats_t *stat)
1570 {
1571 	stat->dds_type = os->os_phys->os_type;
1572 	if (os->os_dsl_dataset)
1573 		dsl_dataset_fast_stat(os->os_dsl_dataset, stat);
1574 }
1575 
1576 void
dmu_objset_stats(objset_t * os,nvlist_t * nv)1577 dmu_objset_stats(objset_t *os, nvlist_t *nv)
1578 {
1579 	ASSERT(os->os_dsl_dataset ||
1580 	    os->os_phys->os_type == DMU_OST_META);
1581 
1582 	if (os->os_dsl_dataset != NULL)
1583 		dsl_dataset_stats(os->os_dsl_dataset, nv);
1584 
1585 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_TYPE,
1586 	    os->os_phys->os_type);
1587 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USERACCOUNTING,
1588 	    dmu_objset_userspace_present(os));
1589 }
1590 
1591 int
dmu_objset_is_snapshot(objset_t * os)1592 dmu_objset_is_snapshot(objset_t *os)
1593 {
1594 	if (os->os_dsl_dataset != NULL)
1595 		return (os->os_dsl_dataset->ds_is_snapshot);
1596 	else
1597 		return (B_FALSE);
1598 }
1599 
1600 int
dmu_snapshot_realname(objset_t * os,char * name,char * real,int maxlen,boolean_t * conflict)1601 dmu_snapshot_realname(objset_t *os, char *name, char *real, int maxlen,
1602     boolean_t *conflict)
1603 {
1604 	dsl_dataset_t *ds = os->os_dsl_dataset;
1605 	uint64_t ignored;
1606 
1607 	if (dsl_dataset_phys(ds)->ds_snapnames_zapobj == 0)
1608 		return (SET_ERROR(ENOENT));
1609 
1610 	return (zap_lookup_norm(ds->ds_dir->dd_pool->dp_meta_objset,
1611 	    dsl_dataset_phys(ds)->ds_snapnames_zapobj, name, 8, 1, &ignored,
1612 	    MT_FIRST, real, maxlen, conflict));
1613 }
1614 
1615 int
dmu_snapshot_list_next(objset_t * os,int namelen,char * name,uint64_t * idp,uint64_t * offp,boolean_t * case_conflict)1616 dmu_snapshot_list_next(objset_t *os, int namelen, char *name,
1617     uint64_t *idp, uint64_t *offp, boolean_t *case_conflict)
1618 {
1619 	dsl_dataset_t *ds = os->os_dsl_dataset;
1620 	zap_cursor_t cursor;
1621 	zap_attribute_t attr;
1622 
1623 	ASSERT(dsl_pool_config_held(dmu_objset_pool(os)));
1624 
1625 	if (dsl_dataset_phys(ds)->ds_snapnames_zapobj == 0)
1626 		return (SET_ERROR(ENOENT));
1627 
1628 	zap_cursor_init_serialized(&cursor,
1629 	    ds->ds_dir->dd_pool->dp_meta_objset,
1630 	    dsl_dataset_phys(ds)->ds_snapnames_zapobj, *offp);
1631 
1632 	if (zap_cursor_retrieve(&cursor, &attr) != 0) {
1633 		zap_cursor_fini(&cursor);
1634 		return (SET_ERROR(ENOENT));
1635 	}
1636 
1637 	if (strlen(attr.za_name) + 1 > namelen) {
1638 		zap_cursor_fini(&cursor);
1639 		return (SET_ERROR(ENAMETOOLONG));
1640 	}
1641 
1642 	(void) strcpy(name, attr.za_name);
1643 	if (idp)
1644 		*idp = attr.za_first_integer;
1645 	if (case_conflict)
1646 		*case_conflict = attr.za_normalization_conflict;
1647 	zap_cursor_advance(&cursor);
1648 	*offp = zap_cursor_serialize(&cursor);
1649 	zap_cursor_fini(&cursor);
1650 
1651 	return (0);
1652 }
1653 
1654 int
dmu_dir_list_next(objset_t * os,int namelen,char * name,uint64_t * idp,uint64_t * offp)1655 dmu_dir_list_next(objset_t *os, int namelen, char *name,
1656     uint64_t *idp, uint64_t *offp)
1657 {
1658 	dsl_dir_t *dd = os->os_dsl_dataset->ds_dir;
1659 	zap_cursor_t cursor;
1660 	zap_attribute_t attr;
1661 
1662 	/* there is no next dir on a snapshot! */
1663 	if (os->os_dsl_dataset->ds_object !=
1664 	    dsl_dir_phys(dd)->dd_head_dataset_obj)
1665 		return (SET_ERROR(ENOENT));
1666 
1667 	zap_cursor_init_serialized(&cursor,
1668 	    dd->dd_pool->dp_meta_objset,
1669 	    dsl_dir_phys(dd)->dd_child_dir_zapobj, *offp);
1670 
1671 	if (zap_cursor_retrieve(&cursor, &attr) != 0) {
1672 		zap_cursor_fini(&cursor);
1673 		return (SET_ERROR(ENOENT));
1674 	}
1675 
1676 	if (strlen(attr.za_name) + 1 > namelen) {
1677 		zap_cursor_fini(&cursor);
1678 		return (SET_ERROR(ENAMETOOLONG));
1679 	}
1680 
1681 	(void) strcpy(name, attr.za_name);
1682 	if (idp)
1683 		*idp = attr.za_first_integer;
1684 	zap_cursor_advance(&cursor);
1685 	*offp = zap_cursor_serialize(&cursor);
1686 	zap_cursor_fini(&cursor);
1687 
1688 	return (0);
1689 }
1690 
1691 typedef struct dmu_objset_find_ctx {
1692 	taskq_t		*dc_tq;
1693 	dsl_pool_t	*dc_dp;
1694 	uint64_t	dc_ddobj;
1695 	int		(*dc_func)(dsl_pool_t *, dsl_dataset_t *, void *);
1696 	void		*dc_arg;
1697 	int		dc_flags;
1698 	kmutex_t	*dc_error_lock;
1699 	int		*dc_error;
1700 } dmu_objset_find_ctx_t;
1701 
1702 static void
dmu_objset_find_dp_impl(dmu_objset_find_ctx_t * dcp)1703 dmu_objset_find_dp_impl(dmu_objset_find_ctx_t *dcp)
1704 {
1705 	dsl_pool_t *dp = dcp->dc_dp;
1706 	dmu_objset_find_ctx_t *child_dcp;
1707 	dsl_dir_t *dd;
1708 	dsl_dataset_t *ds;
1709 	zap_cursor_t zc;
1710 	zap_attribute_t *attr;
1711 	uint64_t thisobj;
1712 	int err = 0;
1713 
1714 	/* don't process if there already was an error */
1715 	if (*dcp->dc_error != 0)
1716 		goto out;
1717 
1718 	err = dsl_dir_hold_obj(dp, dcp->dc_ddobj, NULL, FTAG, &dd);
1719 	if (err != 0)
1720 		goto out;
1721 
1722 	/* Don't visit hidden ($MOS & $ORIGIN) objsets. */
1723 	if (dd->dd_myname[0] == '$') {
1724 		dsl_dir_rele(dd, FTAG);
1725 		goto out;
1726 	}
1727 
1728 	thisobj = dsl_dir_phys(dd)->dd_head_dataset_obj;
1729 	attr = kmem_alloc(sizeof (zap_attribute_t), KM_SLEEP);
1730 
1731 	/*
1732 	 * Iterate over all children.
1733 	 */
1734 	if (dcp->dc_flags & DS_FIND_CHILDREN) {
1735 		for (zap_cursor_init(&zc, dp->dp_meta_objset,
1736 		    dsl_dir_phys(dd)->dd_child_dir_zapobj);
1737 		    zap_cursor_retrieve(&zc, attr) == 0;
1738 		    (void) zap_cursor_advance(&zc)) {
1739 			ASSERT3U(attr->za_integer_length, ==,
1740 			    sizeof (uint64_t));
1741 			ASSERT3U(attr->za_num_integers, ==, 1);
1742 
1743 			child_dcp = kmem_alloc(sizeof (*child_dcp), KM_SLEEP);
1744 			*child_dcp = *dcp;
1745 			child_dcp->dc_ddobj = attr->za_first_integer;
1746 			if (dcp->dc_tq != NULL)
1747 				(void) taskq_dispatch(dcp->dc_tq,
1748 				    dmu_objset_find_dp_cb, child_dcp, TQ_SLEEP);
1749 			else
1750 				dmu_objset_find_dp_impl(child_dcp);
1751 		}
1752 		zap_cursor_fini(&zc);
1753 	}
1754 
1755 	/*
1756 	 * Iterate over all snapshots.
1757 	 */
1758 	if (dcp->dc_flags & DS_FIND_SNAPSHOTS) {
1759 		dsl_dataset_t *ds;
1760 		err = dsl_dataset_hold_obj(dp, thisobj, FTAG, &ds);
1761 
1762 		if (err == 0) {
1763 			uint64_t snapobj;
1764 
1765 			snapobj = dsl_dataset_phys(ds)->ds_snapnames_zapobj;
1766 			dsl_dataset_rele(ds, FTAG);
1767 
1768 			for (zap_cursor_init(&zc, dp->dp_meta_objset, snapobj);
1769 			    zap_cursor_retrieve(&zc, attr) == 0;
1770 			    (void) zap_cursor_advance(&zc)) {
1771 				ASSERT3U(attr->za_integer_length, ==,
1772 				    sizeof (uint64_t));
1773 				ASSERT3U(attr->za_num_integers, ==, 1);
1774 
1775 				err = dsl_dataset_hold_obj(dp,
1776 				    attr->za_first_integer, FTAG, &ds);
1777 				if (err != 0)
1778 					break;
1779 				err = dcp->dc_func(dp, ds, dcp->dc_arg);
1780 				dsl_dataset_rele(ds, FTAG);
1781 				if (err != 0)
1782 					break;
1783 			}
1784 			zap_cursor_fini(&zc);
1785 		}
1786 	}
1787 
1788 	dsl_dir_rele(dd, FTAG);
1789 	kmem_free(attr, sizeof (zap_attribute_t));
1790 
1791 	if (err != 0)
1792 		goto out;
1793 
1794 	/*
1795 	 * Apply to self.
1796 	 */
1797 	err = dsl_dataset_hold_obj(dp, thisobj, FTAG, &ds);
1798 	if (err != 0)
1799 		goto out;
1800 	err = dcp->dc_func(dp, ds, dcp->dc_arg);
1801 	dsl_dataset_rele(ds, FTAG);
1802 
1803 out:
1804 	if (err != 0) {
1805 		mutex_enter(dcp->dc_error_lock);
1806 		/* only keep first error */
1807 		if (*dcp->dc_error == 0)
1808 			*dcp->dc_error = err;
1809 		mutex_exit(dcp->dc_error_lock);
1810 	}
1811 
1812 	kmem_free(dcp, sizeof (*dcp));
1813 }
1814 
1815 static void
dmu_objset_find_dp_cb(void * arg)1816 dmu_objset_find_dp_cb(void *arg)
1817 {
1818 	dmu_objset_find_ctx_t *dcp = arg;
1819 	dsl_pool_t *dp = dcp->dc_dp;
1820 
1821 	/*
1822 	 * We need to get a pool_config_lock here, as there are several
1823 	 * asssert(pool_config_held) down the stack. Getting a lock via
1824 	 * dsl_pool_config_enter is risky, as it might be stalled by a
1825 	 * pending writer. This would deadlock, as the write lock can
1826 	 * only be granted when our parent thread gives up the lock.
1827 	 * The _prio interface gives us priority over a pending writer.
1828 	 */
1829 	dsl_pool_config_enter_prio(dp, FTAG);
1830 
1831 	dmu_objset_find_dp_impl(dcp);
1832 
1833 	dsl_pool_config_exit(dp, FTAG);
1834 }
1835 
1836 /*
1837  * Find objsets under and including ddobj, call func(ds) on each.
1838  * The order for the enumeration is completely undefined.
1839  * func is called with dsl_pool_config held.
1840  */
1841 int
dmu_objset_find_dp(dsl_pool_t * dp,uint64_t ddobj,int func (dsl_pool_t *,dsl_dataset_t *,void *),void * arg,int flags)1842 dmu_objset_find_dp(dsl_pool_t *dp, uint64_t ddobj,
1843     int func(dsl_pool_t *, dsl_dataset_t *, void *), void *arg, int flags)
1844 {
1845 	int error = 0;
1846 	taskq_t *tq = NULL;
1847 	int ntasks;
1848 	dmu_objset_find_ctx_t *dcp;
1849 	kmutex_t err_lock;
1850 
1851 	mutex_init(&err_lock, NULL, MUTEX_DEFAULT, NULL);
1852 	dcp = kmem_alloc(sizeof (*dcp), KM_SLEEP);
1853 	dcp->dc_tq = NULL;
1854 	dcp->dc_dp = dp;
1855 	dcp->dc_ddobj = ddobj;
1856 	dcp->dc_func = func;
1857 	dcp->dc_arg = arg;
1858 	dcp->dc_flags = flags;
1859 	dcp->dc_error_lock = &err_lock;
1860 	dcp->dc_error = &error;
1861 
1862 	if ((flags & DS_FIND_SERIALIZE) || dsl_pool_config_held_writer(dp)) {
1863 		/*
1864 		 * In case a write lock is held we can't make use of
1865 		 * parallelism, as down the stack of the worker threads
1866 		 * the lock is asserted via dsl_pool_config_held.
1867 		 * In case of a read lock this is solved by getting a read
1868 		 * lock in each worker thread, which isn't possible in case
1869 		 * of a writer lock. So we fall back to the synchronous path
1870 		 * here.
1871 		 * In the future it might be possible to get some magic into
1872 		 * dsl_pool_config_held in a way that it returns true for
1873 		 * the worker threads so that a single lock held from this
1874 		 * thread suffices. For now, stay single threaded.
1875 		 */
1876 		dmu_objset_find_dp_impl(dcp);
1877 		mutex_destroy(&err_lock);
1878 
1879 		return (error);
1880 	}
1881 
1882 	ntasks = dmu_find_threads;
1883 	if (ntasks == 0)
1884 		ntasks = vdev_count_leaves(dp->dp_spa) * 4;
1885 	tq = taskq_create("dmu_objset_find", ntasks, minclsyspri, ntasks,
1886 	    INT_MAX, 0);
1887 	if (tq == NULL) {
1888 		kmem_free(dcp, sizeof (*dcp));
1889 		mutex_destroy(&err_lock);
1890 
1891 		return (SET_ERROR(ENOMEM));
1892 	}
1893 	dcp->dc_tq = tq;
1894 
1895 	/* dcp will be freed by task */
1896 	(void) taskq_dispatch(tq, dmu_objset_find_dp_cb, dcp, TQ_SLEEP);
1897 
1898 	/*
1899 	 * PORTING: this code relies on the property of taskq_wait to wait
1900 	 * until no more tasks are queued and no more tasks are active. As
1901 	 * we always queue new tasks from within other tasks, task_wait
1902 	 * reliably waits for the full recursion to finish, even though we
1903 	 * enqueue new tasks after taskq_wait has been called.
1904 	 * On platforms other than illumos, taskq_wait may not have this
1905 	 * property.
1906 	 */
1907 	taskq_wait(tq);
1908 	taskq_destroy(tq);
1909 	mutex_destroy(&err_lock);
1910 
1911 	return (error);
1912 }
1913 
1914 /*
1915  * Find all objsets under name, and for each, call 'func(child_name, arg)'.
1916  * The dp_config_rwlock must not be held when this is called, and it
1917  * will not be held when the callback is called.
1918  * Therefore this function should only be used when the pool is not changing
1919  * (e.g. in syncing context), or the callback can deal with the possible races.
1920  */
1921 static int
dmu_objset_find_impl(spa_t * spa,const char * name,int func (const char *,void *),void * arg,int flags)1922 dmu_objset_find_impl(spa_t *spa, const char *name,
1923     int func(const char *, void *), void *arg, int flags)
1924 {
1925 	dsl_dir_t *dd;
1926 	dsl_pool_t *dp = spa_get_dsl(spa);
1927 	dsl_dataset_t *ds;
1928 	zap_cursor_t zc;
1929 	zap_attribute_t *attr;
1930 	char *child;
1931 	uint64_t thisobj;
1932 	int err;
1933 
1934 	dsl_pool_config_enter(dp, FTAG);
1935 
1936 	err = dsl_dir_hold(dp, name, FTAG, &dd, NULL);
1937 	if (err != 0) {
1938 		dsl_pool_config_exit(dp, FTAG);
1939 		return (err);
1940 	}
1941 
1942 	/* Don't visit hidden ($MOS & $ORIGIN) objsets. */
1943 	if (dd->dd_myname[0] == '$') {
1944 		dsl_dir_rele(dd, FTAG);
1945 		dsl_pool_config_exit(dp, FTAG);
1946 		return (0);
1947 	}
1948 
1949 	thisobj = dsl_dir_phys(dd)->dd_head_dataset_obj;
1950 	attr = kmem_alloc(sizeof (zap_attribute_t), KM_SLEEP);
1951 
1952 	/*
1953 	 * Iterate over all children.
1954 	 */
1955 	if (flags & DS_FIND_CHILDREN) {
1956 		for (zap_cursor_init(&zc, dp->dp_meta_objset,
1957 		    dsl_dir_phys(dd)->dd_child_dir_zapobj);
1958 		    zap_cursor_retrieve(&zc, attr) == 0;
1959 		    (void) zap_cursor_advance(&zc)) {
1960 			ASSERT3U(attr->za_integer_length, ==,
1961 			    sizeof (uint64_t));
1962 			ASSERT3U(attr->za_num_integers, ==, 1);
1963 
1964 			child = kmem_asprintf("%s/%s", name, attr->za_name);
1965 			dsl_pool_config_exit(dp, FTAG);
1966 			err = dmu_objset_find_impl(spa, child,
1967 			    func, arg, flags);
1968 			dsl_pool_config_enter(dp, FTAG);
1969 			strfree(child);
1970 			if (err != 0)
1971 				break;
1972 		}
1973 		zap_cursor_fini(&zc);
1974 
1975 		if (err != 0) {
1976 			dsl_dir_rele(dd, FTAG);
1977 			dsl_pool_config_exit(dp, FTAG);
1978 			kmem_free(attr, sizeof (zap_attribute_t));
1979 			return (err);
1980 		}
1981 	}
1982 
1983 	/*
1984 	 * Iterate over all snapshots.
1985 	 */
1986 	if (flags & DS_FIND_SNAPSHOTS) {
1987 		err = dsl_dataset_hold_obj(dp, thisobj, FTAG, &ds);
1988 
1989 		if (err == 0) {
1990 			uint64_t snapobj;
1991 
1992 			snapobj = dsl_dataset_phys(ds)->ds_snapnames_zapobj;
1993 			dsl_dataset_rele(ds, FTAG);
1994 
1995 			for (zap_cursor_init(&zc, dp->dp_meta_objset, snapobj);
1996 			    zap_cursor_retrieve(&zc, attr) == 0;
1997 			    (void) zap_cursor_advance(&zc)) {
1998 				ASSERT3U(attr->za_integer_length, ==,
1999 				    sizeof (uint64_t));
2000 				ASSERT3U(attr->za_num_integers, ==, 1);
2001 
2002 				child = kmem_asprintf("%s@%s",
2003 				    name, attr->za_name);
2004 				dsl_pool_config_exit(dp, FTAG);
2005 				err = func(child, arg);
2006 				dsl_pool_config_enter(dp, FTAG);
2007 				strfree(child);
2008 				if (err != 0)
2009 					break;
2010 			}
2011 			zap_cursor_fini(&zc);
2012 		}
2013 	}
2014 
2015 	dsl_dir_rele(dd, FTAG);
2016 	kmem_free(attr, sizeof (zap_attribute_t));
2017 	dsl_pool_config_exit(dp, FTAG);
2018 
2019 	if (err != 0)
2020 		return (err);
2021 
2022 	/* Apply to self. */
2023 	return (func(name, arg));
2024 }
2025 
2026 /*
2027  * See comment above dmu_objset_find_impl().
2028  */
2029 int
dmu_objset_find(char * name,int func (const char *,void *),void * arg,int flags)2030 dmu_objset_find(char *name, int func(const char *, void *), void *arg,
2031     int flags)
2032 {
2033 	spa_t *spa;
2034 	int error;
2035 
2036 	error = spa_open(name, &spa, FTAG);
2037 	if (error != 0)
2038 		return (error);
2039 	error = dmu_objset_find_impl(spa, name, func, arg, flags);
2040 	spa_close(spa, FTAG);
2041 	return (error);
2042 }
2043 
2044 void
dmu_objset_set_user(objset_t * os,void * user_ptr)2045 dmu_objset_set_user(objset_t *os, void *user_ptr)
2046 {
2047 	ASSERT(MUTEX_HELD(&os->os_user_ptr_lock));
2048 	os->os_user_ptr = user_ptr;
2049 }
2050 
2051 void *
dmu_objset_get_user(objset_t * os)2052 dmu_objset_get_user(objset_t *os)
2053 {
2054 	ASSERT(MUTEX_HELD(&os->os_user_ptr_lock));
2055 	return (os->os_user_ptr);
2056 }
2057 
2058 /*
2059  * Determine name of filesystem, given name of snapshot.
2060  * buf must be at least ZFS_MAX_DATASET_NAME_LEN bytes
2061  */
2062 int
dmu_fsname(const char * snapname,char * buf)2063 dmu_fsname(const char *snapname, char *buf)
2064 {
2065 	char *atp = strchr(snapname, '@');
2066 	if (atp == NULL)
2067 		return (SET_ERROR(EINVAL));
2068 	if (atp - snapname >= ZFS_MAX_DATASET_NAME_LEN)
2069 		return (SET_ERROR(ENAMETOOLONG));
2070 	(void) strlcpy(buf, snapname, atp - snapname + 1);
2071 	return (0);
2072 }
2073