1168404Spjd/*
2168404Spjd * CDDL HEADER START
3168404Spjd *
4168404Spjd * The contents of this file are subject to the terms of the
5168404Spjd * Common Development and Distribution License (the "License").
6168404Spjd * You may not use this file except in compliance with the License.
7168404Spjd *
8168404Spjd * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9168404Spjd * or http://www.opensolaris.org/os/licensing.
10168404Spjd * See the License for the specific language governing permissions
11168404Spjd * and limitations under the License.
12168404Spjd *
13168404Spjd * When distributing Covered Code, include this CDDL HEADER in each
14168404Spjd * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15168404Spjd * If applicable, add the following below this CDDL HEADER, with the
16168404Spjd * fields enclosed by brackets "[]" replaced with your own identifying
17168404Spjd * information: Portions Copyright [yyyy] [name of copyright owner]
18168404Spjd *
19168404Spjd * CDDL HEADER END
20168404Spjd */
21168404Spjd/*
22219089Spjd * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23226707Spjd * Copyright (c) 2011 Pawel Jakub Dawidek <pawel@dawidek.net>.
24226707Spjd * All rights reserved.
25269006Sdelphij * Copyright (c) 2012, 2014 by Delphix. All rights reserved.
26265744Sdelphij * Copyright (c) 2014 Joyent, Inc. All rights reserved.
27168404Spjd */
28168404Spjd
29168404Spjd#include <sys/dmu.h>
30185029Spjd#include <sys/dmu_objset.h>
31168404Spjd#include <sys/dmu_tx.h>
32168404Spjd#include <sys/dsl_dataset.h>
33168404Spjd#include <sys/dsl_dir.h>
34168404Spjd#include <sys/dsl_prop.h>
35168404Spjd#include <sys/dsl_synctask.h>
36185029Spjd#include <sys/dsl_deleg.h>
37263390Sdelphij#include <sys/dmu_impl.h>
38168404Spjd#include <sys/spa.h>
39219089Spjd#include <sys/metaslab.h>
40168404Spjd#include <sys/zap.h>
41168404Spjd#include <sys/zio.h>
42168404Spjd#include <sys/arc.h>
43185029Spjd#include <sys/sunddi.h>
44219317Spjd#include <sys/zvol.h>
45226678Spjd#ifdef _KERNEL
46226676Spjd#include <sys/zfs_vfsops.h>
47226678Spjd#endif
48265744Sdelphij#include <sys/zfeature.h>
49265744Sdelphij#include <sys/policy.h>
50265744Sdelphij#include <sys/zfs_znode.h>
51168404Spjd#include "zfs_namecheck.h"
52265744Sdelphij#include "zfs_prop.h"
53168404Spjd
54265744Sdelphij/*
55265744Sdelphij * Filesystem and Snapshot Limits
56265744Sdelphij * ------------------------------
57265744Sdelphij *
58265744Sdelphij * These limits are used to restrict the number of filesystems and/or snapshots
59265744Sdelphij * that can be created at a given level in the tree or below. A typical
60265744Sdelphij * use-case is with a delegated dataset where the administrator wants to ensure
61265744Sdelphij * that a user within the zone is not creating too many additional filesystems
62265744Sdelphij * or snapshots, even though they're not exceeding their space quota.
63265744Sdelphij *
64265744Sdelphij * The filesystem and snapshot counts are stored as extensible properties. This
65265744Sdelphij * capability is controlled by a feature flag and must be enabled to be used.
66265744Sdelphij * Once enabled, the feature is not active until the first limit is set. At
67265744Sdelphij * that point, future operations to create/destroy filesystems or snapshots
68265744Sdelphij * will validate and update the counts.
69265744Sdelphij *
70265744Sdelphij * Because the count properties will not exist before the feature is active,
71265744Sdelphij * the counts are updated when a limit is first set on an uninitialized
72265744Sdelphij * dsl_dir node in the tree (The filesystem/snapshot count on a node includes
73265744Sdelphij * all of the nested filesystems/snapshots. Thus, a new leaf node has a
74265744Sdelphij * filesystem count of 0 and a snapshot count of 0. Non-existent filesystem and
75265744Sdelphij * snapshot count properties on a node indicate uninitialized counts on that
76265744Sdelphij * node.) When first setting a limit on an uninitialized node, the code starts
77265744Sdelphij * at the filesystem with the new limit and descends into all sub-filesystems
78265744Sdelphij * to add the count properties.
79265744Sdelphij *
80265744Sdelphij * In practice this is lightweight since a limit is typically set when the
81265744Sdelphij * filesystem is created and thus has no children. Once valid, changing the
82265744Sdelphij * limit value won't require a re-traversal since the counts are already valid.
83265744Sdelphij * When recursively fixing the counts, if a node with a limit is encountered
84265744Sdelphij * during the descent, the counts are known to be valid and there is no need to
85265744Sdelphij * descend into that filesystem's children. The counts on filesystems above the
86265744Sdelphij * one with the new limit will still be uninitialized, unless a limit is
87265744Sdelphij * eventually set on one of those filesystems. The counts are always recursively
88265744Sdelphij * updated when a limit is set on a dataset, unless there is already a limit.
89265744Sdelphij * When a new limit value is set on a filesystem with an existing limit, it is
90265744Sdelphij * possible for the new limit to be less than the current count at that level
91265744Sdelphij * since a user who can change the limit is also allowed to exceed the limit.
92265744Sdelphij *
93265744Sdelphij * Once the feature is active, then whenever a filesystem or snapshot is
94265744Sdelphij * created, the code recurses up the tree, validating the new count against the
95265744Sdelphij * limit at each initialized level. In practice, most levels will not have a
96265744Sdelphij * limit set. If there is a limit at any initialized level up the tree, the
97265744Sdelphij * check must pass or the creation will fail. Likewise, when a filesystem or
98265744Sdelphij * snapshot is destroyed, the counts are recursively adjusted all the way up
99265744Sdelphij * the initizized nodes in the tree. Renaming a filesystem into different point
100265744Sdelphij * in the tree will first validate, then update the counts on each branch up to
101265744Sdelphij * the common ancestor. A receive will also validate the counts and then update
102265744Sdelphij * them.
103265744Sdelphij *
104265744Sdelphij * An exception to the above behavior is that the limit is not enforced if the
105265744Sdelphij * user has permission to modify the limit. This is primarily so that
106265744Sdelphij * recursive snapshots in the global zone always work. We want to prevent a
107265744Sdelphij * denial-of-service in which a lower level delegated dataset could max out its
108265744Sdelphij * limit and thus block recursive snapshots from being taken in the global zone.
109265744Sdelphij * Because of this, it is possible for the snapshot count to be over the limit
110265744Sdelphij * and snapshots taken in the global zone could cause a lower level dataset to
111265744Sdelphij * hit or exceed its limit. The administrator taking the global zone recursive
112265744Sdelphij * snapshot should be aware of this side-effect and behave accordingly.
113265744Sdelphij * For consistency, the filesystem limit is also not enforced if the user can
114265744Sdelphij * modify the limit.
115265744Sdelphij *
116265744Sdelphij * The filesystem and snapshot limits are validated by dsl_fs_ss_limit_check()
117265744Sdelphij * and updated by dsl_fs_ss_count_adjust(). A new limit value is setup in
118265744Sdelphij * dsl_dir_activate_fs_ss_limit() and the counts are adjusted, if necessary, by
119265744Sdelphij * dsl_dir_init_fs_ss_count().
120265744Sdelphij *
121265744Sdelphij * There is a special case when we receive a filesystem that already exists. In
122265744Sdelphij * this case a temporary clone name of %X is created (see dmu_recv_begin). We
123265744Sdelphij * never update the filesystem counts for temporary clones.
124265744Sdelphij *
125265744Sdelphij * Likewise, we do not update the snapshot counts for temporary snapshots,
126265744Sdelphij * such as those created by zfs diff.
127265744Sdelphij */
128265744Sdelphij
129185029Spjdstatic uint64_t dsl_dir_space_towrite(dsl_dir_t *dd);
130168404Spjd
131168404Spjd/* ARGSUSED */
132168404Spjdstatic void
133168404Spjddsl_dir_evict(dmu_buf_t *db, void *arg)
134168404Spjd{
135168404Spjd	dsl_dir_t *dd = arg;
136168404Spjd	dsl_pool_t *dp = dd->dd_pool;
137168404Spjd	int t;
138168404Spjd
139168404Spjd	for (t = 0; t < TXG_SIZE; t++) {
140168404Spjd		ASSERT(!txg_list_member(&dp->dp_dirty_dirs, dd, t));
141168404Spjd		ASSERT(dd->dd_tempreserved[t] == 0);
142168404Spjd		ASSERT(dd->dd_space_towrite[t] == 0);
143168404Spjd	}
144168404Spjd
145168404Spjd	if (dd->dd_parent)
146248571Smm		dsl_dir_rele(dd->dd_parent, dd);
147168404Spjd
148168404Spjd	spa_close(dd->dd_pool->dp_spa, dd);
149168404Spjd
150168404Spjd	/*
151219089Spjd	 * The props callback list should have been cleaned up by
152219089Spjd	 * objset_evict().
153168404Spjd	 */
154168404Spjd	list_destroy(&dd->dd_prop_cbs);
155168404Spjd	mutex_destroy(&dd->dd_lock);
156168404Spjd	kmem_free(dd, sizeof (dsl_dir_t));
157168404Spjd}
158168404Spjd
159168404Spjdint
160248571Smmdsl_dir_hold_obj(dsl_pool_t *dp, uint64_t ddobj,
161168404Spjd    const char *tail, void *tag, dsl_dir_t **ddp)
162168404Spjd{
163168404Spjd	dmu_buf_t *dbuf;
164168404Spjd	dsl_dir_t *dd;
165168404Spjd	int err;
166168404Spjd
167248571Smm	ASSERT(dsl_pool_config_held(dp));
168168404Spjd
169168404Spjd	err = dmu_bonus_hold(dp->dp_meta_objset, ddobj, tag, &dbuf);
170248571Smm	if (err != 0)
171168404Spjd		return (err);
172168404Spjd	dd = dmu_buf_get_user(dbuf);
173168404Spjd#ifdef ZFS_DEBUG
174168404Spjd	{
175168404Spjd		dmu_object_info_t doi;
176168404Spjd		dmu_object_info_from_db(dbuf, &doi);
177263390Sdelphij		ASSERT3U(doi.doi_bonus_type, ==, DMU_OT_DSL_DIR);
178185029Spjd		ASSERT3U(doi.doi_bonus_size, >=, sizeof (dsl_dir_phys_t));
179168404Spjd	}
180168404Spjd#endif
181168404Spjd	if (dd == NULL) {
182168404Spjd		dsl_dir_t *winner;
183168404Spjd
184168404Spjd		dd = kmem_zalloc(sizeof (dsl_dir_t), KM_SLEEP);
185168404Spjd		dd->dd_object = ddobj;
186168404Spjd		dd->dd_dbuf = dbuf;
187168404Spjd		dd->dd_pool = dp;
188168404Spjd		dd->dd_phys = dbuf->db_data;
189168404Spjd		mutex_init(&dd->dd_lock, NULL, MUTEX_DEFAULT, NULL);
190168404Spjd
191168404Spjd		list_create(&dd->dd_prop_cbs, sizeof (dsl_prop_cb_record_t),
192168404Spjd		    offsetof(dsl_prop_cb_record_t, cbr_node));
193168404Spjd
194219089Spjd		dsl_dir_snap_cmtime_update(dd);
195219089Spjd
196168404Spjd		if (dd->dd_phys->dd_parent_obj) {
197248571Smm			err = dsl_dir_hold_obj(dp, dd->dd_phys->dd_parent_obj,
198168404Spjd			    NULL, dd, &dd->dd_parent);
199248571Smm			if (err != 0)
200185029Spjd				goto errout;
201168404Spjd			if (tail) {
202168404Spjd#ifdef ZFS_DEBUG
203168404Spjd				uint64_t foundobj;
204168404Spjd
205168404Spjd				err = zap_lookup(dp->dp_meta_objset,
206185029Spjd				    dd->dd_parent->dd_phys->dd_child_dir_zapobj,
207168404Spjd				    tail, sizeof (foundobj), 1, &foundobj);
208168404Spjd				ASSERT(err || foundobj == ddobj);
209168404Spjd#endif
210168404Spjd				(void) strcpy(dd->dd_myname, tail);
211168404Spjd			} else {
212168404Spjd				err = zap_value_search(dp->dp_meta_objset,
213185029Spjd				    dd->dd_parent->dd_phys->dd_child_dir_zapobj,
214185029Spjd				    ddobj, 0, dd->dd_myname);
215168404Spjd			}
216248571Smm			if (err != 0)
217185029Spjd				goto errout;
218168404Spjd		} else {
219168404Spjd			(void) strcpy(dd->dd_myname, spa_name(dp->dp_spa));
220168404Spjd		}
221168404Spjd
222219089Spjd		if (dsl_dir_is_clone(dd)) {
223219089Spjd			dmu_buf_t *origin_bonus;
224219089Spjd			dsl_dataset_phys_t *origin_phys;
225219089Spjd
226219089Spjd			/*
227219089Spjd			 * We can't open the origin dataset, because
228219089Spjd			 * that would require opening this dsl_dir.
229219089Spjd			 * Just look at its phys directly instead.
230219089Spjd			 */
231219089Spjd			err = dmu_bonus_hold(dp->dp_meta_objset,
232219089Spjd			    dd->dd_phys->dd_origin_obj, FTAG, &origin_bonus);
233248571Smm			if (err != 0)
234219089Spjd				goto errout;
235219089Spjd			origin_phys = origin_bonus->db_data;
236219089Spjd			dd->dd_origin_txg =
237219089Spjd			    origin_phys->ds_creation_txg;
238219089Spjd			dmu_buf_rele(origin_bonus, FTAG);
239219089Spjd		}
240219089Spjd
241168404Spjd		winner = dmu_buf_set_user_ie(dbuf, dd, &dd->dd_phys,
242168404Spjd		    dsl_dir_evict);
243168404Spjd		if (winner) {
244168404Spjd			if (dd->dd_parent)
245248571Smm				dsl_dir_rele(dd->dd_parent, dd);
246168404Spjd			mutex_destroy(&dd->dd_lock);
247168404Spjd			kmem_free(dd, sizeof (dsl_dir_t));
248168404Spjd			dd = winner;
249168404Spjd		} else {
250168404Spjd			spa_open_ref(dp->dp_spa, dd);
251168404Spjd		}
252168404Spjd	}
253168404Spjd
254168404Spjd	/*
255168404Spjd	 * The dsl_dir_t has both open-to-close and instantiate-to-evict
256168404Spjd	 * holds on the spa.  We need the open-to-close holds because
257168404Spjd	 * otherwise the spa_refcnt wouldn't change when we open a
258168404Spjd	 * dir which the spa also has open, so we could incorrectly
259168404Spjd	 * think it was OK to unload/export/destroy the pool.  We need
260168404Spjd	 * the instantiate-to-evict hold because the dsl_dir_t has a
261168404Spjd	 * pointer to the dd_pool, which has a pointer to the spa_t.
262168404Spjd	 */
263168404Spjd	spa_open_ref(dp->dp_spa, tag);
264168404Spjd	ASSERT3P(dd->dd_pool, ==, dp);
265168404Spjd	ASSERT3U(dd->dd_object, ==, ddobj);
266168404Spjd	ASSERT3P(dd->dd_dbuf, ==, dbuf);
267168404Spjd	*ddp = dd;
268168404Spjd	return (0);
269185029Spjd
270185029Spjderrout:
271185029Spjd	if (dd->dd_parent)
272248571Smm		dsl_dir_rele(dd->dd_parent, dd);
273185029Spjd	mutex_destroy(&dd->dd_lock);
274185029Spjd	kmem_free(dd, sizeof (dsl_dir_t));
275185029Spjd	dmu_buf_rele(dbuf, tag);
276185029Spjd	return (err);
277168404Spjd}
278168404Spjd
279168404Spjdvoid
280248571Smmdsl_dir_rele(dsl_dir_t *dd, void *tag)
281168404Spjd{
282168404Spjd	dprintf_dd(dd, "%s\n", "");
283168404Spjd	spa_close(dd->dd_pool->dp_spa, tag);
284168404Spjd	dmu_buf_rele(dd->dd_dbuf, tag);
285168404Spjd}
286168404Spjd
287168404Spjd/* buf must be long enough (MAXNAMELEN + strlen(MOS_DIR_NAME) + 1 should do) */
288168404Spjdvoid
289168404Spjddsl_dir_name(dsl_dir_t *dd, char *buf)
290168404Spjd{
291168404Spjd	if (dd->dd_parent) {
292168404Spjd		dsl_dir_name(dd->dd_parent, buf);
293168404Spjd		(void) strcat(buf, "/");
294168404Spjd	} else {
295168404Spjd		buf[0] = '\0';
296168404Spjd	}
297168404Spjd	if (!MUTEX_HELD(&dd->dd_lock)) {
298168404Spjd		/*
299168404Spjd		 * recursive mutex so that we can use
300168404Spjd		 * dprintf_dd() with dd_lock held
301168404Spjd		 */
302168404Spjd		mutex_enter(&dd->dd_lock);
303168404Spjd		(void) strcat(buf, dd->dd_myname);
304168404Spjd		mutex_exit(&dd->dd_lock);
305168404Spjd	} else {
306168404Spjd		(void) strcat(buf, dd->dd_myname);
307168404Spjd	}
308168404Spjd}
309168404Spjd
310239620Smm/* Calculate name length, avoiding all the strcat calls of dsl_dir_name */
311168404Spjdint
312168498Spjddsl_dir_namelen(dsl_dir_t *dd)
313168498Spjd{
314168498Spjd	int result = 0;
315168498Spjd
316168498Spjd	if (dd->dd_parent) {
317168498Spjd		/* parent's name + 1 for the "/" */
318168498Spjd		result = dsl_dir_namelen(dd->dd_parent) + 1;
319168498Spjd	}
320168498Spjd
321168498Spjd	if (!MUTEX_HELD(&dd->dd_lock)) {
322168498Spjd		/* see dsl_dir_name */
323168498Spjd		mutex_enter(&dd->dd_lock);
324168498Spjd		result += strlen(dd->dd_myname);
325168498Spjd		mutex_exit(&dd->dd_lock);
326168498Spjd	} else {
327168498Spjd		result += strlen(dd->dd_myname);
328168498Spjd	}
329168498Spjd
330168498Spjd	return (result);
331168498Spjd}
332168498Spjd
333168404Spjdstatic int
334168404Spjdgetcomponent(const char *path, char *component, const char **nextp)
335168404Spjd{
336168404Spjd	char *p;
337248571Smm
338209962Smm	if ((path == NULL) || (path[0] == '\0'))
339249195Smm		return (SET_ERROR(ENOENT));
340168404Spjd	/* This would be a good place to reserve some namespace... */
341168404Spjd	p = strpbrk(path, "/@");
342168404Spjd	if (p && (p[1] == '/' || p[1] == '@')) {
343168404Spjd		/* two separators in a row */
344249195Smm		return (SET_ERROR(EINVAL));
345168404Spjd	}
346168404Spjd	if (p == NULL || p == path) {
347168404Spjd		/*
348168404Spjd		 * if the first thing is an @ or /, it had better be an
349168404Spjd		 * @ and it had better not have any more ats or slashes,
350168404Spjd		 * and it had better have something after the @.
351168404Spjd		 */
352168404Spjd		if (p != NULL &&
353168404Spjd		    (p[0] != '@' || strpbrk(path+1, "/@") || p[1] == '\0'))
354249195Smm			return (SET_ERROR(EINVAL));
355168404Spjd		if (strlen(path) >= MAXNAMELEN)
356249195Smm			return (SET_ERROR(ENAMETOOLONG));
357168404Spjd		(void) strcpy(component, path);
358168404Spjd		p = NULL;
359168404Spjd	} else if (p[0] == '/') {
360248571Smm		if (p - path >= MAXNAMELEN)
361249195Smm			return (SET_ERROR(ENAMETOOLONG));
362168404Spjd		(void) strncpy(component, path, p - path);
363248571Smm		component[p - path] = '\0';
364168404Spjd		p++;
365168404Spjd	} else if (p[0] == '@') {
366168404Spjd		/*
367168404Spjd		 * if the next separator is an @, there better not be
368168404Spjd		 * any more slashes.
369168404Spjd		 */
370168404Spjd		if (strchr(path, '/'))
371249195Smm			return (SET_ERROR(EINVAL));
372248571Smm		if (p - path >= MAXNAMELEN)
373249195Smm			return (SET_ERROR(ENAMETOOLONG));
374168404Spjd		(void) strncpy(component, path, p - path);
375248571Smm		component[p - path] = '\0';
376168404Spjd	} else {
377248571Smm		panic("invalid p=%p", (void *)p);
378168404Spjd	}
379168404Spjd	*nextp = p;
380168404Spjd	return (0);
381168404Spjd}
382168404Spjd
383168404Spjd/*
384248571Smm * Return the dsl_dir_t, and possibly the last component which couldn't
385248571Smm * be found in *tail.  The name must be in the specified dsl_pool_t.  This
386248571Smm * thread must hold the dp_config_rwlock for the pool.  Returns NULL if the
387248571Smm * path is bogus, or if tail==NULL and we couldn't parse the whole name.
388248571Smm * (*tail)[0] == '@' means that the last component is a snapshot.
389168404Spjd */
390168404Spjdint
391248571Smmdsl_dir_hold(dsl_pool_t *dp, const char *name, void *tag,
392168404Spjd    dsl_dir_t **ddp, const char **tailp)
393168404Spjd{
394168404Spjd	char buf[MAXNAMELEN];
395248571Smm	const char *spaname, *next, *nextnext = NULL;
396168404Spjd	int err;
397168404Spjd	dsl_dir_t *dd;
398168404Spjd	uint64_t ddobj;
399168404Spjd
400168404Spjd	err = getcomponent(name, buf, &next);
401248571Smm	if (err != 0)
402168404Spjd		return (err);
403168404Spjd
404248571Smm	/* Make sure the name is in the specified pool. */
405248571Smm	spaname = spa_name(dp->dp_spa);
406248571Smm	if (strcmp(buf, spaname) != 0)
407249195Smm		return (SET_ERROR(EINVAL));
408168404Spjd
409248571Smm	ASSERT(dsl_pool_config_held(dp));
410168404Spjd
411248571Smm	err = dsl_dir_hold_obj(dp, dp->dp_root_dir_obj, NULL, tag, &dd);
412248571Smm	if (err != 0) {
413168404Spjd		return (err);
414168404Spjd	}
415168404Spjd
416168404Spjd	while (next != NULL) {
417168404Spjd		dsl_dir_t *child_ds;
418168404Spjd		err = getcomponent(next, buf, &nextnext);
419248571Smm		if (err != 0)
420168404Spjd			break;
421168404Spjd		ASSERT(next[0] != '\0');
422168404Spjd		if (next[0] == '@')
423168404Spjd			break;
424168404Spjd		dprintf("looking up %s in obj%lld\n",
425168404Spjd		    buf, dd->dd_phys->dd_child_dir_zapobj);
426168404Spjd
427168404Spjd		err = zap_lookup(dp->dp_meta_objset,
428168404Spjd		    dd->dd_phys->dd_child_dir_zapobj,
429168404Spjd		    buf, sizeof (ddobj), 1, &ddobj);
430248571Smm		if (err != 0) {
431168404Spjd			if (err == ENOENT)
432168404Spjd				err = 0;
433168404Spjd			break;
434168404Spjd		}
435168404Spjd
436248571Smm		err = dsl_dir_hold_obj(dp, ddobj, buf, tag, &child_ds);
437248571Smm		if (err != 0)
438168404Spjd			break;
439248571Smm		dsl_dir_rele(dd, tag);
440168404Spjd		dd = child_ds;
441168404Spjd		next = nextnext;
442168404Spjd	}
443168404Spjd
444248571Smm	if (err != 0) {
445248571Smm		dsl_dir_rele(dd, tag);
446168404Spjd		return (err);
447168404Spjd	}
448168404Spjd
449168404Spjd	/*
450168404Spjd	 * It's an error if there's more than one component left, or
451168404Spjd	 * tailp==NULL and there's any component left.
452168404Spjd	 */
453168404Spjd	if (next != NULL &&
454168404Spjd	    (tailp == NULL || (nextnext && nextnext[0] != '\0'))) {
455168404Spjd		/* bad path name */
456248571Smm		dsl_dir_rele(dd, tag);
457168404Spjd		dprintf("next=%p (%s) tail=%p\n", next, next?next:"", tailp);
458249195Smm		err = SET_ERROR(ENOENT);
459168404Spjd	}
460248571Smm	if (tailp != NULL)
461168404Spjd		*tailp = next;
462168404Spjd	*ddp = dd;
463168404Spjd	return (err);
464168404Spjd}
465168404Spjd
466265744Sdelphij/*
467265744Sdelphij * If the counts are already initialized for this filesystem and its
468265744Sdelphij * descendants then do nothing, otherwise initialize the counts.
469265744Sdelphij *
470265744Sdelphij * The counts on this filesystem, and those below, may be uninitialized due to
471265744Sdelphij * either the use of a pre-existing pool which did not support the
472265744Sdelphij * filesystem/snapshot limit feature, or one in which the feature had not yet
473265744Sdelphij * been enabled.
474265744Sdelphij *
475265744Sdelphij * Recursively descend the filesystem tree and update the filesystem/snapshot
476265744Sdelphij * counts on each filesystem below, then update the cumulative count on the
477265744Sdelphij * current filesystem. If the filesystem already has a count set on it,
478265744Sdelphij * then we know that its counts, and the counts on the filesystems below it,
479265744Sdelphij * are already correct, so we don't have to update this filesystem.
480265744Sdelphij */
481265744Sdelphijstatic void
482265744Sdelphijdsl_dir_init_fs_ss_count(dsl_dir_t *dd, dmu_tx_t *tx)
483265744Sdelphij{
484265744Sdelphij	uint64_t my_fs_cnt = 0;
485265744Sdelphij	uint64_t my_ss_cnt = 0;
486265744Sdelphij	dsl_pool_t *dp = dd->dd_pool;
487265744Sdelphij	objset_t *os = dp->dp_meta_objset;
488265744Sdelphij	zap_cursor_t *zc;
489265744Sdelphij	zap_attribute_t *za;
490265744Sdelphij	dsl_dataset_t *ds;
491265744Sdelphij
492267138Sdelphij	ASSERT(spa_feature_is_active(dp->dp_spa, SPA_FEATURE_FS_SS_LIMIT));
493265744Sdelphij	ASSERT(dsl_pool_config_held(dp));
494265744Sdelphij	ASSERT(dmu_tx_is_syncing(tx));
495265744Sdelphij
496265744Sdelphij	dsl_dir_zapify(dd, tx);
497265744Sdelphij
498265744Sdelphij	/*
499265744Sdelphij	 * If the filesystem count has already been initialized then we
500265744Sdelphij	 * don't need to recurse down any further.
501265744Sdelphij	 */
502265744Sdelphij	if (zap_contains(os, dd->dd_object, DD_FIELD_FILESYSTEM_COUNT) == 0)
503265744Sdelphij		return;
504265744Sdelphij
505265744Sdelphij	zc = kmem_alloc(sizeof (zap_cursor_t), KM_SLEEP);
506265744Sdelphij	za = kmem_alloc(sizeof (zap_attribute_t), KM_SLEEP);
507265744Sdelphij
508265744Sdelphij	/* Iterate my child dirs */
509265744Sdelphij	for (zap_cursor_init(zc, os, dd->dd_phys->dd_child_dir_zapobj);
510265744Sdelphij	    zap_cursor_retrieve(zc, za) == 0; zap_cursor_advance(zc)) {
511265744Sdelphij		dsl_dir_t *chld_dd;
512265744Sdelphij		uint64_t count;
513265744Sdelphij
514265744Sdelphij		VERIFY0(dsl_dir_hold_obj(dp, za->za_first_integer, NULL, FTAG,
515265744Sdelphij		    &chld_dd));
516265744Sdelphij
517265744Sdelphij		/*
518265744Sdelphij		 * Ignore hidden ($FREE, $MOS & $ORIGIN) objsets and
519265744Sdelphij		 * temporary datasets.
520265744Sdelphij		 */
521265744Sdelphij		if (chld_dd->dd_myname[0] == '$' ||
522265744Sdelphij		    chld_dd->dd_myname[0] == '%') {
523265744Sdelphij			dsl_dir_rele(chld_dd, FTAG);
524265744Sdelphij			continue;
525265744Sdelphij		}
526265744Sdelphij
527265744Sdelphij		my_fs_cnt++;	/* count this child */
528265744Sdelphij
529265744Sdelphij		dsl_dir_init_fs_ss_count(chld_dd, tx);
530265744Sdelphij
531265744Sdelphij		VERIFY0(zap_lookup(os, chld_dd->dd_object,
532265744Sdelphij		    DD_FIELD_FILESYSTEM_COUNT, sizeof (count), 1, &count));
533265744Sdelphij		my_fs_cnt += count;
534265744Sdelphij		VERIFY0(zap_lookup(os, chld_dd->dd_object,
535265744Sdelphij		    DD_FIELD_SNAPSHOT_COUNT, sizeof (count), 1, &count));
536265744Sdelphij		my_ss_cnt += count;
537265744Sdelphij
538265744Sdelphij		dsl_dir_rele(chld_dd, FTAG);
539265744Sdelphij	}
540265744Sdelphij	zap_cursor_fini(zc);
541265744Sdelphij	/* Count my snapshots (we counted children's snapshots above) */
542265744Sdelphij	VERIFY0(dsl_dataset_hold_obj(dd->dd_pool,
543265744Sdelphij	    dd->dd_phys->dd_head_dataset_obj, FTAG, &ds));
544265744Sdelphij
545265744Sdelphij	for (zap_cursor_init(zc, os, ds->ds_phys->ds_snapnames_zapobj);
546265744Sdelphij	    zap_cursor_retrieve(zc, za) == 0;
547265744Sdelphij	    zap_cursor_advance(zc)) {
548265744Sdelphij		/* Don't count temporary snapshots */
549265744Sdelphij		if (za->za_name[0] != '%')
550265744Sdelphij			my_ss_cnt++;
551265744Sdelphij	}
552267138Sdelphij	zap_cursor_fini(zc);
553265744Sdelphij
554265744Sdelphij	dsl_dataset_rele(ds, FTAG);
555265744Sdelphij
556265744Sdelphij	kmem_free(zc, sizeof (zap_cursor_t));
557265744Sdelphij	kmem_free(za, sizeof (zap_attribute_t));
558265744Sdelphij
559265744Sdelphij	/* we're in a sync task, update counts */
560265744Sdelphij	dmu_buf_will_dirty(dd->dd_dbuf, tx);
561265744Sdelphij	VERIFY0(zap_add(os, dd->dd_object, DD_FIELD_FILESYSTEM_COUNT,
562265744Sdelphij	    sizeof (my_fs_cnt), 1, &my_fs_cnt, tx));
563265744Sdelphij	VERIFY0(zap_add(os, dd->dd_object, DD_FIELD_SNAPSHOT_COUNT,
564265744Sdelphij	    sizeof (my_ss_cnt), 1, &my_ss_cnt, tx));
565265744Sdelphij}
566265744Sdelphij
567265744Sdelphijstatic int
568265744Sdelphijdsl_dir_actv_fs_ss_limit_check(void *arg, dmu_tx_t *tx)
569265744Sdelphij{
570265744Sdelphij	char *ddname = (char *)arg;
571265744Sdelphij	dsl_pool_t *dp = dmu_tx_pool(tx);
572265744Sdelphij	dsl_dataset_t *ds;
573265744Sdelphij	dsl_dir_t *dd;
574265744Sdelphij	int error;
575265744Sdelphij
576265744Sdelphij	error = dsl_dataset_hold(dp, ddname, FTAG, &ds);
577265744Sdelphij	if (error != 0)
578265744Sdelphij		return (error);
579265744Sdelphij
580265744Sdelphij	if (!spa_feature_is_enabled(dp->dp_spa, SPA_FEATURE_FS_SS_LIMIT)) {
581265744Sdelphij		dsl_dataset_rele(ds, FTAG);
582265744Sdelphij		return (SET_ERROR(ENOTSUP));
583265744Sdelphij	}
584265744Sdelphij
585265744Sdelphij	dd = ds->ds_dir;
586265744Sdelphij	if (spa_feature_is_active(dp->dp_spa, SPA_FEATURE_FS_SS_LIMIT) &&
587265744Sdelphij	    dsl_dir_is_zapified(dd) &&
588265744Sdelphij	    zap_contains(dp->dp_meta_objset, dd->dd_object,
589265744Sdelphij	    DD_FIELD_FILESYSTEM_COUNT) == 0) {
590265744Sdelphij		dsl_dataset_rele(ds, FTAG);
591265744Sdelphij		return (SET_ERROR(EALREADY));
592265744Sdelphij	}
593265744Sdelphij
594265744Sdelphij	dsl_dataset_rele(ds, FTAG);
595265744Sdelphij	return (0);
596265744Sdelphij}
597265744Sdelphij
598265744Sdelphijstatic void
599265744Sdelphijdsl_dir_actv_fs_ss_limit_sync(void *arg, dmu_tx_t *tx)
600265744Sdelphij{
601265744Sdelphij	char *ddname = (char *)arg;
602265744Sdelphij	dsl_pool_t *dp = dmu_tx_pool(tx);
603265744Sdelphij	dsl_dataset_t *ds;
604265744Sdelphij	spa_t *spa;
605265744Sdelphij
606265744Sdelphij	VERIFY0(dsl_dataset_hold(dp, ddname, FTAG, &ds));
607265744Sdelphij
608265744Sdelphij	spa = dsl_dataset_get_spa(ds);
609265744Sdelphij
610265744Sdelphij	if (!spa_feature_is_active(spa, SPA_FEATURE_FS_SS_LIMIT)) {
611265744Sdelphij		/*
612265744Sdelphij		 * Since the feature was not active and we're now setting a
613265744Sdelphij		 * limit, increment the feature-active counter so that the
614265744Sdelphij		 * feature becomes active for the first time.
615265744Sdelphij		 *
616265744Sdelphij		 * We are already in a sync task so we can update the MOS.
617265744Sdelphij		 */
618265744Sdelphij		spa_feature_incr(spa, SPA_FEATURE_FS_SS_LIMIT, tx);
619265744Sdelphij	}
620265744Sdelphij
621265744Sdelphij	/*
622265744Sdelphij	 * Since we are now setting a non-UINT64_MAX limit on the filesystem,
623265744Sdelphij	 * we need to ensure the counts are correct. Descend down the tree from
624265744Sdelphij	 * this point and update all of the counts to be accurate.
625265744Sdelphij	 */
626265744Sdelphij	dsl_dir_init_fs_ss_count(ds->ds_dir, tx);
627265744Sdelphij
628265744Sdelphij	dsl_dataset_rele(ds, FTAG);
629265744Sdelphij}
630265744Sdelphij
631265744Sdelphij/*
632265744Sdelphij * Make sure the feature is enabled and activate it if necessary.
633265744Sdelphij * Since we're setting a limit, ensure the on-disk counts are valid.
634265744Sdelphij * This is only called by the ioctl path when setting a limit value.
635265744Sdelphij *
636265744Sdelphij * We do not need to validate the new limit, since users who can change the
637265744Sdelphij * limit are also allowed to exceed the limit.
638265744Sdelphij */
639265744Sdelphijint
640265744Sdelphijdsl_dir_activate_fs_ss_limit(const char *ddname)
641265744Sdelphij{
642265744Sdelphij	int error;
643265744Sdelphij
644265744Sdelphij	error = dsl_sync_task(ddname, dsl_dir_actv_fs_ss_limit_check,
645269006Sdelphij	    dsl_dir_actv_fs_ss_limit_sync, (void *)ddname, 0,
646269006Sdelphij	    ZFS_SPACE_CHECK_RESERVED);
647265744Sdelphij
648265744Sdelphij	if (error == EALREADY)
649265744Sdelphij		error = 0;
650265744Sdelphij
651265744Sdelphij	return (error);
652265744Sdelphij}
653265744Sdelphij
654265744Sdelphij/*
655265744Sdelphij * Used to determine if the filesystem_limit or snapshot_limit should be
656265744Sdelphij * enforced. We allow the limit to be exceeded if the user has permission to
657265744Sdelphij * write the property value. We pass in the creds that we got in the open
658265744Sdelphij * context since we will always be the GZ root in syncing context. We also have
659265744Sdelphij * to handle the case where we are allowed to change the limit on the current
660265744Sdelphij * dataset, but there may be another limit in the tree above.
661265744Sdelphij *
662265744Sdelphij * We can never modify these two properties within a non-global zone. In
663265744Sdelphij * addition, the other checks are modeled on zfs_secpolicy_write_perms. We
664265744Sdelphij * can't use that function since we are already holding the dp_config_rwlock.
665265744Sdelphij * In addition, we already have the dd and dealing with snapshots is simplified
666265744Sdelphij * in this code.
667265744Sdelphij */
668265744Sdelphij
669265744Sdelphijtypedef enum {
670265744Sdelphij	ENFORCE_ALWAYS,
671265744Sdelphij	ENFORCE_NEVER,
672265744Sdelphij	ENFORCE_ABOVE
673265744Sdelphij} enforce_res_t;
674265744Sdelphij
675265744Sdelphijstatic enforce_res_t
676265744Sdelphijdsl_enforce_ds_ss_limits(dsl_dir_t *dd, zfs_prop_t prop, cred_t *cr)
677265744Sdelphij{
678265744Sdelphij	enforce_res_t enforce = ENFORCE_ALWAYS;
679265744Sdelphij	uint64_t obj;
680265744Sdelphij	dsl_dataset_t *ds;
681265744Sdelphij	uint64_t zoned;
682265744Sdelphij
683265744Sdelphij	ASSERT(prop == ZFS_PROP_FILESYSTEM_LIMIT ||
684265744Sdelphij	    prop == ZFS_PROP_SNAPSHOT_LIMIT);
685265744Sdelphij
686265744Sdelphij#ifdef _KERNEL
687265744Sdelphij#ifdef __FreeBSD__
688265744Sdelphij	if (jailed(cr))
689265744Sdelphij#else
690265744Sdelphij	if (crgetzoneid(cr) != GLOBAL_ZONEID)
691265744Sdelphij#endif
692265744Sdelphij		return (ENFORCE_ALWAYS);
693265744Sdelphij
694265744Sdelphij	if (secpolicy_zfs(cr) == 0)
695265744Sdelphij		return (ENFORCE_NEVER);
696265744Sdelphij#endif
697265744Sdelphij
698265744Sdelphij	if ((obj = dd->dd_phys->dd_head_dataset_obj) == 0)
699265744Sdelphij		return (ENFORCE_ALWAYS);
700265744Sdelphij
701265744Sdelphij	ASSERT(dsl_pool_config_held(dd->dd_pool));
702265744Sdelphij
703265744Sdelphij	if (dsl_dataset_hold_obj(dd->dd_pool, obj, FTAG, &ds) != 0)
704265744Sdelphij		return (ENFORCE_ALWAYS);
705265744Sdelphij
706265744Sdelphij	if (dsl_prop_get_ds(ds, "zoned", 8, 1, &zoned, NULL) || zoned) {
707265744Sdelphij		/* Only root can access zoned fs's from the GZ */
708265744Sdelphij		enforce = ENFORCE_ALWAYS;
709265744Sdelphij	} else {
710265744Sdelphij		if (dsl_deleg_access_impl(ds, zfs_prop_to_name(prop), cr) == 0)
711265744Sdelphij			enforce = ENFORCE_ABOVE;
712265744Sdelphij	}
713265744Sdelphij
714265744Sdelphij	dsl_dataset_rele(ds, FTAG);
715265744Sdelphij	return (enforce);
716265744Sdelphij}
717265744Sdelphij
718265744Sdelphij/*
719265744Sdelphij * Check if adding additional child filesystem(s) would exceed any filesystem
720265744Sdelphij * limits or adding additional snapshot(s) would exceed any snapshot limits.
721265744Sdelphij * The prop argument indicates which limit to check.
722265744Sdelphij *
723265744Sdelphij * Note that all filesystem limits up to the root (or the highest
724265744Sdelphij * initialized) filesystem or the given ancestor must be satisfied.
725265744Sdelphij */
726265744Sdelphijint
727265744Sdelphijdsl_fs_ss_limit_check(dsl_dir_t *dd, uint64_t delta, zfs_prop_t prop,
728265744Sdelphij    dsl_dir_t *ancestor, cred_t *cr)
729265744Sdelphij{
730265744Sdelphij	objset_t *os = dd->dd_pool->dp_meta_objset;
731265744Sdelphij	uint64_t limit, count;
732265744Sdelphij	char *count_prop;
733265744Sdelphij	enforce_res_t enforce;
734265744Sdelphij	int err = 0;
735265744Sdelphij
736265744Sdelphij	ASSERT(dsl_pool_config_held(dd->dd_pool));
737265744Sdelphij	ASSERT(prop == ZFS_PROP_FILESYSTEM_LIMIT ||
738265744Sdelphij	    prop == ZFS_PROP_SNAPSHOT_LIMIT);
739265744Sdelphij
740265744Sdelphij	/*
741265744Sdelphij	 * If we're allowed to change the limit, don't enforce the limit
742265744Sdelphij	 * e.g. this can happen if a snapshot is taken by an administrative
743265744Sdelphij	 * user in the global zone (i.e. a recursive snapshot by root).
744265744Sdelphij	 * However, we must handle the case of delegated permissions where we
745265744Sdelphij	 * are allowed to change the limit on the current dataset, but there
746265744Sdelphij	 * is another limit in the tree above.
747265744Sdelphij	 */
748265744Sdelphij	enforce = dsl_enforce_ds_ss_limits(dd, prop, cr);
749265744Sdelphij	if (enforce == ENFORCE_NEVER)
750265744Sdelphij		return (0);
751265744Sdelphij
752265744Sdelphij	/*
753265744Sdelphij	 * e.g. if renaming a dataset with no snapshots, count adjustment
754265744Sdelphij	 * is 0.
755265744Sdelphij	 */
756265744Sdelphij	if (delta == 0)
757265744Sdelphij		return (0);
758265744Sdelphij
759265744Sdelphij	if (prop == ZFS_PROP_SNAPSHOT_LIMIT) {
760265744Sdelphij		/*
761265744Sdelphij		 * We don't enforce the limit for temporary snapshots. This is
762265744Sdelphij		 * indicated by a NULL cred_t argument.
763265744Sdelphij		 */
764265744Sdelphij		if (cr == NULL)
765265744Sdelphij			return (0);
766265744Sdelphij
767265744Sdelphij		count_prop = DD_FIELD_SNAPSHOT_COUNT;
768265744Sdelphij	} else {
769265744Sdelphij		count_prop = DD_FIELD_FILESYSTEM_COUNT;
770265744Sdelphij	}
771265744Sdelphij
772265744Sdelphij	/*
773265744Sdelphij	 * If an ancestor has been provided, stop checking the limit once we
774265744Sdelphij	 * hit that dir. We need this during rename so that we don't overcount
775265744Sdelphij	 * the check once we recurse up to the common ancestor.
776265744Sdelphij	 */
777265744Sdelphij	if (ancestor == dd)
778265744Sdelphij		return (0);
779265744Sdelphij
780265744Sdelphij	/*
781265744Sdelphij	 * If we hit an uninitialized node while recursing up the tree, we can
782265744Sdelphij	 * stop since we know there is no limit here (or above). The counts are
783265744Sdelphij	 * not valid on this node and we know we won't touch this node's counts.
784265744Sdelphij	 */
785265744Sdelphij	if (!dsl_dir_is_zapified(dd) || zap_lookup(os, dd->dd_object,
786265744Sdelphij	    count_prop, sizeof (count), 1, &count) == ENOENT)
787265744Sdelphij		return (0);
788265744Sdelphij
789265744Sdelphij	err = dsl_prop_get_dd(dd, zfs_prop_to_name(prop), 8, 1, &limit, NULL,
790265744Sdelphij	    B_FALSE);
791265744Sdelphij	if (err != 0)
792265744Sdelphij		return (err);
793265744Sdelphij
794265744Sdelphij	/* Is there a limit which we've hit? */
795265744Sdelphij	if (enforce == ENFORCE_ALWAYS && (count + delta) > limit)
796265744Sdelphij		return (SET_ERROR(EDQUOT));
797265744Sdelphij
798265744Sdelphij	if (dd->dd_parent != NULL)
799265744Sdelphij		err = dsl_fs_ss_limit_check(dd->dd_parent, delta, prop,
800265744Sdelphij		    ancestor, cr);
801265744Sdelphij
802265744Sdelphij	return (err);
803265744Sdelphij}
804265744Sdelphij
805265744Sdelphij/*
806265744Sdelphij * Adjust the filesystem or snapshot count for the specified dsl_dir_t and all
807265744Sdelphij * parents. When a new filesystem/snapshot is created, increment the count on
808265744Sdelphij * all parents, and when a filesystem/snapshot is destroyed, decrement the
809265744Sdelphij * count.
810265744Sdelphij */
811265744Sdelphijvoid
812265744Sdelphijdsl_fs_ss_count_adjust(dsl_dir_t *dd, int64_t delta, const char *prop,
813265744Sdelphij    dmu_tx_t *tx)
814265744Sdelphij{
815265744Sdelphij	int err;
816265744Sdelphij	objset_t *os = dd->dd_pool->dp_meta_objset;
817265744Sdelphij	uint64_t count;
818265744Sdelphij
819265744Sdelphij	ASSERT(dsl_pool_config_held(dd->dd_pool));
820265744Sdelphij	ASSERT(dmu_tx_is_syncing(tx));
821265744Sdelphij	ASSERT(strcmp(prop, DD_FIELD_FILESYSTEM_COUNT) == 0 ||
822265744Sdelphij	    strcmp(prop, DD_FIELD_SNAPSHOT_COUNT) == 0);
823265744Sdelphij
824265744Sdelphij	/*
825265744Sdelphij	 * When we receive an incremental stream into a filesystem that already
826265744Sdelphij	 * exists, a temporary clone is created.  We don't count this temporary
827265744Sdelphij	 * clone, whose name begins with a '%'. We also ignore hidden ($FREE,
828265744Sdelphij	 * $MOS & $ORIGIN) objsets.
829265744Sdelphij	 */
830265744Sdelphij	if ((dd->dd_myname[0] == '%' || dd->dd_myname[0] == '$') &&
831265744Sdelphij	    strcmp(prop, DD_FIELD_FILESYSTEM_COUNT) == 0)
832265744Sdelphij		return;
833265744Sdelphij
834265744Sdelphij	/*
835265744Sdelphij	 * e.g. if renaming a dataset with no snapshots, count adjustment is 0
836265744Sdelphij	 */
837265744Sdelphij	if (delta == 0)
838265744Sdelphij		return;
839265744Sdelphij
840265744Sdelphij	/*
841265744Sdelphij	 * If we hit an uninitialized node while recursing up the tree, we can
842265744Sdelphij	 * stop since we know the counts are not valid on this node and we
843265744Sdelphij	 * know we shouldn't touch this node's counts. An uninitialized count
844265744Sdelphij	 * on the node indicates that either the feature has not yet been
845265744Sdelphij	 * activated or there are no limits on this part of the tree.
846265744Sdelphij	 */
847265744Sdelphij	if (!dsl_dir_is_zapified(dd) || (err = zap_lookup(os, dd->dd_object,
848265744Sdelphij	    prop, sizeof (count), 1, &count)) == ENOENT)
849265744Sdelphij		return;
850265744Sdelphij	VERIFY0(err);
851265744Sdelphij
852265744Sdelphij	count += delta;
853265744Sdelphij	/* Use a signed verify to make sure we're not neg. */
854265744Sdelphij	VERIFY3S(count, >=, 0);
855265744Sdelphij
856265744Sdelphij	VERIFY0(zap_update(os, dd->dd_object, prop, sizeof (count), 1, &count,
857265744Sdelphij	    tx));
858265744Sdelphij
859265744Sdelphij	/* Roll up this additional count into our ancestors */
860265744Sdelphij	if (dd->dd_parent != NULL)
861265744Sdelphij		dsl_fs_ss_count_adjust(dd->dd_parent, delta, prop, tx);
862265744Sdelphij}
863265744Sdelphij
864168404Spjduint64_t
865185029Spjddsl_dir_create_sync(dsl_pool_t *dp, dsl_dir_t *pds, const char *name,
866185029Spjd    dmu_tx_t *tx)
867168404Spjd{
868185029Spjd	objset_t *mos = dp->dp_meta_objset;
869168404Spjd	uint64_t ddobj;
870219089Spjd	dsl_dir_phys_t *ddphys;
871168404Spjd	dmu_buf_t *dbuf;
872168404Spjd
873168404Spjd	ddobj = dmu_object_alloc(mos, DMU_OT_DSL_DIR, 0,
874168404Spjd	    DMU_OT_DSL_DIR, sizeof (dsl_dir_phys_t), tx);
875185029Spjd	if (pds) {
876185029Spjd		VERIFY(0 == zap_add(mos, pds->dd_phys->dd_child_dir_zapobj,
877185029Spjd		    name, sizeof (uint64_t), 1, &ddobj, tx));
878185029Spjd	} else {
879185029Spjd		/* it's the root dir */
880185029Spjd		VERIFY(0 == zap_add(mos, DMU_POOL_DIRECTORY_OBJECT,
881185029Spjd		    DMU_POOL_ROOT_DATASET, sizeof (uint64_t), 1, &ddobj, tx));
882185029Spjd	}
883168404Spjd	VERIFY(0 == dmu_bonus_hold(mos, ddobj, FTAG, &dbuf));
884168404Spjd	dmu_buf_will_dirty(dbuf, tx);
885219089Spjd	ddphys = dbuf->db_data;
886168404Spjd
887219089Spjd	ddphys->dd_creation_time = gethrestime_sec();
888265744Sdelphij	if (pds) {
889219089Spjd		ddphys->dd_parent_obj = pds->dd_object;
890265744Sdelphij
891265744Sdelphij		/* update the filesystem counts */
892265744Sdelphij		dsl_fs_ss_count_adjust(pds, 1, DD_FIELD_FILESYSTEM_COUNT, tx);
893265744Sdelphij	}
894219089Spjd	ddphys->dd_props_zapobj = zap_create(mos,
895168404Spjd	    DMU_OT_DSL_PROPS, DMU_OT_NONE, 0, tx);
896219089Spjd	ddphys->dd_child_dir_zapobj = zap_create(mos,
897168404Spjd	    DMU_OT_DSL_DIR_CHILD_MAP, DMU_OT_NONE, 0, tx);
898185029Spjd	if (spa_version(dp->dp_spa) >= SPA_VERSION_USED_BREAKDOWN)
899219089Spjd		ddphys->dd_flags |= DD_FLAG_USED_BREAKDOWN;
900168404Spjd	dmu_buf_rele(dbuf, FTAG);
901168404Spjd
902168404Spjd	return (ddobj);
903168404Spjd}
904168404Spjd
905185029Spjdboolean_t
906185029Spjddsl_dir_is_clone(dsl_dir_t *dd)
907168404Spjd{
908185029Spjd	return (dd->dd_phys->dd_origin_obj &&
909185029Spjd	    (dd->dd_pool->dp_origin_snap == NULL ||
910185029Spjd	    dd->dd_phys->dd_origin_obj !=
911185029Spjd	    dd->dd_pool->dp_origin_snap->ds_object));
912168404Spjd}
913168404Spjd
914168404Spjdvoid
915168404Spjddsl_dir_stats(dsl_dir_t *dd, nvlist_t *nv)
916168404Spjd{
917168404Spjd	mutex_enter(&dd->dd_lock);
918185029Spjd	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USED,
919185029Spjd	    dd->dd_phys->dd_used_bytes);
920185029Spjd	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_QUOTA, dd->dd_phys->dd_quota);
921168404Spjd	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_RESERVATION,
922168404Spjd	    dd->dd_phys->dd_reserved);
923168404Spjd	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_COMPRESSRATIO,
924168404Spjd	    dd->dd_phys->dd_compressed_bytes == 0 ? 100 :
925168404Spjd	    (dd->dd_phys->dd_uncompressed_bytes * 100 /
926168404Spjd	    dd->dd_phys->dd_compressed_bytes));
927247585Smm	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_LOGICALUSED,
928247585Smm	    dd->dd_phys->dd_uncompressed_bytes);
929185029Spjd	if (dd->dd_phys->dd_flags & DD_FLAG_USED_BREAKDOWN) {
930185029Spjd		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDSNAP,
931185029Spjd		    dd->dd_phys->dd_used_breakdown[DD_USED_SNAP]);
932185029Spjd		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDDS,
933185029Spjd		    dd->dd_phys->dd_used_breakdown[DD_USED_HEAD]);
934185029Spjd		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDREFRESERV,
935185029Spjd		    dd->dd_phys->dd_used_breakdown[DD_USED_REFRSRV]);
936185029Spjd		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USEDCHILD,
937185029Spjd		    dd->dd_phys->dd_used_breakdown[DD_USED_CHILD] +
938185029Spjd		    dd->dd_phys->dd_used_breakdown[DD_USED_CHILD_RSRV]);
939185029Spjd	}
940168404Spjd	mutex_exit(&dd->dd_lock);
941168404Spjd
942265744Sdelphij	if (dsl_dir_is_zapified(dd)) {
943265744Sdelphij		uint64_t count;
944265744Sdelphij		objset_t *os = dd->dd_pool->dp_meta_objset;
945265744Sdelphij
946265744Sdelphij		if (zap_lookup(os, dd->dd_object, DD_FIELD_FILESYSTEM_COUNT,
947265744Sdelphij		    sizeof (count), 1, &count) == 0) {
948265744Sdelphij			dsl_prop_nvlist_add_uint64(nv,
949265744Sdelphij			    ZFS_PROP_FILESYSTEM_COUNT, count);
950265744Sdelphij		}
951265744Sdelphij		if (zap_lookup(os, dd->dd_object, DD_FIELD_SNAPSHOT_COUNT,
952265744Sdelphij		    sizeof (count), 1, &count) == 0) {
953265744Sdelphij			dsl_prop_nvlist_add_uint64(nv,
954265744Sdelphij			    ZFS_PROP_SNAPSHOT_COUNT, count);
955265744Sdelphij		}
956265744Sdelphij	}
957265744Sdelphij
958185029Spjd	if (dsl_dir_is_clone(dd)) {
959168404Spjd		dsl_dataset_t *ds;
960168404Spjd		char buf[MAXNAMELEN];
961168404Spjd
962248571Smm		VERIFY0(dsl_dataset_hold_obj(dd->dd_pool,
963185029Spjd		    dd->dd_phys->dd_origin_obj, FTAG, &ds));
964168404Spjd		dsl_dataset_name(ds, buf);
965185029Spjd		dsl_dataset_rele(ds, FTAG);
966168404Spjd		dsl_prop_nvlist_add_string(nv, ZFS_PROP_ORIGIN, buf);
967168404Spjd	}
968168404Spjd}
969168404Spjd
970168404Spjdvoid
971168404Spjddsl_dir_dirty(dsl_dir_t *dd, dmu_tx_t *tx)
972168404Spjd{
973168404Spjd	dsl_pool_t *dp = dd->dd_pool;
974168404Spjd
975168404Spjd	ASSERT(dd->dd_phys);
976168404Spjd
977248571Smm	if (txg_list_add(&dp->dp_dirty_dirs, dd, tx->tx_txg)) {
978168404Spjd		/* up the hold count until we can be written out */
979168404Spjd		dmu_buf_add_ref(dd->dd_dbuf, dd);
980168404Spjd	}
981168404Spjd}
982168404Spjd
983168404Spjdstatic int64_t
984168404Spjdparent_delta(dsl_dir_t *dd, uint64_t used, int64_t delta)
985168404Spjd{
986168404Spjd	uint64_t old_accounted = MAX(used, dd->dd_phys->dd_reserved);
987168404Spjd	uint64_t new_accounted = MAX(used + delta, dd->dd_phys->dd_reserved);
988168404Spjd	return (new_accounted - old_accounted);
989168404Spjd}
990168404Spjd
991168404Spjdvoid
992168404Spjddsl_dir_sync(dsl_dir_t *dd, dmu_tx_t *tx)
993168404Spjd{
994168404Spjd	ASSERT(dmu_tx_is_syncing(tx));
995168404Spjd
996168404Spjd	mutex_enter(&dd->dd_lock);
997240415Smm	ASSERT0(dd->dd_tempreserved[tx->tx_txg&TXG_MASK]);
998168404Spjd	dprintf_dd(dd, "txg=%llu towrite=%lluK\n", tx->tx_txg,
999168404Spjd	    dd->dd_space_towrite[tx->tx_txg&TXG_MASK] / 1024);
1000168404Spjd	dd->dd_space_towrite[tx->tx_txg&TXG_MASK] = 0;
1001168404Spjd	mutex_exit(&dd->dd_lock);
1002168404Spjd
1003168404Spjd	/* release the hold from dsl_dir_dirty */
1004168404Spjd	dmu_buf_rele(dd->dd_dbuf, dd);
1005168404Spjd}
1006168404Spjd
1007168404Spjdstatic uint64_t
1008185029Spjddsl_dir_space_towrite(dsl_dir_t *dd)
1009168404Spjd{
1010185029Spjd	uint64_t space = 0;
1011168404Spjd	int i;
1012168404Spjd
1013168404Spjd	ASSERT(MUTEX_HELD(&dd->dd_lock));
1014168404Spjd
1015168404Spjd	for (i = 0; i < TXG_SIZE; i++) {
1016168404Spjd		space += dd->dd_space_towrite[i&TXG_MASK];
1017168404Spjd		ASSERT3U(dd->dd_space_towrite[i&TXG_MASK], >=, 0);
1018168404Spjd	}
1019168404Spjd	return (space);
1020168404Spjd}
1021168404Spjd
1022168404Spjd/*
1023168404Spjd * How much space would dd have available if ancestor had delta applied
1024168404Spjd * to it?  If ondiskonly is set, we're only interested in what's
1025168404Spjd * on-disk, not estimated pending changes.
1026168404Spjd */
1027168404Spjduint64_t
1028168404Spjddsl_dir_space_available(dsl_dir_t *dd,
1029168404Spjd    dsl_dir_t *ancestor, int64_t delta, int ondiskonly)
1030168404Spjd{
1031168404Spjd	uint64_t parentspace, myspace, quota, used;
1032168404Spjd
1033168404Spjd	/*
1034168404Spjd	 * If there are no restrictions otherwise, assume we have
1035168404Spjd	 * unlimited space available.
1036168404Spjd	 */
1037168404Spjd	quota = UINT64_MAX;
1038168404Spjd	parentspace = UINT64_MAX;
1039168404Spjd
1040168404Spjd	if (dd->dd_parent != NULL) {
1041168404Spjd		parentspace = dsl_dir_space_available(dd->dd_parent,
1042168404Spjd		    ancestor, delta, ondiskonly);
1043168404Spjd	}
1044168404Spjd
1045168404Spjd	mutex_enter(&dd->dd_lock);
1046168404Spjd	if (dd->dd_phys->dd_quota != 0)
1047168404Spjd		quota = dd->dd_phys->dd_quota;
1048185029Spjd	used = dd->dd_phys->dd_used_bytes;
1049185029Spjd	if (!ondiskonly)
1050185029Spjd		used += dsl_dir_space_towrite(dd);
1051168404Spjd
1052168404Spjd	if (dd->dd_parent == NULL) {
1053168404Spjd		uint64_t poolsize = dsl_pool_adjustedsize(dd->dd_pool, FALSE);
1054168404Spjd		quota = MIN(quota, poolsize);
1055168404Spjd	}
1056168404Spjd
1057168404Spjd	if (dd->dd_phys->dd_reserved > used && parentspace != UINT64_MAX) {
1058168404Spjd		/*
1059168404Spjd		 * We have some space reserved, in addition to what our
1060168404Spjd		 * parent gave us.
1061168404Spjd		 */
1062168404Spjd		parentspace += dd->dd_phys->dd_reserved - used;
1063168404Spjd	}
1064168404Spjd
1065185029Spjd	if (dd == ancestor) {
1066185029Spjd		ASSERT(delta <= 0);
1067185029Spjd		ASSERT(used >= -delta);
1068185029Spjd		used += delta;
1069185029Spjd		if (parentspace != UINT64_MAX)
1070185029Spjd			parentspace -= delta;
1071185029Spjd	}
1072185029Spjd
1073168404Spjd	if (used > quota) {
1074168404Spjd		/* over quota */
1075168404Spjd		myspace = 0;
1076168404Spjd	} else {
1077168404Spjd		/*
1078168404Spjd		 * the lesser of the space provided by our parent and
1079168404Spjd		 * the space left in our quota
1080168404Spjd		 */
1081168404Spjd		myspace = MIN(parentspace, quota - used);
1082168404Spjd	}
1083168404Spjd
1084168404Spjd	mutex_exit(&dd->dd_lock);
1085168404Spjd
1086168404Spjd	return (myspace);
1087168404Spjd}
1088168404Spjd
1089168404Spjdstruct tempreserve {
1090168404Spjd	list_node_t tr_node;
1091168404Spjd	dsl_dir_t *tr_ds;
1092168404Spjd	uint64_t tr_size;
1093168404Spjd};
1094168404Spjd
1095168404Spjdstatic int
1096185029Spjddsl_dir_tempreserve_impl(dsl_dir_t *dd, uint64_t asize, boolean_t netfree,
1097185029Spjd    boolean_t ignorequota, boolean_t checkrefquota, list_t *tr_list,
1098185029Spjd    dmu_tx_t *tx, boolean_t first)
1099168404Spjd{
1100168404Spjd	uint64_t txg = tx->tx_txg;
1101185029Spjd	uint64_t est_inflight, used_on_disk, quota, parent_rsrv;
1102219089Spjd	uint64_t deferred = 0;
1103185029Spjd	struct tempreserve *tr;
1104219089Spjd	int retval = EDQUOT;
1105168404Spjd	int txgidx = txg & TXG_MASK;
1106168404Spjd	int i;
1107185029Spjd	uint64_t ref_rsrv = 0;
1108168404Spjd
1109168404Spjd	ASSERT3U(txg, !=, 0);
1110185029Spjd	ASSERT3S(asize, >, 0);
1111168404Spjd
1112168404Spjd	mutex_enter(&dd->dd_lock);
1113185029Spjd
1114168404Spjd	/*
1115168404Spjd	 * Check against the dsl_dir's quota.  We don't add in the delta
1116168404Spjd	 * when checking for over-quota because they get one free hit.
1117168404Spjd	 */
1118185029Spjd	est_inflight = dsl_dir_space_towrite(dd);
1119168404Spjd	for (i = 0; i < TXG_SIZE; i++)
1120185029Spjd		est_inflight += dd->dd_tempreserved[i];
1121185029Spjd	used_on_disk = dd->dd_phys->dd_used_bytes;
1122168404Spjd
1123185029Spjd	/*
1124185029Spjd	 * On the first iteration, fetch the dataset's used-on-disk and
1125185029Spjd	 * refreservation values. Also, if checkrefquota is set, test if
1126185029Spjd	 * allocating this space would exceed the dataset's refquota.
1127185029Spjd	 */
1128185029Spjd	if (first && tx->tx_objset) {
1129185029Spjd		int error;
1130219089Spjd		dsl_dataset_t *ds = tx->tx_objset->os_dsl_dataset;
1131168404Spjd
1132185029Spjd		error = dsl_dataset_check_quota(ds, checkrefquota,
1133185029Spjd		    asize, est_inflight, &used_on_disk, &ref_rsrv);
1134185029Spjd		if (error) {
1135185029Spjd			mutex_exit(&dd->dd_lock);
1136185029Spjd			return (error);
1137185029Spjd		}
1138185029Spjd	}
1139185029Spjd
1140185029Spjd	/*
1141185029Spjd	 * If this transaction will result in a net free of space,
1142185029Spjd	 * we want to let it through.
1143185029Spjd	 */
1144185029Spjd	if (ignorequota || netfree || dd->dd_phys->dd_quota == 0)
1145185029Spjd		quota = UINT64_MAX;
1146185029Spjd	else
1147168404Spjd		quota = dd->dd_phys->dd_quota;
1148168404Spjd
1149168404Spjd	/*
1150219089Spjd	 * Adjust the quota against the actual pool size at the root
1151219089Spjd	 * minus any outstanding deferred frees.
1152185029Spjd	 * To ensure that it's possible to remove files from a full
1153185029Spjd	 * pool without inducing transient overcommits, we throttle
1154168404Spjd	 * netfree transactions against a quota that is slightly larger,
1155168404Spjd	 * but still within the pool's allocation slop.  In cases where
1156168404Spjd	 * we're very close to full, this will allow a steady trickle of
1157168404Spjd	 * removes to get through.
1158168404Spjd	 */
1159168404Spjd	if (dd->dd_parent == NULL) {
1160219089Spjd		spa_t *spa = dd->dd_pool->dp_spa;
1161168404Spjd		uint64_t poolsize = dsl_pool_adjustedsize(dd->dd_pool, netfree);
1162219089Spjd		deferred = metaslab_class_get_deferred(spa_normal_class(spa));
1163219089Spjd		if (poolsize - deferred < quota) {
1164219089Spjd			quota = poolsize - deferred;
1165219089Spjd			retval = ENOSPC;
1166168404Spjd		}
1167168404Spjd	}
1168168404Spjd
1169168404Spjd	/*
1170168404Spjd	 * If they are requesting more space, and our current estimate
1171185029Spjd	 * is over quota, they get to try again unless the actual
1172168404Spjd	 * on-disk is over quota and there are no pending changes (which
1173168404Spjd	 * may free up space for us).
1174168404Spjd	 */
1175219089Spjd	if (used_on_disk + est_inflight >= quota) {
1176219089Spjd		if (est_inflight > 0 || used_on_disk < quota ||
1177219089Spjd		    (retval == ENOSPC && used_on_disk < quota + deferred))
1178219089Spjd			retval = ERESTART;
1179185029Spjd		dprintf_dd(dd, "failing: used=%lluK inflight = %lluK "
1180168404Spjd		    "quota=%lluK tr=%lluK err=%d\n",
1181185029Spjd		    used_on_disk>>10, est_inflight>>10,
1182219089Spjd		    quota>>10, asize>>10, retval);
1183168404Spjd		mutex_exit(&dd->dd_lock);
1184249195Smm		return (SET_ERROR(retval));
1185168404Spjd	}
1186168404Spjd
1187168404Spjd	/* We need to up our estimated delta before dropping dd_lock */
1188168404Spjd	dd->dd_tempreserved[txgidx] += asize;
1189168404Spjd
1190185029Spjd	parent_rsrv = parent_delta(dd, used_on_disk + est_inflight,
1191185029Spjd	    asize - ref_rsrv);
1192168404Spjd	mutex_exit(&dd->dd_lock);
1193168404Spjd
1194185029Spjd	tr = kmem_zalloc(sizeof (struct tempreserve), KM_SLEEP);
1195168404Spjd	tr->tr_ds = dd;
1196168404Spjd	tr->tr_size = asize;
1197168404Spjd	list_insert_tail(tr_list, tr);
1198168404Spjd
1199168404Spjd	/* see if it's OK with our parent */
1200168404Spjd	if (dd->dd_parent && parent_rsrv) {
1201185029Spjd		boolean_t ismos = (dd->dd_phys->dd_head_dataset_obj == 0);
1202185029Spjd
1203168404Spjd		return (dsl_dir_tempreserve_impl(dd->dd_parent,
1204185029Spjd		    parent_rsrv, netfree, ismos, TRUE, tr_list, tx, FALSE));
1205168404Spjd	} else {
1206168404Spjd		return (0);
1207168404Spjd	}
1208168404Spjd}
1209168404Spjd
1210168404Spjd/*
1211168404Spjd * Reserve space in this dsl_dir, to be used in this tx's txg.
1212185029Spjd * After the space has been dirtied (and dsl_dir_willuse_space()
1213185029Spjd * has been called), the reservation should be canceled, using
1214185029Spjd * dsl_dir_tempreserve_clear().
1215168404Spjd */
1216168404Spjdint
1217185029Spjddsl_dir_tempreserve_space(dsl_dir_t *dd, uint64_t lsize, uint64_t asize,
1218185029Spjd    uint64_t fsize, uint64_t usize, void **tr_cookiep, dmu_tx_t *tx)
1219168404Spjd{
1220185029Spjd	int err;
1221168404Spjd	list_t *tr_list;
1222168404Spjd
1223185029Spjd	if (asize == 0) {
1224185029Spjd		*tr_cookiep = NULL;
1225185029Spjd		return (0);
1226185029Spjd	}
1227185029Spjd
1228168404Spjd	tr_list = kmem_alloc(sizeof (list_t), KM_SLEEP);
1229168404Spjd	list_create(tr_list, sizeof (struct tempreserve),
1230168404Spjd	    offsetof(struct tempreserve, tr_node));
1231185029Spjd	ASSERT3S(asize, >, 0);
1232168404Spjd	ASSERT3S(fsize, >=, 0);
1233168404Spjd
1234185029Spjd	err = arc_tempreserve_space(lsize, tx->tx_txg);
1235168404Spjd	if (err == 0) {
1236168404Spjd		struct tempreserve *tr;
1237168404Spjd
1238185029Spjd		tr = kmem_zalloc(sizeof (struct tempreserve), KM_SLEEP);
1239185029Spjd		tr->tr_size = lsize;
1240185029Spjd		list_insert_tail(tr_list, tr);
1241185029Spjd	} else {
1242185029Spjd		if (err == EAGAIN) {
1243260763Savg			/*
1244260763Savg			 * If arc_memory_throttle() detected that pageout
1245260763Savg			 * is running and we are low on memory, we delay new
1246260763Savg			 * non-pageout transactions to give pageout an
1247260763Savg			 * advantage.
1248260763Savg			 *
1249260763Savg			 * It is unfortunate to be delaying while the caller's
1250260763Savg			 * locks are held.
1251260763Savg			 */
1252255437Sdelphij			txg_delay(dd->dd_pool, tx->tx_txg,
1253255437Sdelphij			    MSEC2NSEC(10), MSEC2NSEC(10));
1254249195Smm			err = SET_ERROR(ERESTART);
1255168404Spjd		}
1256168404Spjd	}
1257168404Spjd
1258185029Spjd	if (err == 0) {
1259185029Spjd		err = dsl_dir_tempreserve_impl(dd, asize, fsize >= asize,
1260185029Spjd		    FALSE, asize > usize, tr_list, tx, TRUE);
1261185029Spjd	}
1262185029Spjd
1263248571Smm	if (err != 0)
1264168404Spjd		dsl_dir_tempreserve_clear(tr_list, tx);
1265168404Spjd	else
1266168404Spjd		*tr_cookiep = tr_list;
1267185029Spjd
1268168404Spjd	return (err);
1269168404Spjd}
1270168404Spjd
1271168404Spjd/*
1272168404Spjd * Clear a temporary reservation that we previously made with
1273168404Spjd * dsl_dir_tempreserve_space().
1274168404Spjd */
1275168404Spjdvoid
1276168404Spjddsl_dir_tempreserve_clear(void *tr_cookie, dmu_tx_t *tx)
1277168404Spjd{
1278168404Spjd	int txgidx = tx->tx_txg & TXG_MASK;
1279168404Spjd	list_t *tr_list = tr_cookie;
1280168404Spjd	struct tempreserve *tr;
1281168404Spjd
1282168404Spjd	ASSERT3U(tx->tx_txg, !=, 0);
1283168404Spjd
1284185029Spjd	if (tr_cookie == NULL)
1285185029Spjd		return;
1286185029Spjd
1287260763Savg	while ((tr = list_head(tr_list)) != NULL) {
1288260763Savg		if (tr->tr_ds) {
1289168404Spjd			mutex_enter(&tr->tr_ds->dd_lock);
1290168404Spjd			ASSERT3U(tr->tr_ds->dd_tempreserved[txgidx], >=,
1291168404Spjd			    tr->tr_size);
1292168404Spjd			tr->tr_ds->dd_tempreserved[txgidx] -= tr->tr_size;
1293168404Spjd			mutex_exit(&tr->tr_ds->dd_lock);
1294185029Spjd		} else {
1295185029Spjd			arc_tempreserve_clear(tr->tr_size);
1296168404Spjd		}
1297168404Spjd		list_remove(tr_list, tr);
1298168404Spjd		kmem_free(tr, sizeof (struct tempreserve));
1299168404Spjd	}
1300168404Spjd
1301168404Spjd	kmem_free(tr_list, sizeof (list_t));
1302168404Spjd}
1303168404Spjd
1304260763Savg/*
1305260763Savg * This should be called from open context when we think we're going to write
1306260763Savg * or free space, for example when dirtying data. Be conservative; it's okay
1307260763Savg * to write less space or free more, but we don't want to write more or free
1308260763Savg * less than the amount specified.
1309260763Savg */
1310260763Savgvoid
1311260763Savgdsl_dir_willuse_space(dsl_dir_t *dd, int64_t space, dmu_tx_t *tx)
1312168404Spjd{
1313168404Spjd	int64_t parent_space;
1314168404Spjd	uint64_t est_used;
1315168404Spjd
1316168404Spjd	mutex_enter(&dd->dd_lock);
1317168404Spjd	if (space > 0)
1318168404Spjd		dd->dd_space_towrite[tx->tx_txg & TXG_MASK] += space;
1319168404Spjd
1320185029Spjd	est_used = dsl_dir_space_towrite(dd) + dd->dd_phys->dd_used_bytes;
1321168404Spjd	parent_space = parent_delta(dd, est_used, space);
1322168404Spjd	mutex_exit(&dd->dd_lock);
1323168404Spjd
1324168404Spjd	/* Make sure that we clean up dd_space_to* */
1325168404Spjd	dsl_dir_dirty(dd, tx);
1326168404Spjd
1327168404Spjd	/* XXX this is potentially expensive and unnecessary... */
1328168404Spjd	if (parent_space && dd->dd_parent)
1329260763Savg		dsl_dir_willuse_space(dd->dd_parent, parent_space, tx);
1330168404Spjd}
1331168404Spjd
1332168404Spjd/* call from syncing context when we actually write/free space for this dd */
1333168404Spjdvoid
1334185029Spjddsl_dir_diduse_space(dsl_dir_t *dd, dd_used_t type,
1335168404Spjd    int64_t used, int64_t compressed, int64_t uncompressed, dmu_tx_t *tx)
1336168404Spjd{
1337168404Spjd	int64_t accounted_delta;
1338254757Sdelphij
1339254757Sdelphij	/*
1340254757Sdelphij	 * dsl_dataset_set_refreservation_sync_impl() calls this with
1341254757Sdelphij	 * dd_lock held, so that it can atomically update
1342254757Sdelphij	 * ds->ds_reserved and the dsl_dir accounting, so that
1343254757Sdelphij	 * dsl_dataset_check_quota() can see dataset and dir accounting
1344254757Sdelphij	 * consistently.
1345254757Sdelphij	 */
1346185029Spjd	boolean_t needlock = !MUTEX_HELD(&dd->dd_lock);
1347168404Spjd
1348168404Spjd	ASSERT(dmu_tx_is_syncing(tx));
1349185029Spjd	ASSERT(type < DD_USED_NUM);
1350168404Spjd
1351254757Sdelphij	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1352254757Sdelphij
1353185029Spjd	if (needlock)
1354185029Spjd		mutex_enter(&dd->dd_lock);
1355185029Spjd	accounted_delta = parent_delta(dd, dd->dd_phys->dd_used_bytes, used);
1356185029Spjd	ASSERT(used >= 0 || dd->dd_phys->dd_used_bytes >= -used);
1357168404Spjd	ASSERT(compressed >= 0 ||
1358168404Spjd	    dd->dd_phys->dd_compressed_bytes >= -compressed);
1359168404Spjd	ASSERT(uncompressed >= 0 ||
1360168404Spjd	    dd->dd_phys->dd_uncompressed_bytes >= -uncompressed);
1361185029Spjd	dd->dd_phys->dd_used_bytes += used;
1362168404Spjd	dd->dd_phys->dd_uncompressed_bytes += uncompressed;
1363168404Spjd	dd->dd_phys->dd_compressed_bytes += compressed;
1364168404Spjd
1365185029Spjd	if (dd->dd_phys->dd_flags & DD_FLAG_USED_BREAKDOWN) {
1366185029Spjd		ASSERT(used > 0 ||
1367185029Spjd		    dd->dd_phys->dd_used_breakdown[type] >= -used);
1368185029Spjd		dd->dd_phys->dd_used_breakdown[type] += used;
1369185029Spjd#ifdef DEBUG
1370185029Spjd		dd_used_t t;
1371185029Spjd		uint64_t u = 0;
1372185029Spjd		for (t = 0; t < DD_USED_NUM; t++)
1373185029Spjd			u += dd->dd_phys->dd_used_breakdown[t];
1374185029Spjd		ASSERT3U(u, ==, dd->dd_phys->dd_used_bytes);
1375185029Spjd#endif
1376185029Spjd	}
1377185029Spjd	if (needlock)
1378185029Spjd		mutex_exit(&dd->dd_lock);
1379185029Spjd
1380168404Spjd	if (dd->dd_parent != NULL) {
1381185029Spjd		dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD,
1382168404Spjd		    accounted_delta, compressed, uncompressed, tx);
1383185029Spjd		dsl_dir_transfer_space(dd->dd_parent,
1384185029Spjd		    used - accounted_delta,
1385185029Spjd		    DD_USED_CHILD_RSRV, DD_USED_CHILD, tx);
1386168404Spjd	}
1387168404Spjd}
1388168404Spjd
1389185029Spjdvoid
1390185029Spjddsl_dir_transfer_space(dsl_dir_t *dd, int64_t delta,
1391185029Spjd    dd_used_t oldtype, dd_used_t newtype, dmu_tx_t *tx)
1392185029Spjd{
1393185029Spjd	ASSERT(dmu_tx_is_syncing(tx));
1394185029Spjd	ASSERT(oldtype < DD_USED_NUM);
1395185029Spjd	ASSERT(newtype < DD_USED_NUM);
1396185029Spjd
1397185029Spjd	if (delta == 0 || !(dd->dd_phys->dd_flags & DD_FLAG_USED_BREAKDOWN))
1398185029Spjd		return;
1399185029Spjd
1400254757Sdelphij	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1401254757Sdelphij	mutex_enter(&dd->dd_lock);
1402185029Spjd	ASSERT(delta > 0 ?
1403185029Spjd	    dd->dd_phys->dd_used_breakdown[oldtype] >= delta :
1404185029Spjd	    dd->dd_phys->dd_used_breakdown[newtype] >= -delta);
1405185029Spjd	ASSERT(dd->dd_phys->dd_used_bytes >= ABS(delta));
1406185029Spjd	dd->dd_phys->dd_used_breakdown[oldtype] -= delta;
1407185029Spjd	dd->dd_phys->dd_used_breakdown[newtype] += delta;
1408254757Sdelphij	mutex_exit(&dd->dd_lock);
1409185029Spjd}
1410185029Spjd
1411248571Smmtypedef struct dsl_dir_set_qr_arg {
1412248571Smm	const char *ddsqra_name;
1413248571Smm	zprop_source_t ddsqra_source;
1414248571Smm	uint64_t ddsqra_value;
1415248571Smm} dsl_dir_set_qr_arg_t;
1416248571Smm
1417168404Spjdstatic int
1418248571Smmdsl_dir_set_quota_check(void *arg, dmu_tx_t *tx)
1419168404Spjd{
1420248571Smm	dsl_dir_set_qr_arg_t *ddsqra = arg;
1421248571Smm	dsl_pool_t *dp = dmu_tx_pool(tx);
1422248571Smm	dsl_dataset_t *ds;
1423248571Smm	int error;
1424248571Smm	uint64_t towrite, newval;
1425168404Spjd
1426248571Smm	error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
1427248571Smm	if (error != 0)
1428248571Smm		return (error);
1429219089Spjd
1430248571Smm	error = dsl_prop_predict(ds->ds_dir, "quota",
1431248571Smm	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
1432248571Smm	if (error != 0) {
1433248571Smm		dsl_dataset_rele(ds, FTAG);
1434248571Smm		return (error);
1435248571Smm	}
1436248571Smm
1437248571Smm	if (newval == 0) {
1438248571Smm		dsl_dataset_rele(ds, FTAG);
1439168404Spjd		return (0);
1440248571Smm	}
1441168404Spjd
1442248571Smm	mutex_enter(&ds->ds_dir->dd_lock);
1443168404Spjd	/*
1444168404Spjd	 * If we are doing the preliminary check in open context, and
1445168404Spjd	 * there are pending changes, then don't fail it, since the
1446185029Spjd	 * pending changes could under-estimate the amount of space to be
1447168404Spjd	 * freed up.
1448168404Spjd	 */
1449248571Smm	towrite = dsl_dir_space_towrite(ds->ds_dir);
1450168404Spjd	if ((dmu_tx_is_syncing(tx) || towrite == 0) &&
1451248571Smm	    (newval < ds->ds_dir->dd_phys->dd_reserved ||
1452248571Smm	    newval < ds->ds_dir->dd_phys->dd_used_bytes + towrite)) {
1453249195Smm		error = SET_ERROR(ENOSPC);
1454168404Spjd	}
1455248571Smm	mutex_exit(&ds->ds_dir->dd_lock);
1456248571Smm	dsl_dataset_rele(ds, FTAG);
1457248571Smm	return (error);
1458168404Spjd}
1459168404Spjd
1460168404Spjdstatic void
1461248571Smmdsl_dir_set_quota_sync(void *arg, dmu_tx_t *tx)
1462168404Spjd{
1463248571Smm	dsl_dir_set_qr_arg_t *ddsqra = arg;
1464248571Smm	dsl_pool_t *dp = dmu_tx_pool(tx);
1465248571Smm	dsl_dataset_t *ds;
1466248571Smm	uint64_t newval;
1467168404Spjd
1468248571Smm	VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
1469219089Spjd
1470249787Smm	if (spa_version(dp->dp_spa) >= SPA_VERSION_RECVD_PROPS) {
1471249787Smm		dsl_prop_set_sync_impl(ds, zfs_prop_to_name(ZFS_PROP_QUOTA),
1472249787Smm		    ddsqra->ddsqra_source, sizeof (ddsqra->ddsqra_value), 1,
1473249787Smm		    &ddsqra->ddsqra_value, tx);
1474168404Spjd
1475249787Smm		VERIFY0(dsl_prop_get_int_ds(ds,
1476249787Smm		    zfs_prop_to_name(ZFS_PROP_QUOTA), &newval));
1477249787Smm	} else {
1478249787Smm		newval = ddsqra->ddsqra_value;
1479249787Smm		spa_history_log_internal_ds(ds, "set", tx, "%s=%lld",
1480249787Smm		    zfs_prop_to_name(ZFS_PROP_QUOTA), (longlong_t)newval);
1481249787Smm	}
1482248571Smm
1483248571Smm	dmu_buf_will_dirty(ds->ds_dir->dd_dbuf, tx);
1484248571Smm	mutex_enter(&ds->ds_dir->dd_lock);
1485248571Smm	ds->ds_dir->dd_phys->dd_quota = newval;
1486248571Smm	mutex_exit(&ds->ds_dir->dd_lock);
1487248571Smm	dsl_dataset_rele(ds, FTAG);
1488168404Spjd}
1489168404Spjd
1490168404Spjdint
1491219089Spjddsl_dir_set_quota(const char *ddname, zprop_source_t source, uint64_t quota)
1492168404Spjd{
1493248571Smm	dsl_dir_set_qr_arg_t ddsqra;
1494168404Spjd
1495248571Smm	ddsqra.ddsqra_name = ddname;
1496248571Smm	ddsqra.ddsqra_source = source;
1497248571Smm	ddsqra.ddsqra_value = quota;
1498219089Spjd
1499248571Smm	return (dsl_sync_task(ddname, dsl_dir_set_quota_check,
1500269006Sdelphij	    dsl_dir_set_quota_sync, &ddsqra, 0, ZFS_SPACE_CHECK_NONE));
1501168404Spjd}
1502168404Spjd
1503185029Spjdint
1504248571Smmdsl_dir_set_reservation_check(void *arg, dmu_tx_t *tx)
1505168404Spjd{
1506248571Smm	dsl_dir_set_qr_arg_t *ddsqra = arg;
1507248571Smm	dsl_pool_t *dp = dmu_tx_pool(tx);
1508248571Smm	dsl_dataset_t *ds;
1509248571Smm	dsl_dir_t *dd;
1510248571Smm	uint64_t newval, used, avail;
1511248571Smm	int error;
1512168404Spjd
1513248571Smm	error = dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds);
1514248571Smm	if (error != 0)
1515248571Smm		return (error);
1516248571Smm	dd = ds->ds_dir;
1517219089Spjd
1518168404Spjd	/*
1519168404Spjd	 * If we are doing the preliminary check in open context, the
1520168404Spjd	 * space estimates may be inaccurate.
1521168404Spjd	 */
1522248571Smm	if (!dmu_tx_is_syncing(tx)) {
1523248571Smm		dsl_dataset_rele(ds, FTAG);
1524168404Spjd		return (0);
1525248571Smm	}
1526168404Spjd
1527248571Smm	error = dsl_prop_predict(ds->ds_dir,
1528248571Smm	    zfs_prop_to_name(ZFS_PROP_RESERVATION),
1529248571Smm	    ddsqra->ddsqra_source, ddsqra->ddsqra_value, &newval);
1530248571Smm	if (error != 0) {
1531248571Smm		dsl_dataset_rele(ds, FTAG);
1532248571Smm		return (error);
1533248571Smm	}
1534248571Smm
1535168404Spjd	mutex_enter(&dd->dd_lock);
1536185029Spjd	used = dd->dd_phys->dd_used_bytes;
1537168404Spjd	mutex_exit(&dd->dd_lock);
1538168404Spjd
1539168404Spjd	if (dd->dd_parent) {
1540168404Spjd		avail = dsl_dir_space_available(dd->dd_parent,
1541168404Spjd		    NULL, 0, FALSE);
1542168404Spjd	} else {
1543168404Spjd		avail = dsl_pool_adjustedsize(dd->dd_pool, B_FALSE) - used;
1544168404Spjd	}
1545168404Spjd
1546248571Smm	if (MAX(used, newval) > MAX(used, dd->dd_phys->dd_reserved)) {
1547248571Smm		uint64_t delta = MAX(used, newval) -
1548209962Smm		    MAX(used, dd->dd_phys->dd_reserved);
1549209962Smm
1550248571Smm		if (delta > avail ||
1551248571Smm		    (dd->dd_phys->dd_quota > 0 &&
1552248571Smm		    newval > dd->dd_phys->dd_quota))
1553249195Smm			error = SET_ERROR(ENOSPC);
1554209962Smm	}
1555209962Smm
1556248571Smm	dsl_dataset_rele(ds, FTAG);
1557248571Smm	return (error);
1558168404Spjd}
1559168404Spjd
1560248571Smmvoid
1561248571Smmdsl_dir_set_reservation_sync_impl(dsl_dir_t *dd, uint64_t value, dmu_tx_t *tx)
1562168404Spjd{
1563168404Spjd	uint64_t used;
1564168404Spjd	int64_t delta;
1565168404Spjd
1566185029Spjd	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1567185029Spjd
1568168404Spjd	mutex_enter(&dd->dd_lock);
1569185029Spjd	used = dd->dd_phys->dd_used_bytes;
1570248571Smm	delta = MAX(used, value) - MAX(used, dd->dd_phys->dd_reserved);
1571248571Smm	dd->dd_phys->dd_reserved = value;
1572168404Spjd
1573168404Spjd	if (dd->dd_parent != NULL) {
1574168404Spjd		/* Roll up this additional usage into our ancestors */
1575185029Spjd		dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD_RSRV,
1576185029Spjd		    delta, 0, 0, tx);
1577168404Spjd	}
1578185029Spjd	mutex_exit(&dd->dd_lock);
1579168404Spjd}
1580168404Spjd
1581248571Smmstatic void
1582248571Smmdsl_dir_set_reservation_sync(void *arg, dmu_tx_t *tx)
1583168404Spjd{
1584248571Smm	dsl_dir_set_qr_arg_t *ddsqra = arg;
1585248571Smm	dsl_pool_t *dp = dmu_tx_pool(tx);
1586219089Spjd	dsl_dataset_t *ds;
1587248571Smm	uint64_t newval;
1588168404Spjd
1589248571Smm	VERIFY0(dsl_dataset_hold(dp, ddsqra->ddsqra_name, FTAG, &ds));
1590219089Spjd
1591249787Smm	if (spa_version(dp->dp_spa) >= SPA_VERSION_RECVD_PROPS) {
1592249787Smm		dsl_prop_set_sync_impl(ds,
1593249787Smm		    zfs_prop_to_name(ZFS_PROP_RESERVATION),
1594249787Smm		    ddsqra->ddsqra_source, sizeof (ddsqra->ddsqra_value), 1,
1595249787Smm		    &ddsqra->ddsqra_value, tx);
1596219089Spjd
1597249787Smm		VERIFY0(dsl_prop_get_int_ds(ds,
1598249787Smm		    zfs_prop_to_name(ZFS_PROP_RESERVATION), &newval));
1599249787Smm	} else {
1600249787Smm		newval = ddsqra->ddsqra_value;
1601249787Smm		spa_history_log_internal_ds(ds, "set", tx, "%s=%lld",
1602249787Smm		    zfs_prop_to_name(ZFS_PROP_RESERVATION),
1603249787Smm		    (longlong_t)newval);
1604249787Smm	}
1605219089Spjd
1606248571Smm	dsl_dir_set_reservation_sync_impl(ds->ds_dir, newval, tx);
1607248571Smm	dsl_dataset_rele(ds, FTAG);
1608248571Smm}
1609219089Spjd
1610248571Smmint
1611248571Smmdsl_dir_set_reservation(const char *ddname, zprop_source_t source,
1612248571Smm    uint64_t reservation)
1613248571Smm{
1614248571Smm	dsl_dir_set_qr_arg_t ddsqra;
1615219089Spjd
1616248571Smm	ddsqra.ddsqra_name = ddname;
1617248571Smm	ddsqra.ddsqra_source = source;
1618248571Smm	ddsqra.ddsqra_value = reservation;
1619248571Smm
1620248571Smm	return (dsl_sync_task(ddname, dsl_dir_set_reservation_check,
1621269006Sdelphij	    dsl_dir_set_reservation_sync, &ddsqra, 0, ZFS_SPACE_CHECK_NONE));
1622168404Spjd}
1623168404Spjd
1624168404Spjdstatic dsl_dir_t *
1625168404Spjdclosest_common_ancestor(dsl_dir_t *ds1, dsl_dir_t *ds2)
1626168404Spjd{
1627168404Spjd	for (; ds1; ds1 = ds1->dd_parent) {
1628168404Spjd		dsl_dir_t *dd;
1629168404Spjd		for (dd = ds2; dd; dd = dd->dd_parent) {
1630168404Spjd			if (ds1 == dd)
1631168404Spjd				return (dd);
1632168404Spjd		}
1633168404Spjd	}
1634168404Spjd	return (NULL);
1635168404Spjd}
1636168404Spjd
1637168404Spjd/*
1638168404Spjd * If delta is applied to dd, how much of that delta would be applied to
1639168404Spjd * ancestor?  Syncing context only.
1640168404Spjd */
1641168404Spjdstatic int64_t
1642168404Spjdwould_change(dsl_dir_t *dd, int64_t delta, dsl_dir_t *ancestor)
1643168404Spjd{
1644168404Spjd	if (dd == ancestor)
1645168404Spjd		return (delta);
1646168404Spjd
1647168404Spjd	mutex_enter(&dd->dd_lock);
1648185029Spjd	delta = parent_delta(dd, dd->dd_phys->dd_used_bytes, delta);
1649168404Spjd	mutex_exit(&dd->dd_lock);
1650168404Spjd	return (would_change(dd->dd_parent, delta, ancestor));
1651168404Spjd}
1652168404Spjd
1653248571Smmtypedef struct dsl_dir_rename_arg {
1654248571Smm	const char *ddra_oldname;
1655248571Smm	const char *ddra_newname;
1656265744Sdelphij	cred_t *ddra_cred;
1657248571Smm} dsl_dir_rename_arg_t;
1658168404Spjd
1659248571Smm/* ARGSUSED */
1660168404Spjdstatic int
1661248571Smmdsl_valid_rename(dsl_pool_t *dp, dsl_dataset_t *ds, void *arg)
1662168404Spjd{
1663248571Smm	int *deltap = arg;
1664248571Smm	char namebuf[MAXNAMELEN];
1665168404Spjd
1666248571Smm	dsl_dataset_name(ds, namebuf);
1667248571Smm
1668248571Smm	if (strlen(namebuf) + *deltap >= MAXNAMELEN)
1669249195Smm		return (SET_ERROR(ENAMETOOLONG));
1670248571Smm	return (0);
1671248571Smm}
1672248571Smm
1673248571Smmstatic int
1674248571Smmdsl_dir_rename_check(void *arg, dmu_tx_t *tx)
1675248571Smm{
1676248571Smm	dsl_dir_rename_arg_t *ddra = arg;
1677248571Smm	dsl_pool_t *dp = dmu_tx_pool(tx);
1678248571Smm	dsl_dir_t *dd, *newparent;
1679248571Smm	const char *mynewname;
1680248571Smm	int error;
1681248571Smm	int delta = strlen(ddra->ddra_newname) - strlen(ddra->ddra_oldname);
1682248571Smm
1683248571Smm	/* target dir should exist */
1684248571Smm	error = dsl_dir_hold(dp, ddra->ddra_oldname, FTAG, &dd, NULL);
1685248571Smm	if (error != 0)
1686248571Smm		return (error);
1687248571Smm
1688248571Smm	/* new parent should exist */
1689248571Smm	error = dsl_dir_hold(dp, ddra->ddra_newname, FTAG,
1690248571Smm	    &newparent, &mynewname);
1691248571Smm	if (error != 0) {
1692248571Smm		dsl_dir_rele(dd, FTAG);
1693248571Smm		return (error);
1694226676Spjd	}
1695168404Spjd
1696248571Smm	/* can't rename to different pool */
1697248571Smm	if (dd->dd_pool != newparent->dd_pool) {
1698248571Smm		dsl_dir_rele(newparent, FTAG);
1699248571Smm		dsl_dir_rele(dd, FTAG);
1700249195Smm		return (SET_ERROR(ENXIO));
1701248571Smm	}
1702248571Smm
1703248571Smm	/* new name should not already exist */
1704248571Smm	if (mynewname == NULL) {
1705248571Smm		dsl_dir_rele(newparent, FTAG);
1706248571Smm		dsl_dir_rele(dd, FTAG);
1707249195Smm		return (SET_ERROR(EEXIST));
1708248571Smm	}
1709168404Spjd
1710248571Smm	/* if the name length is growing, validate child name lengths */
1711248571Smm	if (delta > 0) {
1712248571Smm		error = dmu_objset_find_dp(dp, dd->dd_object, dsl_valid_rename,
1713248571Smm		    &delta, DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
1714248571Smm		if (error != 0) {
1715248571Smm			dsl_dir_rele(newparent, FTAG);
1716248571Smm			dsl_dir_rele(dd, FTAG);
1717248571Smm			return (error);
1718248571Smm		}
1719248571Smm	}
1720248571Smm
1721265744Sdelphij	if (dmu_tx_is_syncing(tx)) {
1722267138Sdelphij		if (spa_feature_is_active(dp->dp_spa,
1723265744Sdelphij		    SPA_FEATURE_FS_SS_LIMIT)) {
1724265744Sdelphij			/*
1725265744Sdelphij			 * Although this is the check function and we don't
1726265744Sdelphij			 * normally make on-disk changes in check functions,
1727265744Sdelphij			 * we need to do that here.
1728265744Sdelphij			 *
1729265744Sdelphij			 * Ensure this portion of the tree's counts have been
1730265744Sdelphij			 * initialized in case the new parent has limits set.
1731265744Sdelphij			 */
1732265744Sdelphij			dsl_dir_init_fs_ss_count(dd, tx);
1733265744Sdelphij		}
1734265744Sdelphij	}
1735265744Sdelphij
1736248571Smm	if (newparent != dd->dd_parent) {
1737168404Spjd		/* is there enough space? */
1738168404Spjd		uint64_t myspace =
1739185029Spjd		    MAX(dd->dd_phys->dd_used_bytes, dd->dd_phys->dd_reserved);
1740265744Sdelphij		objset_t *os = dd->dd_pool->dp_meta_objset;
1741265744Sdelphij		uint64_t fs_cnt = 0;
1742265744Sdelphij		uint64_t ss_cnt = 0;
1743168404Spjd
1744265744Sdelphij		if (dsl_dir_is_zapified(dd)) {
1745265744Sdelphij			int err;
1746265744Sdelphij
1747265744Sdelphij			err = zap_lookup(os, dd->dd_object,
1748265744Sdelphij			    DD_FIELD_FILESYSTEM_COUNT, sizeof (fs_cnt), 1,
1749265744Sdelphij			    &fs_cnt);
1750267138Sdelphij			if (err != ENOENT && err != 0) {
1751267138Sdelphij				dsl_dir_rele(newparent, FTAG);
1752267138Sdelphij				dsl_dir_rele(dd, FTAG);
1753265744Sdelphij				return (err);
1754267138Sdelphij			}
1755265744Sdelphij
1756265744Sdelphij			/*
1757265744Sdelphij			 * have to add 1 for the filesystem itself that we're
1758265744Sdelphij			 * moving
1759265744Sdelphij			 */
1760265744Sdelphij			fs_cnt++;
1761265744Sdelphij
1762265744Sdelphij			err = zap_lookup(os, dd->dd_object,
1763265744Sdelphij			    DD_FIELD_SNAPSHOT_COUNT, sizeof (ss_cnt), 1,
1764265744Sdelphij			    &ss_cnt);
1765267138Sdelphij			if (err != ENOENT && err != 0) {
1766267138Sdelphij				dsl_dir_rele(newparent, FTAG);
1767267138Sdelphij				dsl_dir_rele(dd, FTAG);
1768265744Sdelphij				return (err);
1769267138Sdelphij			}
1770265744Sdelphij		}
1771265744Sdelphij
1772168404Spjd		/* no rename into our descendant */
1773248571Smm		if (closest_common_ancestor(dd, newparent) == dd) {
1774248571Smm			dsl_dir_rele(newparent, FTAG);
1775248571Smm			dsl_dir_rele(dd, FTAG);
1776249195Smm			return (SET_ERROR(EINVAL));
1777248571Smm		}
1778168404Spjd
1779248571Smm		error = dsl_dir_transfer_possible(dd->dd_parent,
1780265744Sdelphij		    newparent, fs_cnt, ss_cnt, myspace, ddra->ddra_cred);
1781248571Smm		if (error != 0) {
1782248571Smm			dsl_dir_rele(newparent, FTAG);
1783248571Smm			dsl_dir_rele(dd, FTAG);
1784248571Smm			return (error);
1785248571Smm		}
1786168404Spjd	}
1787168404Spjd
1788248571Smm	dsl_dir_rele(newparent, FTAG);
1789248571Smm	dsl_dir_rele(dd, FTAG);
1790168404Spjd	return (0);
1791168404Spjd}
1792168404Spjd
1793168404Spjdstatic void
1794248571Smmdsl_dir_rename_sync(void *arg, dmu_tx_t *tx)
1795168404Spjd{
1796248571Smm	dsl_dir_rename_arg_t *ddra = arg;
1797248571Smm	dsl_pool_t *dp = dmu_tx_pool(tx);
1798248571Smm	dsl_dir_t *dd, *newparent;
1799248571Smm	const char *mynewname;
1800248571Smm	int error;
1801168404Spjd	objset_t *mos = dp->dp_meta_objset;
1802168404Spjd
1803248571Smm	VERIFY0(dsl_dir_hold(dp, ddra->ddra_oldname, FTAG, &dd, NULL));
1804248571Smm	VERIFY0(dsl_dir_hold(dp, ddra->ddra_newname, FTAG, &newparent,
1805248571Smm	    &mynewname));
1806248571Smm
1807248571Smm	/* Log this before we change the name. */
1808248571Smm	spa_history_log_internal_dd(dd, "rename", tx,
1809248571Smm	    "-> %s", ddra->ddra_newname);
1810248571Smm
1811248571Smm	if (newparent != dd->dd_parent) {
1812265744Sdelphij		objset_t *os = dd->dd_pool->dp_meta_objset;
1813265744Sdelphij		uint64_t fs_cnt = 0;
1814265744Sdelphij		uint64_t ss_cnt = 0;
1815265744Sdelphij
1816265744Sdelphij		/*
1817265744Sdelphij		 * We already made sure the dd counts were initialized in the
1818265744Sdelphij		 * check function.
1819265744Sdelphij		 */
1820267138Sdelphij		if (spa_feature_is_active(dp->dp_spa,
1821265744Sdelphij		    SPA_FEATURE_FS_SS_LIMIT)) {
1822265744Sdelphij			VERIFY0(zap_lookup(os, dd->dd_object,
1823265744Sdelphij			    DD_FIELD_FILESYSTEM_COUNT, sizeof (fs_cnt), 1,
1824265744Sdelphij			    &fs_cnt));
1825265744Sdelphij			/* add 1 for the filesystem itself that we're moving */
1826265744Sdelphij			fs_cnt++;
1827265744Sdelphij
1828265744Sdelphij			VERIFY0(zap_lookup(os, dd->dd_object,
1829265744Sdelphij			    DD_FIELD_SNAPSHOT_COUNT, sizeof (ss_cnt), 1,
1830265744Sdelphij			    &ss_cnt));
1831265744Sdelphij		}
1832265744Sdelphij
1833265744Sdelphij		dsl_fs_ss_count_adjust(dd->dd_parent, -fs_cnt,
1834265744Sdelphij		    DD_FIELD_FILESYSTEM_COUNT, tx);
1835265744Sdelphij		dsl_fs_ss_count_adjust(newparent, fs_cnt,
1836265744Sdelphij		    DD_FIELD_FILESYSTEM_COUNT, tx);
1837265744Sdelphij
1838265744Sdelphij		dsl_fs_ss_count_adjust(dd->dd_parent, -ss_cnt,
1839265744Sdelphij		    DD_FIELD_SNAPSHOT_COUNT, tx);
1840265744Sdelphij		dsl_fs_ss_count_adjust(newparent, ss_cnt,
1841265744Sdelphij		    DD_FIELD_SNAPSHOT_COUNT, tx);
1842265744Sdelphij
1843185029Spjd		dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD,
1844185029Spjd		    -dd->dd_phys->dd_used_bytes,
1845168404Spjd		    -dd->dd_phys->dd_compressed_bytes,
1846168404Spjd		    -dd->dd_phys->dd_uncompressed_bytes, tx);
1847248571Smm		dsl_dir_diduse_space(newparent, DD_USED_CHILD,
1848185029Spjd		    dd->dd_phys->dd_used_bytes,
1849168404Spjd		    dd->dd_phys->dd_compressed_bytes,
1850168404Spjd		    dd->dd_phys->dd_uncompressed_bytes, tx);
1851185029Spjd
1852185029Spjd		if (dd->dd_phys->dd_reserved > dd->dd_phys->dd_used_bytes) {
1853185029Spjd			uint64_t unused_rsrv = dd->dd_phys->dd_reserved -
1854185029Spjd			    dd->dd_phys->dd_used_bytes;
1855185029Spjd
1856185029Spjd			dsl_dir_diduse_space(dd->dd_parent, DD_USED_CHILD_RSRV,
1857185029Spjd			    -unused_rsrv, 0, 0, tx);
1858248571Smm			dsl_dir_diduse_space(newparent, DD_USED_CHILD_RSRV,
1859185029Spjd			    unused_rsrv, 0, 0, tx);
1860185029Spjd		}
1861168404Spjd	}
1862168404Spjd
1863168404Spjd	dmu_buf_will_dirty(dd->dd_dbuf, tx);
1864168404Spjd
1865168404Spjd	/* remove from old parent zapobj */
1866248571Smm	error = zap_remove(mos, dd->dd_parent->dd_phys->dd_child_dir_zapobj,
1867168404Spjd	    dd->dd_myname, tx);
1868248571Smm	ASSERT0(error);
1869168404Spjd
1870248571Smm	(void) strcpy(dd->dd_myname, mynewname);
1871248571Smm	dsl_dir_rele(dd->dd_parent, dd);
1872248571Smm	dd->dd_phys->dd_parent_obj = newparent->dd_object;
1873248571Smm	VERIFY0(dsl_dir_hold_obj(dp,
1874248571Smm	    newparent->dd_object, NULL, dd, &dd->dd_parent));
1875168404Spjd
1876168404Spjd	/* add to new parent zapobj */
1877248571Smm	VERIFY0(zap_add(mos, newparent->dd_phys->dd_child_dir_zapobj,
1878248571Smm	    dd->dd_myname, 8, 1, &dd->dd_object, tx));
1879248571Smm
1880248571Smm#ifdef __FreeBSD__
1881219320Spjd#ifdef _KERNEL
1882248571Smm	zfsvfs_update_fromname(ddra->ddra_oldname, ddra->ddra_newname);
1883248571Smm	zvol_rename_minors(ddra->ddra_oldname, ddra->ddra_newname);
1884219320Spjd#endif
1885248571Smm#endif
1886185029Spjd
1887248571Smm	dsl_prop_notify_all(dd);
1888248571Smm
1889248571Smm	dsl_dir_rele(newparent, FTAG);
1890248571Smm	dsl_dir_rele(dd, FTAG);
1891168404Spjd}
1892168404Spjd
1893168404Spjdint
1894248571Smmdsl_dir_rename(const char *oldname, const char *newname)
1895168404Spjd{
1896248571Smm	dsl_dir_rename_arg_t ddra;
1897168404Spjd
1898248571Smm	ddra.ddra_oldname = oldname;
1899248571Smm	ddra.ddra_newname = newname;
1900265744Sdelphij	ddra.ddra_cred = CRED();
1901168404Spjd
1902248571Smm	return (dsl_sync_task(oldname,
1903269006Sdelphij	    dsl_dir_rename_check, dsl_dir_rename_sync, &ddra,
1904269006Sdelphij	    3, ZFS_SPACE_CHECK_RESERVED));
1905168404Spjd}
1906168404Spjd
1907168404Spjdint
1908265744Sdelphijdsl_dir_transfer_possible(dsl_dir_t *sdd, dsl_dir_t *tdd,
1909265744Sdelphij    uint64_t fs_cnt, uint64_t ss_cnt, uint64_t space, cred_t *cr)
1910168404Spjd{
1911168404Spjd	dsl_dir_t *ancestor;
1912168404Spjd	int64_t adelta;
1913168404Spjd	uint64_t avail;
1914265744Sdelphij	int err;
1915168404Spjd
1916168404Spjd	ancestor = closest_common_ancestor(sdd, tdd);
1917168404Spjd	adelta = would_change(sdd, -space, ancestor);
1918168404Spjd	avail = dsl_dir_space_available(tdd, ancestor, adelta, FALSE);
1919168404Spjd	if (avail < space)
1920249195Smm		return (SET_ERROR(ENOSPC));
1921168404Spjd
1922265744Sdelphij	err = dsl_fs_ss_limit_check(tdd, fs_cnt, ZFS_PROP_FILESYSTEM_LIMIT,
1923265744Sdelphij	    ancestor, cr);
1924265744Sdelphij	if (err != 0)
1925265744Sdelphij		return (err);
1926265744Sdelphij	err = dsl_fs_ss_limit_check(tdd, ss_cnt, ZFS_PROP_SNAPSHOT_LIMIT,
1927265744Sdelphij	    ancestor, cr);
1928265744Sdelphij	if (err != 0)
1929265744Sdelphij		return (err);
1930265744Sdelphij
1931168404Spjd	return (0);
1932168404Spjd}
1933219089Spjd
1934219089Spjdtimestruc_t
1935219089Spjddsl_dir_snap_cmtime(dsl_dir_t *dd)
1936219089Spjd{
1937219089Spjd	timestruc_t t;
1938219089Spjd
1939219089Spjd	mutex_enter(&dd->dd_lock);
1940219089Spjd	t = dd->dd_snap_cmtime;
1941219089Spjd	mutex_exit(&dd->dd_lock);
1942219089Spjd
1943219089Spjd	return (t);
1944219089Spjd}
1945219089Spjd
1946219089Spjdvoid
1947219089Spjddsl_dir_snap_cmtime_update(dsl_dir_t *dd)
1948219089Spjd{
1949219089Spjd	timestruc_t t;
1950219089Spjd
1951219089Spjd	gethrestime(&t);
1952219089Spjd	mutex_enter(&dd->dd_lock);
1953219089Spjd	dd->dd_snap_cmtime = t;
1954219089Spjd	mutex_exit(&dd->dd_lock);
1955219089Spjd}
1956263390Sdelphij
1957263390Sdelphijvoid
1958263390Sdelphijdsl_dir_zapify(dsl_dir_t *dd, dmu_tx_t *tx)
1959263390Sdelphij{
1960263390Sdelphij	objset_t *mos = dd->dd_pool->dp_meta_objset;
1961263390Sdelphij	dmu_object_zapify(mos, dd->dd_object, DMU_OT_DSL_DIR, tx);
1962263390Sdelphij}
1963265744Sdelphij
1964265744Sdelphijboolean_t
1965265744Sdelphijdsl_dir_is_zapified(dsl_dir_t *dd)
1966265744Sdelphij{
1967265744Sdelphij	dmu_object_info_t doi;
1968265744Sdelphij
1969265744Sdelphij	dmu_object_info_from_db(dd->dd_dbuf, &doi);
1970265744Sdelphij	return (doi.doi_type == DMU_OTN_ZAP_METADATA);
1971265744Sdelphij}
1972