xref: /titanic_44/usr/src/uts/common/fs/zfs/dsl_dir.c (revision 2f1c59b18b4820d3f912c5465e37c28a93f9a5be)
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 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <sys/dmu.h>
29 #include <sys/dmu_tx.h>
30 #include <sys/dsl_dataset.h>
31 #include <sys/dsl_dir.h>
32 #include <sys/dsl_prop.h>
33 #include <sys/dsl_synctask.h>
34 #include <sys/spa.h>
35 #include <sys/zap.h>
36 #include <sys/zio.h>
37 #include <sys/arc.h>
38 #include "zfs_namecheck.h"
39 
40 static uint64_t dsl_dir_estimated_space(dsl_dir_t *dd);
41 static void dsl_dir_set_reservation_sync(void *arg1, void *arg2, dmu_tx_t *tx);
42 
43 
44 /* ARGSUSED */
45 static void
46 dsl_dir_evict(dmu_buf_t *db, void *arg)
47 {
48 	dsl_dir_t *dd = arg;
49 	dsl_pool_t *dp = dd->dd_pool;
50 	int t;
51 
52 	for (t = 0; t < TXG_SIZE; t++) {
53 		ASSERT(!txg_list_member(&dp->dp_dirty_dirs, dd, t));
54 		ASSERT(dd->dd_tempreserved[t] == 0);
55 		ASSERT(dd->dd_space_towrite[t] == 0);
56 	}
57 
58 	ASSERT3U(dd->dd_used_bytes, ==, dd->dd_phys->dd_used_bytes);
59 
60 	if (dd->dd_parent)
61 		dsl_dir_close(dd->dd_parent, dd);
62 
63 	spa_close(dd->dd_pool->dp_spa, dd);
64 
65 	/*
66 	 * The props callback list should be empty since they hold the
67 	 * dir open.
68 	 */
69 	list_destroy(&dd->dd_prop_cbs);
70 	mutex_destroy(&dd->dd_lock);
71 	kmem_free(dd, sizeof (dsl_dir_t));
72 }
73 
74 int
75 dsl_dir_open_obj(dsl_pool_t *dp, uint64_t ddobj,
76     const char *tail, void *tag, dsl_dir_t **ddp)
77 {
78 	dmu_buf_t *dbuf;
79 	dsl_dir_t *dd;
80 	int err;
81 
82 	ASSERT(RW_LOCK_HELD(&dp->dp_config_rwlock) ||
83 	    dsl_pool_sync_context(dp));
84 
85 	err = dmu_bonus_hold(dp->dp_meta_objset, ddobj, tag, &dbuf);
86 	if (err)
87 		return (err);
88 	dd = dmu_buf_get_user(dbuf);
89 #ifdef ZFS_DEBUG
90 	{
91 		dmu_object_info_t doi;
92 		dmu_object_info_from_db(dbuf, &doi);
93 		ASSERT3U(doi.doi_type, ==, DMU_OT_DSL_DIR);
94 	}
95 #endif
96 	/* XXX assert bonus buffer size is correct */
97 	if (dd == NULL) {
98 		dsl_dir_t *winner;
99 		int err;
100 
101 		dd = kmem_zalloc(sizeof (dsl_dir_t), KM_SLEEP);
102 		dd->dd_object = ddobj;
103 		dd->dd_dbuf = dbuf;
104 		dd->dd_pool = dp;
105 		dd->dd_phys = dbuf->db_data;
106 		dd->dd_used_bytes = dd->dd_phys->dd_used_bytes;
107 		mutex_init(&dd->dd_lock, NULL, MUTEX_DEFAULT, NULL);
108 
109 		list_create(&dd->dd_prop_cbs, sizeof (dsl_prop_cb_record_t),
110 		    offsetof(dsl_prop_cb_record_t, cbr_node));
111 
112 		if (dd->dd_phys->dd_parent_obj) {
113 			err = dsl_dir_open_obj(dp, dd->dd_phys->dd_parent_obj,
114 			    NULL, dd, &dd->dd_parent);
115 			if (err) {
116 				mutex_destroy(&dd->dd_lock);
117 				kmem_free(dd, sizeof (dsl_dir_t));
118 				dmu_buf_rele(dbuf, tag);
119 				return (err);
120 			}
121 			if (tail) {
122 #ifdef ZFS_DEBUG
123 				uint64_t foundobj;
124 
125 				err = zap_lookup(dp->dp_meta_objset,
126 				    dd->dd_parent->dd_phys->
127 				    dd_child_dir_zapobj,
128 				    tail, sizeof (foundobj), 1, &foundobj);
129 				ASSERT(err || foundobj == ddobj);
130 #endif
131 				(void) strcpy(dd->dd_myname, tail);
132 			} else {
133 				err = zap_value_search(dp->dp_meta_objset,
134 				    dd->dd_parent->dd_phys->
135 				    dd_child_dir_zapobj,
136 				    ddobj, dd->dd_myname);
137 			}
138 			if (err) {
139 				dsl_dir_close(dd->dd_parent, dd);
140 				mutex_destroy(&dd->dd_lock);
141 				kmem_free(dd, sizeof (dsl_dir_t));
142 				dmu_buf_rele(dbuf, tag);
143 				return (err);
144 			}
145 		} else {
146 			(void) strcpy(dd->dd_myname, spa_name(dp->dp_spa));
147 		}
148 
149 		winner = dmu_buf_set_user_ie(dbuf, dd, &dd->dd_phys,
150 		    dsl_dir_evict);
151 		if (winner) {
152 			if (dd->dd_parent)
153 				dsl_dir_close(dd->dd_parent, dd);
154 			mutex_destroy(&dd->dd_lock);
155 			kmem_free(dd, sizeof (dsl_dir_t));
156 			dd = winner;
157 		} else {
158 			spa_open_ref(dp->dp_spa, dd);
159 		}
160 	}
161 
162 	/*
163 	 * The dsl_dir_t has both open-to-close and instantiate-to-evict
164 	 * holds on the spa.  We need the open-to-close holds because
165 	 * otherwise the spa_refcnt wouldn't change when we open a
166 	 * dir which the spa also has open, so we could incorrectly
167 	 * think it was OK to unload/export/destroy the pool.  We need
168 	 * the instantiate-to-evict hold because the dsl_dir_t has a
169 	 * pointer to the dd_pool, which has a pointer to the spa_t.
170 	 */
171 	spa_open_ref(dp->dp_spa, tag);
172 	ASSERT3P(dd->dd_pool, ==, dp);
173 	ASSERT3U(dd->dd_object, ==, ddobj);
174 	ASSERT3P(dd->dd_dbuf, ==, dbuf);
175 	*ddp = dd;
176 	return (0);
177 }
178 
179 void
180 dsl_dir_close(dsl_dir_t *dd, void *tag)
181 {
182 	dprintf_dd(dd, "%s\n", "");
183 	spa_close(dd->dd_pool->dp_spa, tag);
184 	dmu_buf_rele(dd->dd_dbuf, tag);
185 }
186 
187 /* buf must be long enough (MAXNAMELEN + strlen(MOS_DIR_NAME) + 1 should do) */
188 void
189 dsl_dir_name(dsl_dir_t *dd, char *buf)
190 {
191 	if (dd->dd_parent) {
192 		dsl_dir_name(dd->dd_parent, buf);
193 		(void) strcat(buf, "/");
194 	} else {
195 		buf[0] = '\0';
196 	}
197 	if (!MUTEX_HELD(&dd->dd_lock)) {
198 		/*
199 		 * recursive mutex so that we can use
200 		 * dprintf_dd() with dd_lock held
201 		 */
202 		mutex_enter(&dd->dd_lock);
203 		(void) strcat(buf, dd->dd_myname);
204 		mutex_exit(&dd->dd_lock);
205 	} else {
206 		(void) strcat(buf, dd->dd_myname);
207 	}
208 }
209 
210 int
211 dsl_dir_is_private(dsl_dir_t *dd)
212 {
213 	int rv = FALSE;
214 
215 	if (dd->dd_parent && dsl_dir_is_private(dd->dd_parent))
216 		rv = TRUE;
217 	if (dataset_name_hidden(dd->dd_myname))
218 		rv = TRUE;
219 	return (rv);
220 }
221 
222 
223 static int
224 getcomponent(const char *path, char *component, const char **nextp)
225 {
226 	char *p;
227 	if (path == NULL)
228 		return (ENOENT);
229 	/* This would be a good place to reserve some namespace... */
230 	p = strpbrk(path, "/@");
231 	if (p && (p[1] == '/' || p[1] == '@')) {
232 		/* two separators in a row */
233 		return (EINVAL);
234 	}
235 	if (p == NULL || p == path) {
236 		/*
237 		 * if the first thing is an @ or /, it had better be an
238 		 * @ and it had better not have any more ats or slashes,
239 		 * and it had better have something after the @.
240 		 */
241 		if (p != NULL &&
242 		    (p[0] != '@' || strpbrk(path+1, "/@") || p[1] == '\0'))
243 			return (EINVAL);
244 		if (strlen(path) >= MAXNAMELEN)
245 			return (ENAMETOOLONG);
246 		(void) strcpy(component, path);
247 		p = NULL;
248 	} else if (p[0] == '/') {
249 		if (p-path >= MAXNAMELEN)
250 			return (ENAMETOOLONG);
251 		(void) strncpy(component, path, p - path);
252 		component[p-path] = '\0';
253 		p++;
254 	} else if (p[0] == '@') {
255 		/*
256 		 * if the next separator is an @, there better not be
257 		 * any more slashes.
258 		 */
259 		if (strchr(path, '/'))
260 			return (EINVAL);
261 		if (p-path >= MAXNAMELEN)
262 			return (ENAMETOOLONG);
263 		(void) strncpy(component, path, p - path);
264 		component[p-path] = '\0';
265 	} else {
266 		ASSERT(!"invalid p");
267 	}
268 	*nextp = p;
269 	return (0);
270 }
271 
272 /*
273  * same as dsl_open_dir, ignore the first component of name and use the
274  * spa instead
275  */
276 int
277 dsl_dir_open_spa(spa_t *spa, const char *name, void *tag,
278     dsl_dir_t **ddp, const char **tailp)
279 {
280 	char buf[MAXNAMELEN];
281 	const char *next, *nextnext = NULL;
282 	int err;
283 	dsl_dir_t *dd;
284 	dsl_pool_t *dp;
285 	uint64_t ddobj;
286 	int openedspa = FALSE;
287 
288 	dprintf("%s\n", name);
289 
290 	err = getcomponent(name, buf, &next);
291 	if (err)
292 		return (err);
293 	if (spa == NULL) {
294 		err = spa_open(buf, &spa, FTAG);
295 		if (err) {
296 			dprintf("spa_open(%s) failed\n", buf);
297 			return (err);
298 		}
299 		openedspa = TRUE;
300 
301 		/* XXX this assertion belongs in spa_open */
302 		ASSERT(!dsl_pool_sync_context(spa_get_dsl(spa)));
303 	}
304 
305 	dp = spa_get_dsl(spa);
306 
307 	rw_enter(&dp->dp_config_rwlock, RW_READER);
308 	err = dsl_dir_open_obj(dp, dp->dp_root_dir_obj, NULL, tag, &dd);
309 	if (err) {
310 		rw_exit(&dp->dp_config_rwlock);
311 		if (openedspa)
312 			spa_close(spa, FTAG);
313 		return (err);
314 	}
315 
316 	while (next != NULL) {
317 		dsl_dir_t *child_ds;
318 		err = getcomponent(next, buf, &nextnext);
319 		if (err)
320 			break;
321 		ASSERT(next[0] != '\0');
322 		if (next[0] == '@')
323 			break;
324 		dprintf("looking up %s in obj%lld\n",
325 		    buf, dd->dd_phys->dd_child_dir_zapobj);
326 
327 		err = zap_lookup(dp->dp_meta_objset,
328 		    dd->dd_phys->dd_child_dir_zapobj,
329 		    buf, sizeof (ddobj), 1, &ddobj);
330 		if (err) {
331 			if (err == ENOENT)
332 				err = 0;
333 			break;
334 		}
335 
336 		err = dsl_dir_open_obj(dp, ddobj, buf, tag, &child_ds);
337 		if (err)
338 			break;
339 		dsl_dir_close(dd, tag);
340 		dd = child_ds;
341 		next = nextnext;
342 	}
343 	rw_exit(&dp->dp_config_rwlock);
344 
345 	if (err) {
346 		dsl_dir_close(dd, tag);
347 		if (openedspa)
348 			spa_close(spa, FTAG);
349 		return (err);
350 	}
351 
352 	/*
353 	 * It's an error if there's more than one component left, or
354 	 * tailp==NULL and there's any component left.
355 	 */
356 	if (next != NULL &&
357 	    (tailp == NULL || (nextnext && nextnext[0] != '\0'))) {
358 		/* bad path name */
359 		dsl_dir_close(dd, tag);
360 		dprintf("next=%p (%s) tail=%p\n", next, next?next:"", tailp);
361 		err = ENOENT;
362 	}
363 	if (tailp)
364 		*tailp = next;
365 	if (openedspa)
366 		spa_close(spa, FTAG);
367 	*ddp = dd;
368 	return (err);
369 }
370 
371 /*
372  * Return the dsl_dir_t, and possibly the last component which couldn't
373  * be found in *tail.  Return NULL if the path is bogus, or if
374  * tail==NULL and we couldn't parse the whole name.  (*tail)[0] == '@'
375  * means that the last component is a snapshot.
376  */
377 int
378 dsl_dir_open(const char *name, void *tag, dsl_dir_t **ddp, const char **tailp)
379 {
380 	return (dsl_dir_open_spa(NULL, name, tag, ddp, tailp));
381 }
382 
383 uint64_t
384 dsl_dir_create_sync(dsl_dir_t *pds, const char *name, dmu_tx_t *tx)
385 {
386 	objset_t *mos = pds->dd_pool->dp_meta_objset;
387 	uint64_t ddobj;
388 	dsl_dir_phys_t *dsphys;
389 	dmu_buf_t *dbuf;
390 
391 	ddobj = dmu_object_alloc(mos, DMU_OT_DSL_DIR, 0,
392 	    DMU_OT_DSL_DIR, sizeof (dsl_dir_phys_t), tx);
393 	VERIFY(0 == zap_add(mos, pds->dd_phys->dd_child_dir_zapobj,
394 	    name, sizeof (uint64_t), 1, &ddobj, tx));
395 	VERIFY(0 == dmu_bonus_hold(mos, ddobj, FTAG, &dbuf));
396 	dmu_buf_will_dirty(dbuf, tx);
397 	dsphys = dbuf->db_data;
398 
399 	dsphys->dd_creation_time = gethrestime_sec();
400 	dsphys->dd_parent_obj = pds->dd_object;
401 	dsphys->dd_props_zapobj = zap_create(mos,
402 	    DMU_OT_DSL_PROPS, DMU_OT_NONE, 0, tx);
403 	dsphys->dd_child_dir_zapobj = zap_create(mos,
404 	    DMU_OT_DSL_DIR_CHILD_MAP, DMU_OT_NONE, 0, tx);
405 	dmu_buf_rele(dbuf, FTAG);
406 
407 	return (ddobj);
408 }
409 
410 /* ARGSUSED */
411 int
412 dsl_dir_destroy_check(void *arg1, void *arg2, dmu_tx_t *tx)
413 {
414 	dsl_dir_t *dd = arg1;
415 	dsl_pool_t *dp = dd->dd_pool;
416 	objset_t *mos = dp->dp_meta_objset;
417 	int err;
418 	uint64_t count;
419 
420 	/*
421 	 * There should be exactly two holds, both from
422 	 * dsl_dataset_destroy: one on the dd directory, and one on its
423 	 * head ds.  Otherwise, someone is trying to lookup something
424 	 * inside this dir while we want to destroy it.  The
425 	 * config_rwlock ensures that nobody else opens it after we
426 	 * check.
427 	 */
428 	if (dmu_buf_refcount(dd->dd_dbuf) > 2)
429 		return (EBUSY);
430 
431 	err = zap_count(mos, dd->dd_phys->dd_child_dir_zapobj, &count);
432 	if (err)
433 		return (err);
434 	if (count != 0)
435 		return (EEXIST);
436 
437 	return (0);
438 }
439 
440 void
441 dsl_dir_destroy_sync(void *arg1, void *tag, dmu_tx_t *tx)
442 {
443 	dsl_dir_t *dd = arg1;
444 	objset_t *mos = dd->dd_pool->dp_meta_objset;
445 	uint64_t val, obj;
446 
447 	ASSERT(RW_WRITE_HELD(&dd->dd_pool->dp_config_rwlock));
448 	ASSERT(dd->dd_phys->dd_head_dataset_obj == 0);
449 
450 	/* Remove our reservation. */
451 	val = 0;
452 	dsl_dir_set_reservation_sync(dd, &val, tx);
453 	ASSERT3U(dd->dd_used_bytes, ==, 0);
454 	ASSERT3U(dd->dd_phys->dd_reserved, ==, 0);
455 
456 	VERIFY(0 == zap_destroy(mos, dd->dd_phys->dd_child_dir_zapobj, tx));
457 	VERIFY(0 == zap_destroy(mos, dd->dd_phys->dd_props_zapobj, tx));
458 	VERIFY(0 == zap_remove(mos,
459 	    dd->dd_parent->dd_phys->dd_child_dir_zapobj, dd->dd_myname, tx));
460 
461 	obj = dd->dd_object;
462 	dsl_dir_close(dd, tag);
463 	VERIFY(0 == dmu_object_free(mos, obj, tx));
464 }
465 
466 void
467 dsl_dir_create_root(objset_t *mos, uint64_t *ddobjp, dmu_tx_t *tx)
468 {
469 	dsl_dir_phys_t *dsp;
470 	dmu_buf_t *dbuf;
471 	int error;
472 
473 	*ddobjp = dmu_object_alloc(mos, DMU_OT_DSL_DIR, 0,
474 	    DMU_OT_DSL_DIR, sizeof (dsl_dir_phys_t), tx);
475 
476 	error = zap_add(mos, DMU_POOL_DIRECTORY_OBJECT, DMU_POOL_ROOT_DATASET,
477 	    sizeof (uint64_t), 1, ddobjp, tx);
478 	ASSERT3U(error, ==, 0);
479 
480 	VERIFY(0 == dmu_bonus_hold(mos, *ddobjp, FTAG, &dbuf));
481 	dmu_buf_will_dirty(dbuf, tx);
482 	dsp = dbuf->db_data;
483 
484 	dsp->dd_creation_time = gethrestime_sec();
485 	dsp->dd_props_zapobj = zap_create(mos,
486 	    DMU_OT_DSL_PROPS, DMU_OT_NONE, 0, tx);
487 	dsp->dd_child_dir_zapobj = zap_create(mos,
488 	    DMU_OT_DSL_DIR_CHILD_MAP, DMU_OT_NONE, 0, tx);
489 
490 	dmu_buf_rele(dbuf, FTAG);
491 }
492 
493 void
494 dsl_dir_stats(dsl_dir_t *dd, nvlist_t *nv)
495 {
496 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_AVAILABLE,
497 	    dsl_dir_space_available(dd, NULL, 0, TRUE));
498 
499 	mutex_enter(&dd->dd_lock);
500 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USED, dd->dd_used_bytes);
501 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_QUOTA,
502 	    dd->dd_phys->dd_quota);
503 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_RESERVATION,
504 	    dd->dd_phys->dd_reserved);
505 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_COMPRESSRATIO,
506 	    dd->dd_phys->dd_compressed_bytes == 0 ? 100 :
507 	    (dd->dd_phys->dd_uncompressed_bytes * 100 /
508 	    dd->dd_phys->dd_compressed_bytes));
509 	mutex_exit(&dd->dd_lock);
510 
511 	if (dd->dd_phys->dd_clone_parent_obj) {
512 		dsl_dataset_t *ds;
513 		char buf[MAXNAMELEN];
514 
515 		rw_enter(&dd->dd_pool->dp_config_rwlock, RW_READER);
516 		VERIFY(0 == dsl_dataset_open_obj(dd->dd_pool,
517 		    dd->dd_phys->dd_clone_parent_obj,
518 		    NULL, DS_MODE_NONE, FTAG, &ds));
519 		dsl_dataset_name(ds, buf);
520 		dsl_dataset_close(ds, DS_MODE_NONE, FTAG);
521 		rw_exit(&dd->dd_pool->dp_config_rwlock);
522 
523 		dsl_prop_nvlist_add_string(nv, ZFS_PROP_ORIGIN, buf);
524 	}
525 }
526 
527 void
528 dsl_dir_dirty(dsl_dir_t *dd, dmu_tx_t *tx)
529 {
530 	dsl_pool_t *dp = dd->dd_pool;
531 
532 	ASSERT(dd->dd_phys);
533 
534 	if (txg_list_add(&dp->dp_dirty_dirs, dd, tx->tx_txg) == 0) {
535 		/* up the hold count until we can be written out */
536 		dmu_buf_add_ref(dd->dd_dbuf, dd);
537 	}
538 }
539 
540 static int64_t
541 parent_delta(dsl_dir_t *dd, uint64_t used, int64_t delta)
542 {
543 	uint64_t old_accounted = MAX(used, dd->dd_phys->dd_reserved);
544 	uint64_t new_accounted = MAX(used + delta, dd->dd_phys->dd_reserved);
545 	return (new_accounted - old_accounted);
546 }
547 
548 void
549 dsl_dir_sync(dsl_dir_t *dd, dmu_tx_t *tx)
550 {
551 	ASSERT(dmu_tx_is_syncing(tx));
552 
553 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
554 
555 	mutex_enter(&dd->dd_lock);
556 	ASSERT3U(dd->dd_tempreserved[tx->tx_txg&TXG_MASK], ==, 0);
557 	dprintf_dd(dd, "txg=%llu towrite=%lluK\n", tx->tx_txg,
558 	    dd->dd_space_towrite[tx->tx_txg&TXG_MASK] / 1024);
559 	dd->dd_space_towrite[tx->tx_txg&TXG_MASK] = 0;
560 	dd->dd_phys->dd_used_bytes = dd->dd_used_bytes;
561 	mutex_exit(&dd->dd_lock);
562 
563 	/* release the hold from dsl_dir_dirty */
564 	dmu_buf_rele(dd->dd_dbuf, dd);
565 }
566 
567 static uint64_t
568 dsl_dir_estimated_space(dsl_dir_t *dd)
569 {
570 	int64_t space;
571 	int i;
572 
573 	ASSERT(MUTEX_HELD(&dd->dd_lock));
574 
575 	space = dd->dd_phys->dd_used_bytes;
576 	ASSERT(space >= 0);
577 	for (i = 0; i < TXG_SIZE; i++) {
578 		space += dd->dd_space_towrite[i&TXG_MASK];
579 		ASSERT3U(dd->dd_space_towrite[i&TXG_MASK], >=, 0);
580 	}
581 	return (space);
582 }
583 
584 /*
585  * How much space would dd have available if ancestor had delta applied
586  * to it?  If ondiskonly is set, we're only interested in what's
587  * on-disk, not estimated pending changes.
588  */
589 uint64_t
590 dsl_dir_space_available(dsl_dir_t *dd,
591     dsl_dir_t *ancestor, int64_t delta, int ondiskonly)
592 {
593 	uint64_t parentspace, myspace, quota, used;
594 
595 	/*
596 	 * If there are no restrictions otherwise, assume we have
597 	 * unlimited space available.
598 	 */
599 	quota = UINT64_MAX;
600 	parentspace = UINT64_MAX;
601 
602 	if (dd->dd_parent != NULL) {
603 		parentspace = dsl_dir_space_available(dd->dd_parent,
604 		    ancestor, delta, ondiskonly);
605 	}
606 
607 	mutex_enter(&dd->dd_lock);
608 	if (dd->dd_phys->dd_quota != 0)
609 		quota = dd->dd_phys->dd_quota;
610 	if (ondiskonly) {
611 		used = dd->dd_used_bytes;
612 	} else {
613 		used = dsl_dir_estimated_space(dd);
614 	}
615 	if (dd == ancestor)
616 		used += delta;
617 
618 	if (dd->dd_parent == NULL) {
619 		uint64_t poolsize = dsl_pool_adjustedsize(dd->dd_pool, FALSE);
620 		quota = MIN(quota, poolsize);
621 	}
622 
623 	if (dd->dd_phys->dd_reserved > used && parentspace != UINT64_MAX) {
624 		/*
625 		 * We have some space reserved, in addition to what our
626 		 * parent gave us.
627 		 */
628 		parentspace += dd->dd_phys->dd_reserved - used;
629 	}
630 
631 	if (used > quota) {
632 		/* over quota */
633 		myspace = 0;
634 
635 		/*
636 		 * While it's OK to be a little over quota, if
637 		 * we think we are using more space than there
638 		 * is in the pool (which is already 1.6% more than
639 		 * dsl_pool_adjustedsize()), something is very
640 		 * wrong.
641 		 */
642 		ASSERT3U(used, <=, spa_get_space(dd->dd_pool->dp_spa));
643 	} else {
644 		/*
645 		 * the lesser of the space provided by our parent and
646 		 * the space left in our quota
647 		 */
648 		myspace = MIN(parentspace, quota - used);
649 	}
650 
651 	mutex_exit(&dd->dd_lock);
652 
653 	return (myspace);
654 }
655 
656 struct tempreserve {
657 	list_node_t tr_node;
658 	dsl_dir_t *tr_ds;
659 	uint64_t tr_size;
660 };
661 
662 /*
663  * Reserve space in this dsl_dir, to be used in this tx's txg.
664  * After the space has been dirtied (and thus
665  * dsl_dir_willuse_space() has been called), the reservation should
666  * be canceled, using dsl_dir_tempreserve_clear().
667  */
668 static int
669 dsl_dir_tempreserve_impl(dsl_dir_t *dd,
670     uint64_t asize, boolean_t netfree, list_t *tr_list, dmu_tx_t *tx)
671 {
672 	uint64_t txg = tx->tx_txg;
673 	uint64_t est_used, quota, parent_rsrv;
674 	int edquot = EDQUOT;
675 	int txgidx = txg & TXG_MASK;
676 	int i;
677 	struct tempreserve *tr;
678 
679 	ASSERT3U(txg, !=, 0);
680 	ASSERT3S(asize, >=, 0);
681 
682 	mutex_enter(&dd->dd_lock);
683 	/*
684 	 * Check against the dsl_dir's quota.  We don't add in the delta
685 	 * when checking for over-quota because they get one free hit.
686 	 */
687 	est_used = dsl_dir_estimated_space(dd);
688 	for (i = 0; i < TXG_SIZE; i++)
689 		est_used += dd->dd_tempreserved[i];
690 
691 	quota = UINT64_MAX;
692 
693 	if (dd->dd_phys->dd_quota)
694 		quota = dd->dd_phys->dd_quota;
695 
696 	/*
697 	 * If this transaction will result in a net free of space, we want
698 	 * to let it through, but we have to be careful: the space that it
699 	 * frees won't become available until *after* this txg syncs.
700 	 * Therefore, to ensure that it's possible to remove files from
701 	 * a full pool without inducing transient overcommits, we throttle
702 	 * netfree transactions against a quota that is slightly larger,
703 	 * but still within the pool's allocation slop.  In cases where
704 	 * we're very close to full, this will allow a steady trickle of
705 	 * removes to get through.
706 	 */
707 	if (dd->dd_parent == NULL) {
708 		uint64_t poolsize = dsl_pool_adjustedsize(dd->dd_pool, netfree);
709 		if (poolsize < quota) {
710 			quota = poolsize;
711 			edquot = ENOSPC;
712 		}
713 	} else if (netfree) {
714 		quota = UINT64_MAX;
715 	}
716 
717 	/*
718 	 * If they are requesting more space, and our current estimate
719 	 * is over quota.  They get to try again unless the actual
720 	 * on-disk is over quota and there are no pending changes (which
721 	 * may free up space for us).
722 	 */
723 	if (asize > 0 && est_used > quota) {
724 		if (dd->dd_space_towrite[txg & TXG_MASK] != 0 ||
725 		    dd->dd_space_towrite[(txg-1) & TXG_MASK] != 0 ||
726 		    dd->dd_space_towrite[(txg-2) & TXG_MASK] != 0 ||
727 		    dd->dd_used_bytes < quota)
728 			edquot = ERESTART;
729 		dprintf_dd(dd, "failing: used=%lluK est_used = %lluK "
730 		    "quota=%lluK tr=%lluK err=%d\n",
731 		    dd->dd_used_bytes>>10, est_used>>10,
732 		    quota>>10, asize>>10, edquot);
733 		mutex_exit(&dd->dd_lock);
734 		return (edquot);
735 	}
736 
737 	/* We need to up our estimated delta before dropping dd_lock */
738 	dd->dd_tempreserved[txgidx] += asize;
739 
740 	parent_rsrv = parent_delta(dd, est_used, asize);
741 	mutex_exit(&dd->dd_lock);
742 
743 	tr = kmem_alloc(sizeof (struct tempreserve), KM_SLEEP);
744 	tr->tr_ds = dd;
745 	tr->tr_size = asize;
746 	list_insert_tail(tr_list, tr);
747 
748 	/* see if it's OK with our parent */
749 	if (dd->dd_parent && parent_rsrv) {
750 		return (dsl_dir_tempreserve_impl(dd->dd_parent,
751 		    parent_rsrv, netfree, tr_list, tx));
752 	} else {
753 		return (0);
754 	}
755 }
756 
757 /*
758  * Reserve space in this dsl_dir, to be used in this tx's txg.
759  * After the space has been dirtied (and thus
760  * dsl_dir_willuse_space() has been called), the reservation should
761  * be canceled, using dsl_dir_tempreserve_clear().
762  */
763 int
764 dsl_dir_tempreserve_space(dsl_dir_t *dd, uint64_t lsize,
765     uint64_t asize, uint64_t fsize, void **tr_cookiep, dmu_tx_t *tx)
766 {
767 	int err = 0;
768 	list_t *tr_list;
769 
770 	tr_list = kmem_alloc(sizeof (list_t), KM_SLEEP);
771 	list_create(tr_list, sizeof (struct tempreserve),
772 	    offsetof(struct tempreserve, tr_node));
773 	ASSERT3S(asize, >=, 0);
774 	ASSERT3S(fsize, >=, 0);
775 
776 	err = dsl_dir_tempreserve_impl(dd, asize, fsize >= asize,
777 	    tr_list, tx);
778 
779 	if (err == 0) {
780 		struct tempreserve *tr;
781 
782 		err = arc_tempreserve_space(lsize);
783 		if (err == 0) {
784 			tr = kmem_alloc(sizeof (struct tempreserve), KM_SLEEP);
785 			tr->tr_ds = NULL;
786 			tr->tr_size = lsize;
787 			list_insert_tail(tr_list, tr);
788 		}
789 	}
790 
791 	if (err)
792 		dsl_dir_tempreserve_clear(tr_list, tx);
793 	else
794 		*tr_cookiep = tr_list;
795 	return (err);
796 }
797 
798 /*
799  * Clear a temporary reservation that we previously made with
800  * dsl_dir_tempreserve_space().
801  */
802 void
803 dsl_dir_tempreserve_clear(void *tr_cookie, dmu_tx_t *tx)
804 {
805 	int txgidx = tx->tx_txg & TXG_MASK;
806 	list_t *tr_list = tr_cookie;
807 	struct tempreserve *tr;
808 
809 	ASSERT3U(tx->tx_txg, !=, 0);
810 
811 	while (tr = list_head(tr_list)) {
812 		if (tr->tr_ds == NULL) {
813 			arc_tempreserve_clear(tr->tr_size);
814 		} else {
815 			mutex_enter(&tr->tr_ds->dd_lock);
816 			ASSERT3U(tr->tr_ds->dd_tempreserved[txgidx], >=,
817 			    tr->tr_size);
818 			tr->tr_ds->dd_tempreserved[txgidx] -= tr->tr_size;
819 			mutex_exit(&tr->tr_ds->dd_lock);
820 		}
821 		list_remove(tr_list, tr);
822 		kmem_free(tr, sizeof (struct tempreserve));
823 	}
824 
825 	kmem_free(tr_list, sizeof (list_t));
826 }
827 
828 /*
829  * Call in open context when we think we're going to write/free space,
830  * eg. when dirtying data.  Be conservative (ie. OK to write less than
831  * this or free more than this, but don't write more or free less).
832  */
833 void
834 dsl_dir_willuse_space(dsl_dir_t *dd, int64_t space, dmu_tx_t *tx)
835 {
836 	int64_t parent_space;
837 	uint64_t est_used;
838 
839 	mutex_enter(&dd->dd_lock);
840 	if (space > 0)
841 		dd->dd_space_towrite[tx->tx_txg & TXG_MASK] += space;
842 
843 	est_used = dsl_dir_estimated_space(dd);
844 	parent_space = parent_delta(dd, est_used, space);
845 	mutex_exit(&dd->dd_lock);
846 
847 	/* Make sure that we clean up dd_space_to* */
848 	dsl_dir_dirty(dd, tx);
849 
850 	/* XXX this is potentially expensive and unnecessary... */
851 	if (parent_space && dd->dd_parent)
852 		dsl_dir_willuse_space(dd->dd_parent, parent_space, tx);
853 }
854 
855 /* call from syncing context when we actually write/free space for this dd */
856 void
857 dsl_dir_diduse_space(dsl_dir_t *dd,
858     int64_t used, int64_t compressed, int64_t uncompressed, dmu_tx_t *tx)
859 {
860 	int64_t accounted_delta;
861 
862 	ASSERT(dmu_tx_is_syncing(tx));
863 
864 	dsl_dir_dirty(dd, tx);
865 
866 	mutex_enter(&dd->dd_lock);
867 	accounted_delta = parent_delta(dd, dd->dd_used_bytes, used);
868 	ASSERT(used >= 0 || dd->dd_used_bytes >= -used);
869 	ASSERT(compressed >= 0 ||
870 	    dd->dd_phys->dd_compressed_bytes >= -compressed);
871 	ASSERT(uncompressed >= 0 ||
872 	    dd->dd_phys->dd_uncompressed_bytes >= -uncompressed);
873 	dd->dd_used_bytes += used;
874 	dd->dd_phys->dd_uncompressed_bytes += uncompressed;
875 	dd->dd_phys->dd_compressed_bytes += compressed;
876 	mutex_exit(&dd->dd_lock);
877 
878 	if (dd->dd_parent != NULL) {
879 		dsl_dir_diduse_space(dd->dd_parent,
880 		    accounted_delta, compressed, uncompressed, tx);
881 	}
882 }
883 
884 /* ARGSUSED */
885 static int
886 dsl_dir_set_quota_check(void *arg1, void *arg2, dmu_tx_t *tx)
887 {
888 	dsl_dir_t *dd = arg1;
889 	uint64_t *quotap = arg2;
890 	uint64_t new_quota = *quotap;
891 	int err = 0;
892 	uint64_t towrite;
893 
894 	if (new_quota == 0)
895 		return (0);
896 
897 	mutex_enter(&dd->dd_lock);
898 	/*
899 	 * If we are doing the preliminary check in open context, and
900 	 * there are pending changes, then don't fail it, since the
901 	 * pending changes could under-estimat the amount of space to be
902 	 * freed up.
903 	 */
904 	towrite = dd->dd_space_towrite[0] + dd->dd_space_towrite[1] +
905 	    dd->dd_space_towrite[2] + dd->dd_space_towrite[3];
906 	if ((dmu_tx_is_syncing(tx) || towrite == 0) &&
907 	    (new_quota < dd->dd_phys->dd_reserved ||
908 	    new_quota < dsl_dir_estimated_space(dd))) {
909 		err = ENOSPC;
910 	}
911 	mutex_exit(&dd->dd_lock);
912 	return (err);
913 }
914 
915 static void
916 dsl_dir_set_quota_sync(void *arg1, void *arg2, dmu_tx_t *tx)
917 {
918 	dsl_dir_t *dd = arg1;
919 	uint64_t *quotap = arg2;
920 	uint64_t new_quota = *quotap;
921 
922 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
923 
924 	mutex_enter(&dd->dd_lock);
925 	dd->dd_phys->dd_quota = new_quota;
926 	mutex_exit(&dd->dd_lock);
927 }
928 
929 int
930 dsl_dir_set_quota(const char *ddname, uint64_t quota)
931 {
932 	dsl_dir_t *dd;
933 	int err;
934 
935 	err = dsl_dir_open(ddname, FTAG, &dd, NULL);
936 	if (err)
937 		return (err);
938 	/*
939 	 * If someone removes a file, then tries to set the quota, we
940 	 * want to make sure the file freeing takes effect.
941 	 */
942 	txg_wait_open(dd->dd_pool, 0);
943 
944 	err = dsl_sync_task_do(dd->dd_pool, dsl_dir_set_quota_check,
945 	    dsl_dir_set_quota_sync, dd, &quota, 0);
946 	dsl_dir_close(dd, FTAG);
947 	return (err);
948 }
949 
950 /* ARGSUSED */
951 static int
952 dsl_dir_set_reservation_check(void *arg1, void *arg2, dmu_tx_t *tx)
953 {
954 	dsl_dir_t *dd = arg1;
955 	uint64_t *reservationp = arg2;
956 	uint64_t new_reservation = *reservationp;
957 	uint64_t used, avail;
958 	int64_t delta;
959 
960 	if (new_reservation > INT64_MAX)
961 		return (EOVERFLOW);
962 
963 	/*
964 	 * If we are doing the preliminary check in open context, the
965 	 * space estimates may be inaccurate.
966 	 */
967 	if (!dmu_tx_is_syncing(tx))
968 		return (0);
969 
970 	mutex_enter(&dd->dd_lock);
971 	used = dd->dd_used_bytes;
972 	delta = MAX(used, new_reservation) -
973 	    MAX(used, dd->dd_phys->dd_reserved);
974 	mutex_exit(&dd->dd_lock);
975 
976 	if (dd->dd_parent) {
977 		avail = dsl_dir_space_available(dd->dd_parent,
978 		    NULL, 0, FALSE);
979 	} else {
980 		avail = dsl_pool_adjustedsize(dd->dd_pool, B_FALSE) - used;
981 	}
982 
983 	if (delta > 0 && delta > avail)
984 		return (ENOSPC);
985 	if (delta > 0 && dd->dd_phys->dd_quota > 0 &&
986 	    new_reservation > dd->dd_phys->dd_quota)
987 		return (ENOSPC);
988 	return (0);
989 }
990 
991 static void
992 dsl_dir_set_reservation_sync(void *arg1, void *arg2, dmu_tx_t *tx)
993 {
994 	dsl_dir_t *dd = arg1;
995 	uint64_t *reservationp = arg2;
996 	uint64_t new_reservation = *reservationp;
997 	uint64_t used;
998 	int64_t delta;
999 
1000 	mutex_enter(&dd->dd_lock);
1001 	used = dd->dd_used_bytes;
1002 	delta = MAX(used, new_reservation) -
1003 	    MAX(used, dd->dd_phys->dd_reserved);
1004 	mutex_exit(&dd->dd_lock);
1005 
1006 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1007 	dd->dd_phys->dd_reserved = new_reservation;
1008 
1009 	if (dd->dd_parent != NULL) {
1010 		/* Roll up this additional usage into our ancestors */
1011 		dsl_dir_diduse_space(dd->dd_parent, delta, 0, 0, tx);
1012 	}
1013 }
1014 
1015 int
1016 dsl_dir_set_reservation(const char *ddname, uint64_t reservation)
1017 {
1018 	dsl_dir_t *dd;
1019 	int err;
1020 
1021 	err = dsl_dir_open(ddname, FTAG, &dd, NULL);
1022 	if (err)
1023 		return (err);
1024 	err = dsl_sync_task_do(dd->dd_pool, dsl_dir_set_reservation_check,
1025 	    dsl_dir_set_reservation_sync, dd, &reservation, 0);
1026 	dsl_dir_close(dd, FTAG);
1027 	return (err);
1028 }
1029 
1030 static dsl_dir_t *
1031 closest_common_ancestor(dsl_dir_t *ds1, dsl_dir_t *ds2)
1032 {
1033 	for (; ds1; ds1 = ds1->dd_parent) {
1034 		dsl_dir_t *dd;
1035 		for (dd = ds2; dd; dd = dd->dd_parent) {
1036 			if (ds1 == dd)
1037 				return (dd);
1038 		}
1039 	}
1040 	return (NULL);
1041 }
1042 
1043 /*
1044  * If delta is applied to dd, how much of that delta would be applied to
1045  * ancestor?  Syncing context only.
1046  */
1047 static int64_t
1048 would_change(dsl_dir_t *dd, int64_t delta, dsl_dir_t *ancestor)
1049 {
1050 	if (dd == ancestor)
1051 		return (delta);
1052 
1053 	mutex_enter(&dd->dd_lock);
1054 	delta = parent_delta(dd, dd->dd_used_bytes, delta);
1055 	mutex_exit(&dd->dd_lock);
1056 	return (would_change(dd->dd_parent, delta, ancestor));
1057 }
1058 
1059 struct renamearg {
1060 	dsl_dir_t *newparent;
1061 	const char *mynewname;
1062 };
1063 
1064 /* ARGSUSED */
1065 static int
1066 dsl_dir_rename_check(void *arg1, void *arg2, dmu_tx_t *tx)
1067 {
1068 	dsl_dir_t *dd = arg1;
1069 	struct renamearg *ra = arg2;
1070 	dsl_pool_t *dp = dd->dd_pool;
1071 	objset_t *mos = dp->dp_meta_objset;
1072 	int err;
1073 	uint64_t val;
1074 
1075 	/* There should be 2 references: the open and the dirty */
1076 	if (dmu_buf_refcount(dd->dd_dbuf) > 2)
1077 		return (EBUSY);
1078 
1079 	/* check for existing name */
1080 	err = zap_lookup(mos, ra->newparent->dd_phys->dd_child_dir_zapobj,
1081 	    ra->mynewname, 8, 1, &val);
1082 	if (err == 0)
1083 		return (EEXIST);
1084 	if (err != ENOENT)
1085 		return (err);
1086 
1087 	if (ra->newparent != dd->dd_parent) {
1088 		/* is there enough space? */
1089 		uint64_t myspace =
1090 		    MAX(dd->dd_used_bytes, dd->dd_phys->dd_reserved);
1091 
1092 		/* no rename into our descendant */
1093 		if (closest_common_ancestor(dd, ra->newparent) == dd)
1094 			return (EINVAL);
1095 
1096 		if (err = dsl_dir_transfer_possible(dd->dd_parent,
1097 		    ra->newparent, myspace))
1098 			return (err);
1099 	}
1100 
1101 	return (0);
1102 }
1103 
1104 static void
1105 dsl_dir_rename_sync(void *arg1, void *arg2, dmu_tx_t *tx)
1106 {
1107 	dsl_dir_t *dd = arg1;
1108 	struct renamearg *ra = arg2;
1109 	dsl_pool_t *dp = dd->dd_pool;
1110 	objset_t *mos = dp->dp_meta_objset;
1111 	int err;
1112 
1113 	ASSERT(dmu_buf_refcount(dd->dd_dbuf) <= 2);
1114 
1115 	if (ra->newparent != dd->dd_parent) {
1116 		uint64_t myspace =
1117 		    MAX(dd->dd_used_bytes, dd->dd_phys->dd_reserved);
1118 
1119 		dsl_dir_diduse_space(dd->dd_parent, -myspace,
1120 		    -dd->dd_phys->dd_compressed_bytes,
1121 		    -dd->dd_phys->dd_uncompressed_bytes, tx);
1122 		dsl_dir_diduse_space(ra->newparent, myspace,
1123 		    dd->dd_phys->dd_compressed_bytes,
1124 		    dd->dd_phys->dd_uncompressed_bytes, tx);
1125 	}
1126 
1127 	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1128 
1129 	/* remove from old parent zapobj */
1130 	err = zap_remove(mos, dd->dd_parent->dd_phys->dd_child_dir_zapobj,
1131 	    dd->dd_myname, tx);
1132 	ASSERT3U(err, ==, 0);
1133 
1134 	(void) strcpy(dd->dd_myname, ra->mynewname);
1135 	dsl_dir_close(dd->dd_parent, dd);
1136 	dd->dd_phys->dd_parent_obj = ra->newparent->dd_object;
1137 	VERIFY(0 == dsl_dir_open_obj(dd->dd_pool,
1138 	    ra->newparent->dd_object, NULL, dd, &dd->dd_parent));
1139 
1140 	/* add to new parent zapobj */
1141 	err = zap_add(mos, ra->newparent->dd_phys->dd_child_dir_zapobj,
1142 	    dd->dd_myname, 8, 1, &dd->dd_object, tx);
1143 	ASSERT3U(err, ==, 0);
1144 }
1145 
1146 int
1147 dsl_dir_rename(dsl_dir_t *dd, const char *newname)
1148 {
1149 	struct renamearg ra;
1150 	int err;
1151 
1152 	/* new parent should exist */
1153 	err = dsl_dir_open(newname, FTAG, &ra.newparent, &ra.mynewname);
1154 	if (err)
1155 		return (err);
1156 
1157 	/* can't rename to different pool */
1158 	if (dd->dd_pool != ra.newparent->dd_pool) {
1159 		err = ENXIO;
1160 		goto out;
1161 	}
1162 
1163 	/* new name should not already exist */
1164 	if (ra.mynewname == NULL) {
1165 		err = EEXIST;
1166 		goto out;
1167 	}
1168 
1169 
1170 	err = dsl_sync_task_do(dd->dd_pool,
1171 	    dsl_dir_rename_check, dsl_dir_rename_sync, dd, &ra, 3);
1172 
1173 out:
1174 	dsl_dir_close(ra.newparent, FTAG);
1175 	return (err);
1176 }
1177 
1178 int
1179 dsl_dir_transfer_possible(dsl_dir_t *sdd, dsl_dir_t *tdd, uint64_t space)
1180 {
1181 	dsl_dir_t *ancestor;
1182 	int64_t adelta;
1183 	uint64_t avail;
1184 
1185 	ancestor = closest_common_ancestor(sdd, tdd);
1186 	adelta = would_change(sdd, -space, ancestor);
1187 	avail = dsl_dir_space_available(tdd, ancestor, adelta, FALSE);
1188 	if (avail < space)
1189 		return (ENOSPC);
1190 
1191 	return (0);
1192 }
1193