xref: /illumos-gate/usr/src/uts/common/fs/zfs/zfs_dir.c (revision 85bb5f1d642e430b889478fb1200b511338085d7)
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 2008 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/types.h>
29 #include <sys/param.h>
30 #include <sys/time.h>
31 #include <sys/systm.h>
32 #include <sys/sysmacros.h>
33 #include <sys/resource.h>
34 #include <sys/vfs.h>
35 #include <sys/vnode.h>
36 #include <sys/file.h>
37 #include <sys/mode.h>
38 #include <sys/kmem.h>
39 #include <sys/uio.h>
40 #include <sys/pathname.h>
41 #include <sys/cmn_err.h>
42 #include <sys/errno.h>
43 #include <sys/stat.h>
44 #include <sys/unistd.h>
45 #include <sys/sunddi.h>
46 #include <sys/random.h>
47 #include <sys/policy.h>
48 #include <sys/zfs_dir.h>
49 #include <sys/zfs_acl.h>
50 #include <sys/fs/zfs.h>
51 #include "fs/fs_subr.h"
52 #include <sys/zap.h>
53 #include <sys/dmu.h>
54 #include <sys/atomic.h>
55 #include <sys/zfs_ctldir.h>
56 #include <sys/zfs_fuid.h>
57 #include <sys/dnlc.h>
58 #include <sys/extdirent.h>
59 
60 /*
61  * zfs_match_find() is used by zfs_dirent_lock() to peform zap lookups
62  * of names after deciding which is the appropriate lookup interface.
63  */
64 static int
65 zfs_match_find(zfsvfs_t *zfsvfs, znode_t *dzp, char *name, boolean_t exact,
66     boolean_t update, int *deflags, pathname_t *rpnp, uint64_t *zoid)
67 {
68 	int error;
69 
70 	if (zfsvfs->z_norm) {
71 		matchtype_t mt = MT_FIRST;
72 		boolean_t conflict = B_FALSE;
73 		size_t bufsz = 0;
74 		char *buf = NULL;
75 
76 		if (rpnp) {
77 			buf = rpnp->pn_buf;
78 			bufsz = rpnp->pn_bufsize;
79 		}
80 		if (exact)
81 			mt = MT_EXACT;
82 		/*
83 		 * In the non-mixed case we only expect there would ever
84 		 * be one match, but we need to use the normalizing lookup.
85 		 */
86 		error = zap_lookup_norm(zfsvfs->z_os, dzp->z_id, name, 8, 1,
87 		    zoid, mt, buf, bufsz, &conflict);
88 		if (!error && deflags)
89 			*deflags = conflict ? ED_CASE_CONFLICT : 0;
90 	} else {
91 		error = zap_lookup(zfsvfs->z_os, dzp->z_id, name, 8, 1, zoid);
92 	}
93 	*zoid = ZFS_DIRENT_OBJ(*zoid);
94 
95 	if (error == ENOENT && update)
96 		dnlc_update(ZTOV(dzp), name, DNLC_NO_VNODE);
97 
98 	return (error);
99 }
100 
101 /*
102  * Lock a directory entry.  A dirlock on <dzp, name> protects that name
103  * in dzp's directory zap object.  As long as you hold a dirlock, you can
104  * assume two things: (1) dzp cannot be reaped, and (2) no other thread
105  * can change the zap entry for (i.e. link or unlink) this name.
106  *
107  * Input arguments:
108  *	dzp	- znode for directory
109  *	name	- name of entry to lock
110  *	flag	- ZNEW: if the entry already exists, fail with EEXIST.
111  *		  ZEXISTS: if the entry does not exist, fail with ENOENT.
112  *		  ZSHARED: allow concurrent access with other ZSHARED callers.
113  *		  ZXATTR: we want dzp's xattr directory
114  *		  ZCILOOK: On a mixed sensitivity file system,
115  *			   this lookup should be case-insensitive.
116  *		  ZCIEXACT: On a purely case-insensitive file system,
117  *			    this lookup should be case-sensitive.
118  *		  ZRENAMING: we are locking for renaming, force narrow locks
119  *
120  * Output arguments:
121  *	zpp	- pointer to the znode for the entry (NULL if there isn't one)
122  *	dlpp	- pointer to the dirlock for this entry (NULL on error)
123  *      direntflags - (case-insensitive lookup only)
124  *		flags if multiple case-sensitive matches exist in directory
125  *      realpnp     - (case-insensitive lookup only)
126  *		actual name matched within the directory
127  *
128  * Return value: 0 on success or errno on failure.
129  *
130  * NOTE: Always checks for, and rejects, '.' and '..'.
131  * NOTE: For case-insensitive file systems we take wide locks (see below),
132  *	 but return znode pointers to a single match.
133  */
134 int
135 zfs_dirent_lock(zfs_dirlock_t **dlpp, znode_t *dzp, char *name, znode_t **zpp,
136     int flag, int *direntflags, pathname_t *realpnp)
137 {
138 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
139 	zfs_dirlock_t	*dl;
140 	boolean_t	update;
141 	boolean_t	exact;
142 	uint64_t	zoid;
143 	vnode_t		*vp = NULL;
144 	int		error = 0;
145 	int		cmpflags;
146 
147 	*zpp = NULL;
148 	*dlpp = NULL;
149 
150 	/*
151 	 * Verify that we are not trying to lock '.', '..', or '.zfs'
152 	 */
153 	if (name[0] == '.' &&
154 	    (name[1] == '\0' || (name[1] == '.' && name[2] == '\0')) ||
155 	    zfs_has_ctldir(dzp) && strcmp(name, ZFS_CTLDIR_NAME) == 0)
156 		return (EEXIST);
157 
158 	/*
159 	 * Case sensitivity and normalization preferences are set when
160 	 * the file system is created.  These are stored in the
161 	 * zfsvfs->z_case and zfsvfs->z_norm fields.  These choices
162 	 * affect what vnodes can be cached in the DNLC, how we
163 	 * perform zap lookups, and the "width" of our dirlocks.
164 	 *
165 	 * A normal dirlock locks a single name.  Note that with
166 	 * normalization a name can be composed multiple ways, but
167 	 * when normalized, these names all compare equal.  A wide
168 	 * dirlock locks multiple names.  We need these when the file
169 	 * system is supporting mixed-mode access.  It is sometimes
170 	 * necessary to lock all case permutations of file name at
171 	 * once so that simultaneous case-insensitive/case-sensitive
172 	 * behaves as rationally as possible.
173 	 */
174 
175 	/*
176 	 * Decide if exact matches should be requested when performing
177 	 * a zap lookup on file systems supporting case-insensitive
178 	 * access.
179 	 */
180 	exact =
181 	    ((zfsvfs->z_case == ZFS_CASE_INSENSITIVE) && (flag & ZCIEXACT)) ||
182 	    ((zfsvfs->z_case == ZFS_CASE_MIXED) && !(flag & ZCILOOK));
183 
184 	/*
185 	 * Only look in or update the DNLC if we are looking for the
186 	 * name on a file system that does not require normalization
187 	 * or case folding.  We can also look there if we happen to be
188 	 * on a non-normalizing, mixed sensitivity file system IF we
189 	 * are looking for the exact name.
190 	 *
191 	 * Maybe can add TO-UPPERed version of name to dnlc in ci-only
192 	 * case for performance improvement?
193 	 */
194 	update = !zfsvfs->z_norm ||
195 	    ((zfsvfs->z_case == ZFS_CASE_MIXED) &&
196 	    !(zfsvfs->z_norm & ~U8_TEXTPREP_TOUPPER) && !(flag & ZCILOOK));
197 
198 	/*
199 	 * ZRENAMING indicates we are in a situation where we should
200 	 * take narrow locks regardless of the file system's
201 	 * preferences for normalizing and case folding.  This will
202 	 * prevent us deadlocking trying to grab the same wide lock
203 	 * twice if the two names happen to be case-insensitive
204 	 * matches.
205 	 */
206 	if (flag & ZRENAMING)
207 		cmpflags = 0;
208 	else
209 		cmpflags = zfsvfs->z_norm;
210 
211 	/*
212 	 * Wait until there are no locks on this name.
213 	 */
214 	rw_enter(&dzp->z_name_lock, RW_READER);
215 	mutex_enter(&dzp->z_lock);
216 	for (;;) {
217 		if (dzp->z_unlinked) {
218 			mutex_exit(&dzp->z_lock);
219 			rw_exit(&dzp->z_name_lock);
220 			return (ENOENT);
221 		}
222 		for (dl = dzp->z_dirlocks; dl != NULL; dl = dl->dl_next) {
223 			if ((u8_strcmp(name, dl->dl_name, 0, cmpflags,
224 			    U8_UNICODE_LATEST, &error) == 0) || error != 0)
225 				break;
226 		}
227 		if (error != 0) {
228 			mutex_exit(&dzp->z_lock);
229 			rw_exit(&dzp->z_name_lock);
230 			return (ENOENT);
231 		}
232 		if (dl == NULL)	{
233 			/*
234 			 * Allocate a new dirlock and add it to the list.
235 			 */
236 			dl = kmem_alloc(sizeof (zfs_dirlock_t), KM_SLEEP);
237 			cv_init(&dl->dl_cv, NULL, CV_DEFAULT, NULL);
238 			dl->dl_name = name;
239 			dl->dl_sharecnt = 0;
240 			dl->dl_namesize = 0;
241 			dl->dl_dzp = dzp;
242 			dl->dl_next = dzp->z_dirlocks;
243 			dzp->z_dirlocks = dl;
244 			break;
245 		}
246 		if ((flag & ZSHARED) && dl->dl_sharecnt != 0)
247 			break;
248 		cv_wait(&dl->dl_cv, &dzp->z_lock);
249 	}
250 
251 	if ((flag & ZSHARED) && ++dl->dl_sharecnt > 1 && dl->dl_namesize == 0) {
252 		/*
253 		 * We're the second shared reference to dl.  Make a copy of
254 		 * dl_name in case the first thread goes away before we do.
255 		 * Note that we initialize the new name before storing its
256 		 * pointer into dl_name, because the first thread may load
257 		 * dl->dl_name at any time.  He'll either see the old value,
258 		 * which is his, or the new shared copy; either is OK.
259 		 */
260 		dl->dl_namesize = strlen(dl->dl_name) + 1;
261 		name = kmem_alloc(dl->dl_namesize, KM_SLEEP);
262 		bcopy(dl->dl_name, name, dl->dl_namesize);
263 		dl->dl_name = name;
264 	}
265 
266 	mutex_exit(&dzp->z_lock);
267 
268 	/*
269 	 * We have a dirlock on the name.  (Note that it is the dirlock,
270 	 * not the dzp's z_lock, that protects the name in the zap object.)
271 	 * See if there's an object by this name; if so, put a hold on it.
272 	 */
273 	if (flag & ZXATTR) {
274 		zoid = dzp->z_phys->zp_xattr;
275 		error = (zoid == 0 ? ENOENT : 0);
276 	} else {
277 		if (update)
278 			vp = dnlc_lookup(ZTOV(dzp), name);
279 		if (vp == DNLC_NO_VNODE) {
280 			VN_RELE(vp);
281 			error = ENOENT;
282 		} else if (vp) {
283 			if (flag & ZNEW) {
284 				zfs_dirent_unlock(dl);
285 				VN_RELE(vp);
286 				return (EEXIST);
287 			}
288 			*dlpp = dl;
289 			*zpp = VTOZ(vp);
290 			return (0);
291 		} else {
292 			error = zfs_match_find(zfsvfs, dzp, name, exact,
293 			    update, direntflags, realpnp, &zoid);
294 		}
295 	}
296 	if (error) {
297 		if (error != ENOENT || (flag & ZEXISTS)) {
298 			zfs_dirent_unlock(dl);
299 			return (error);
300 		}
301 	} else {
302 		if (flag & ZNEW) {
303 			zfs_dirent_unlock(dl);
304 			return (EEXIST);
305 		}
306 		error = zfs_zget(zfsvfs, zoid, zpp);
307 		if (error) {
308 			zfs_dirent_unlock(dl);
309 			return (error);
310 		}
311 		if (!(flag & ZXATTR) && update)
312 			dnlc_update(ZTOV(dzp), name, ZTOV(*zpp));
313 	}
314 
315 	*dlpp = dl;
316 
317 	return (0);
318 }
319 
320 /*
321  * Unlock this directory entry and wake anyone who was waiting for it.
322  */
323 void
324 zfs_dirent_unlock(zfs_dirlock_t *dl)
325 {
326 	znode_t *dzp = dl->dl_dzp;
327 	zfs_dirlock_t **prev_dl, *cur_dl;
328 
329 	mutex_enter(&dzp->z_lock);
330 	rw_exit(&dzp->z_name_lock);
331 	if (dl->dl_sharecnt > 1) {
332 		dl->dl_sharecnt--;
333 		mutex_exit(&dzp->z_lock);
334 		return;
335 	}
336 	prev_dl = &dzp->z_dirlocks;
337 	while ((cur_dl = *prev_dl) != dl)
338 		prev_dl = &cur_dl->dl_next;
339 	*prev_dl = dl->dl_next;
340 	cv_broadcast(&dl->dl_cv);
341 	mutex_exit(&dzp->z_lock);
342 
343 	if (dl->dl_namesize != 0)
344 		kmem_free(dl->dl_name, dl->dl_namesize);
345 	cv_destroy(&dl->dl_cv);
346 	kmem_free(dl, sizeof (*dl));
347 }
348 
349 /*
350  * Look up an entry in a directory.
351  *
352  * NOTE: '.' and '..' are handled as special cases because
353  *	no directory entries are actually stored for them.  If this is
354  *	the root of a filesystem, then '.zfs' is also treated as a
355  *	special pseudo-directory.
356  */
357 int
358 zfs_dirlook(znode_t *dzp, char *name, vnode_t **vpp, int flags,
359     int *deflg, pathname_t *rpnp)
360 {
361 	zfs_dirlock_t *dl;
362 	znode_t *zp;
363 	int error = 0;
364 
365 	if (name[0] == 0 || (name[0] == '.' && name[1] == 0)) {
366 		*vpp = ZTOV(dzp);
367 		VN_HOLD(*vpp);
368 	} else if (name[0] == '.' && name[1] == '.' && name[2] == 0) {
369 		zfsvfs_t *zfsvfs = dzp->z_zfsvfs;
370 		/*
371 		 * If we are a snapshot mounted under .zfs, return
372 		 * the vp for the snapshot directory.
373 		 */
374 		if (dzp->z_phys->zp_parent == dzp->z_id &&
375 		    zfsvfs->z_parent != zfsvfs) {
376 			error = zfsctl_root_lookup(zfsvfs->z_parent->z_ctldir,
377 			    "snapshot", vpp, NULL, 0, NULL, kcred,
378 			    NULL, NULL, NULL);
379 			return (error);
380 		}
381 		rw_enter(&dzp->z_parent_lock, RW_READER);
382 		error = zfs_zget(zfsvfs, dzp->z_phys->zp_parent, &zp);
383 		if (error == 0)
384 			*vpp = ZTOV(zp);
385 		rw_exit(&dzp->z_parent_lock);
386 	} else if (zfs_has_ctldir(dzp) && strcmp(name, ZFS_CTLDIR_NAME) == 0) {
387 		*vpp = zfsctl_root(dzp);
388 	} else {
389 		int zf;
390 
391 		zf = ZEXISTS | ZSHARED;
392 		if (flags & FIGNORECASE)
393 			zf |= ZCILOOK;
394 
395 		error = zfs_dirent_lock(&dl, dzp, name, &zp, zf, deflg, rpnp);
396 		if (error == 0) {
397 			*vpp = ZTOV(zp);
398 			zfs_dirent_unlock(dl);
399 			dzp->z_zn_prefetch = B_TRUE; /* enable prefetching */
400 		}
401 		rpnp = NULL;
402 	}
403 
404 	if ((flags & FIGNORECASE) && rpnp && !error)
405 		(void) strlcpy(rpnp->pn_buf, name, rpnp->pn_bufsize);
406 
407 	return (error);
408 }
409 
410 static char *
411 zfs_unlinked_hexname(char namebuf[17], uint64_t x)
412 {
413 	char *name = &namebuf[16];
414 	const char digits[16] = "0123456789abcdef";
415 
416 	*name = '\0';
417 	do {
418 		*--name = digits[x & 0xf];
419 		x >>= 4;
420 	} while (x != 0);
421 
422 	return (name);
423 }
424 
425 /*
426  * unlinked Set (formerly known as the "delete queue") Error Handling
427  *
428  * When dealing with the unlinked set, we dmu_tx_hold_zap(), but we
429  * don't specify the name of the entry that we will be manipulating.  We
430  * also fib and say that we won't be adding any new entries to the
431  * unlinked set, even though we might (this is to lower the minimum file
432  * size that can be deleted in a full filesystem).  So on the small
433  * chance that the nlink list is using a fat zap (ie. has more than
434  * 2000 entries), we *may* not pre-read a block that's needed.
435  * Therefore it is remotely possible for some of the assertions
436  * regarding the unlinked set below to fail due to i/o error.  On a
437  * nondebug system, this will result in the space being leaked.
438  */
439 void
440 zfs_unlinked_add(znode_t *zp, dmu_tx_t *tx)
441 {
442 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
443 	char obj_name[17];
444 	int error;
445 
446 	ASSERT(zp->z_unlinked);
447 	ASSERT3U(zp->z_phys->zp_links, ==, 0);
448 
449 	error = zap_add(zfsvfs->z_os, zfsvfs->z_unlinkedobj,
450 	    zfs_unlinked_hexname(obj_name, zp->z_id), 8, 1, &zp->z_id, tx);
451 	ASSERT3U(error, ==, 0);
452 }
453 
454 static void
455 zfs_unlinked_remove(znode_t *zp, dmu_tx_t *tx)
456 {
457 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
458 	char obj_name[17];
459 	int error;
460 
461 	ASSERT(zp->z_unlinked);
462 	ASSERT3U(zp->z_phys->zp_links, ==, 0);
463 
464 	error = zap_remove(zfsvfs->z_os, zfsvfs->z_unlinkedobj,
465 	    zfs_unlinked_hexname(obj_name, zp->z_id), tx);
466 	ASSERT3U(error, ==, 0);
467 }
468 
469 /*
470  * Clean up any znodes that had no links when we either crashed or
471  * (force) umounted the file system.
472  */
473 void
474 zfs_unlinked_drain(zfsvfs_t *zfsvfs)
475 {
476 	zap_cursor_t	zc;
477 	zap_attribute_t zap;
478 	dmu_object_info_t doi;
479 	znode_t		*zp;
480 	int		error;
481 
482 	/*
483 	 * Interate over the contents of the unlinked set.
484 	 */
485 	for (zap_cursor_init(&zc, zfsvfs->z_os, zfsvfs->z_unlinkedobj);
486 	    zap_cursor_retrieve(&zc, &zap) == 0;
487 	    zap_cursor_advance(&zc)) {
488 
489 		/*
490 		 * See what kind of object we have in list
491 		 */
492 
493 		error = dmu_object_info(zfsvfs->z_os,
494 		    zap.za_first_integer, &doi);
495 		if (error != 0)
496 			continue;
497 
498 		ASSERT((doi.doi_type == DMU_OT_PLAIN_FILE_CONTENTS) ||
499 		    (doi.doi_type == DMU_OT_DIRECTORY_CONTENTS));
500 		/*
501 		 * We need to re-mark these list entries for deletion,
502 		 * so we pull them back into core and set zp->z_unlinked.
503 		 */
504 		error = zfs_zget(zfsvfs, zap.za_first_integer, &zp);
505 
506 		/*
507 		 * We may pick up znodes that are already marked for deletion.
508 		 * This could happen during the purge of an extended attribute
509 		 * directory.  All we need to do is skip over them, since they
510 		 * are already in the system marked z_unlinked.
511 		 */
512 		if (error != 0)
513 			continue;
514 
515 		zp->z_unlinked = B_TRUE;
516 		VN_RELE(ZTOV(zp));
517 	}
518 	zap_cursor_fini(&zc);
519 }
520 
521 /*
522  * Delete the entire contents of a directory.  Return a count
523  * of the number of entries that could not be deleted. If we encounter
524  * an error, return a count of at least one so that the directory stays
525  * in the unlinked set.
526  *
527  * NOTE: this function assumes that the directory is inactive,
528  *	so there is no need to lock its entries before deletion.
529  *	Also, it assumes the directory contents is *only* regular
530  *	files.
531  */
532 static int
533 zfs_purgedir(znode_t *dzp)
534 {
535 	zap_cursor_t	zc;
536 	zap_attribute_t	zap;
537 	znode_t		*xzp;
538 	dmu_tx_t	*tx;
539 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
540 	zfs_dirlock_t	dl;
541 	int skipped = 0;
542 	int error;
543 
544 	for (zap_cursor_init(&zc, zfsvfs->z_os, dzp->z_id);
545 	    (error = zap_cursor_retrieve(&zc, &zap)) == 0;
546 	    zap_cursor_advance(&zc)) {
547 		error = zfs_zget(zfsvfs,
548 		    ZFS_DIRENT_OBJ(zap.za_first_integer), &xzp);
549 		if (error) {
550 			skipped += 1;
551 			continue;
552 		}
553 
554 		ASSERT((ZTOV(xzp)->v_type == VREG) ||
555 		    (ZTOV(xzp)->v_type == VLNK));
556 
557 		tx = dmu_tx_create(zfsvfs->z_os);
558 		dmu_tx_hold_bonus(tx, dzp->z_id);
559 		dmu_tx_hold_zap(tx, dzp->z_id, FALSE, zap.za_name);
560 		dmu_tx_hold_bonus(tx, xzp->z_id);
561 		dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
562 		error = dmu_tx_assign(tx, TXG_WAIT);
563 		if (error) {
564 			dmu_tx_abort(tx);
565 			VN_RELE(ZTOV(xzp));
566 			skipped += 1;
567 			continue;
568 		}
569 		bzero(&dl, sizeof (dl));
570 		dl.dl_dzp = dzp;
571 		dl.dl_name = zap.za_name;
572 
573 		error = zfs_link_destroy(&dl, xzp, tx, 0, NULL);
574 		if (error)
575 			skipped += 1;
576 		dmu_tx_commit(tx);
577 
578 		VN_RELE(ZTOV(xzp));
579 	}
580 	zap_cursor_fini(&zc);
581 	if (error != ENOENT)
582 		skipped += 1;
583 	return (skipped);
584 }
585 
586 void
587 zfs_rmnode(znode_t *zp)
588 {
589 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
590 	objset_t	*os = zfsvfs->z_os;
591 	znode_t		*xzp = NULL;
592 	dmu_tx_t	*tx;
593 	uint64_t	acl_obj;
594 	int		error;
595 
596 	ASSERT(ZTOV(zp)->v_count == 0);
597 	ASSERT(zp->z_phys->zp_links == 0);
598 
599 	/*
600 	 * If this is an attribute directory, purge its contents.
601 	 */
602 	if (ZTOV(zp)->v_type == VDIR && (zp->z_phys->zp_flags & ZFS_XATTR)) {
603 		if (zfs_purgedir(zp) != 0) {
604 			/*
605 			 * Not enough space to delete some xattrs.
606 			 * Leave it in the unlinked set.
607 			 */
608 			zfs_znode_dmu_fini(zp);
609 			zfs_znode_free(zp);
610 			return;
611 		}
612 	}
613 
614 	/*
615 	 * Free up all the data in the file.
616 	 */
617 	error = dmu_free_long_range(os, zp->z_id, 0, DMU_OBJECT_END);
618 	if (error) {
619 		/*
620 		 * Not enough space.  Leave the file in the unlinked set.
621 		 */
622 		zfs_znode_dmu_fini(zp);
623 		zfs_znode_free(zp);
624 		return;
625 	}
626 
627 	/*
628 	 * If the file has extended attributes, we're going to unlink
629 	 * the xattr dir.
630 	 */
631 	if (zp->z_phys->zp_xattr) {
632 		error = zfs_zget(zfsvfs, zp->z_phys->zp_xattr, &xzp);
633 		ASSERT(error == 0);
634 	}
635 
636 	acl_obj = zp->z_phys->zp_acl.z_acl_extern_obj;
637 
638 	/*
639 	 * Set up the final transaction.
640 	 */
641 	tx = dmu_tx_create(os);
642 	dmu_tx_hold_free(tx, zp->z_id, 0, DMU_OBJECT_END);
643 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
644 	if (xzp) {
645 		dmu_tx_hold_bonus(tx, xzp->z_id);
646 		dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, TRUE, NULL);
647 	}
648 	if (acl_obj)
649 		dmu_tx_hold_free(tx, acl_obj, 0, DMU_OBJECT_END);
650 	error = dmu_tx_assign(tx, TXG_WAIT);
651 	if (error) {
652 		/*
653 		 * Not enough space to delete the file.  Leave it in the
654 		 * unlinked set, leaking it until the fs is remounted (at
655 		 * which point we'll call zfs_unlinked_drain() to process it).
656 		 */
657 		dmu_tx_abort(tx);
658 		zfs_znode_dmu_fini(zp);
659 		zfs_znode_free(zp);
660 		goto out;
661 	}
662 
663 	if (xzp) {
664 		dmu_buf_will_dirty(xzp->z_dbuf, tx);
665 		mutex_enter(&xzp->z_lock);
666 		xzp->z_unlinked = B_TRUE;	/* mark xzp for deletion */
667 		xzp->z_phys->zp_links = 0;	/* no more links to it */
668 		mutex_exit(&xzp->z_lock);
669 		zfs_unlinked_add(xzp, tx);
670 	}
671 
672 	/* Remove this znode from the unlinked set */
673 	zfs_unlinked_remove(zp, tx);
674 
675 	zfs_znode_delete(zp, tx);
676 
677 	dmu_tx_commit(tx);
678 out:
679 	if (xzp)
680 		VN_RELE(ZTOV(xzp));
681 }
682 
683 static uint64_t
684 zfs_dirent(znode_t *zp)
685 {
686 	uint64_t de = zp->z_id;
687 	if (zp->z_zfsvfs->z_version >= ZPL_VERSION_DIRENT_TYPE)
688 		de |= IFTODT((zp)->z_phys->zp_mode) << 60;
689 	return (de);
690 }
691 
692 /*
693  * Link zp into dl.  Can only fail if zp has been unlinked.
694  */
695 int
696 zfs_link_create(zfs_dirlock_t *dl, znode_t *zp, dmu_tx_t *tx, int flag)
697 {
698 	znode_t *dzp = dl->dl_dzp;
699 	vnode_t *vp = ZTOV(zp);
700 	uint64_t value;
701 	int zp_is_dir = (vp->v_type == VDIR);
702 	int error;
703 
704 	dmu_buf_will_dirty(zp->z_dbuf, tx);
705 	mutex_enter(&zp->z_lock);
706 
707 	if (!(flag & ZRENAMING)) {
708 		if (zp->z_unlinked) {	/* no new links to unlinked zp */
709 			ASSERT(!(flag & (ZNEW | ZEXISTS)));
710 			mutex_exit(&zp->z_lock);
711 			return (ENOENT);
712 		}
713 		zp->z_phys->zp_links++;
714 	}
715 	zp->z_phys->zp_parent = dzp->z_id;	/* dzp is now zp's parent */
716 
717 	if (!(flag & ZNEW))
718 		zfs_time_stamper_locked(zp, STATE_CHANGED, tx);
719 	mutex_exit(&zp->z_lock);
720 
721 	dmu_buf_will_dirty(dzp->z_dbuf, tx);
722 	mutex_enter(&dzp->z_lock);
723 	dzp->z_phys->zp_size++;			/* one dirent added */
724 	dzp->z_phys->zp_links += zp_is_dir;	/* ".." link from zp */
725 	zfs_time_stamper_locked(dzp, CONTENT_MODIFIED, tx);
726 	mutex_exit(&dzp->z_lock);
727 
728 	value = zfs_dirent(zp);
729 	error = zap_add(zp->z_zfsvfs->z_os, dzp->z_id, dl->dl_name,
730 	    8, 1, &value, tx);
731 	ASSERT(error == 0);
732 
733 	dnlc_update(ZTOV(dzp), dl->dl_name, vp);
734 
735 	return (0);
736 }
737 
738 /*
739  * Unlink zp from dl, and mark zp for deletion if this was the last link.
740  * Can fail if zp is a mount point (EBUSY) or a non-empty directory (EEXIST).
741  * If 'unlinkedp' is NULL, we put unlinked znodes on the unlinked list.
742  * If it's non-NULL, we use it to indicate whether the znode needs deletion,
743  * and it's the caller's job to do it.
744  */
745 int
746 zfs_link_destroy(zfs_dirlock_t *dl, znode_t *zp, dmu_tx_t *tx, int flag,
747 	boolean_t *unlinkedp)
748 {
749 	znode_t *dzp = dl->dl_dzp;
750 	vnode_t *vp = ZTOV(zp);
751 	int zp_is_dir = (vp->v_type == VDIR);
752 	boolean_t unlinked = B_FALSE;
753 	int error;
754 
755 	dnlc_remove(ZTOV(dzp), dl->dl_name);
756 
757 	if (!(flag & ZRENAMING)) {
758 		dmu_buf_will_dirty(zp->z_dbuf, tx);
759 
760 		if (vn_vfswlock(vp))		/* prevent new mounts on zp */
761 			return (EBUSY);
762 
763 		if (vn_ismntpt(vp)) {		/* don't remove mount point */
764 			vn_vfsunlock(vp);
765 			return (EBUSY);
766 		}
767 
768 		mutex_enter(&zp->z_lock);
769 		if (zp_is_dir && !zfs_dirempty(zp)) {	/* dir not empty */
770 			mutex_exit(&zp->z_lock);
771 			vn_vfsunlock(vp);
772 			return (EEXIST);
773 		}
774 		if (zp->z_phys->zp_links <= zp_is_dir) {
775 			zfs_panic_recover("zfs: link count on %s is %u, "
776 			    "should be at least %u",
777 			    zp->z_vnode->v_path ? zp->z_vnode->v_path :
778 			    "<unknown>", (int)zp->z_phys->zp_links,
779 			    zp_is_dir + 1);
780 			zp->z_phys->zp_links = zp_is_dir + 1;
781 		}
782 		if (--zp->z_phys->zp_links == zp_is_dir) {
783 			zp->z_unlinked = B_TRUE;
784 			zp->z_phys->zp_links = 0;
785 			unlinked = B_TRUE;
786 		} else {
787 			zfs_time_stamper_locked(zp, STATE_CHANGED, tx);
788 		}
789 		mutex_exit(&zp->z_lock);
790 		vn_vfsunlock(vp);
791 	}
792 
793 	dmu_buf_will_dirty(dzp->z_dbuf, tx);
794 	mutex_enter(&dzp->z_lock);
795 	dzp->z_phys->zp_size--;			/* one dirent removed */
796 	dzp->z_phys->zp_links -= zp_is_dir;	/* ".." link from zp */
797 	zfs_time_stamper_locked(dzp, CONTENT_MODIFIED, tx);
798 	mutex_exit(&dzp->z_lock);
799 
800 	if (zp->z_zfsvfs->z_norm) {
801 		if (((zp->z_zfsvfs->z_case == ZFS_CASE_INSENSITIVE) &&
802 		    (flag & ZCIEXACT)) ||
803 		    ((zp->z_zfsvfs->z_case == ZFS_CASE_MIXED) &&
804 		    !(flag & ZCILOOK)))
805 			error = zap_remove_norm(zp->z_zfsvfs->z_os,
806 			    dzp->z_id, dl->dl_name, MT_EXACT, tx);
807 		else
808 			error = zap_remove_norm(zp->z_zfsvfs->z_os,
809 			    dzp->z_id, dl->dl_name, MT_FIRST, tx);
810 	} else {
811 		error = zap_remove(zp->z_zfsvfs->z_os,
812 		    dzp->z_id, dl->dl_name, tx);
813 	}
814 	ASSERT(error == 0);
815 
816 	if (unlinkedp != NULL)
817 		*unlinkedp = unlinked;
818 	else if (unlinked)
819 		zfs_unlinked_add(zp, tx);
820 
821 	return (0);
822 }
823 
824 /*
825  * Indicate whether the directory is empty.  Works with or without z_lock
826  * held, but can only be consider a hint in the latter case.  Returns true
827  * if only "." and ".." remain and there's no work in progress.
828  */
829 boolean_t
830 zfs_dirempty(znode_t *dzp)
831 {
832 	return (dzp->z_phys->zp_size == 2 && dzp->z_dirlocks == 0);
833 }
834 
835 int
836 zfs_make_xattrdir(znode_t *zp, vattr_t *vap, vnode_t **xvpp, cred_t *cr)
837 {
838 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
839 	znode_t *xzp;
840 	dmu_tx_t *tx;
841 	int error;
842 	zfs_fuid_info_t *fuidp = NULL;
843 
844 	*xvpp = NULL;
845 
846 	if (error = zfs_zaccess(zp, ACE_WRITE_NAMED_ATTRS, 0, B_FALSE, cr))
847 		return (error);
848 
849 	tx = dmu_tx_create(zfsvfs->z_os);
850 	dmu_tx_hold_bonus(tx, zp->z_id);
851 	dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
852 	if (IS_EPHEMERAL(crgetuid(cr)) || IS_EPHEMERAL(crgetgid(cr))) {
853 		if (zfsvfs->z_fuid_obj == 0) {
854 			dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
855 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
856 			    FUID_SIZE_ESTIMATE(zfsvfs));
857 			dmu_tx_hold_zap(tx, MASTER_NODE_OBJ, FALSE, NULL);
858 		} else {
859 			dmu_tx_hold_bonus(tx, zfsvfs->z_fuid_obj);
860 			dmu_tx_hold_write(tx, zfsvfs->z_fuid_obj, 0,
861 			    FUID_SIZE_ESTIMATE(zfsvfs));
862 		}
863 	}
864 	error = dmu_tx_assign(tx, zfsvfs->z_assign);
865 	if (error) {
866 		if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT)
867 			dmu_tx_wait(tx);
868 		dmu_tx_abort(tx);
869 		return (error);
870 	}
871 	zfs_mknode(zp, vap, tx, cr, IS_XATTR, &xzp, 0, NULL, &fuidp);
872 	ASSERT(xzp->z_phys->zp_parent == zp->z_id);
873 	dmu_buf_will_dirty(zp->z_dbuf, tx);
874 	zp->z_phys->zp_xattr = xzp->z_id;
875 
876 	(void) zfs_log_create(zfsvfs->z_log, tx, TX_MKXATTR, zp,
877 	    xzp, "", NULL, fuidp, vap);
878 	if (fuidp)
879 		zfs_fuid_info_free(fuidp);
880 	dmu_tx_commit(tx);
881 
882 	*xvpp = ZTOV(xzp);
883 
884 	return (0);
885 }
886 
887 /*
888  * Return a znode for the extended attribute directory for zp.
889  * ** If the directory does not already exist, it is created **
890  *
891  *	IN:	zp	- znode to obtain attribute directory from
892  *		cr	- credentials of caller
893  *		flags	- flags from the VOP_LOOKUP call
894  *
895  *	OUT:	xzpp	- pointer to extended attribute znode
896  *
897  *	RETURN:	0 on success
898  *		error number on failure
899  */
900 int
901 zfs_get_xattrdir(znode_t *zp, vnode_t **xvpp, cred_t *cr, int flags)
902 {
903 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
904 	znode_t		*xzp;
905 	zfs_dirlock_t	*dl;
906 	vattr_t		va;
907 	int		error;
908 top:
909 	error = zfs_dirent_lock(&dl, zp, "", &xzp, ZXATTR, NULL, NULL);
910 	if (error)
911 		return (error);
912 
913 	if (xzp != NULL) {
914 		*xvpp = ZTOV(xzp);
915 		zfs_dirent_unlock(dl);
916 		return (0);
917 	}
918 
919 	ASSERT(zp->z_phys->zp_xattr == 0);
920 
921 	if (!(flags & CREATE_XATTR_DIR)) {
922 		zfs_dirent_unlock(dl);
923 		return (ENOENT);
924 	}
925 
926 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
927 		zfs_dirent_unlock(dl);
928 		return (EROFS);
929 	}
930 
931 	/*
932 	 * The ability to 'create' files in an attribute
933 	 * directory comes from the write_xattr permission on the base file.
934 	 *
935 	 * The ability to 'search' an attribute directory requires
936 	 * read_xattr permission on the base file.
937 	 *
938 	 * Once in a directory the ability to read/write attributes
939 	 * is controlled by the permissions on the attribute file.
940 	 */
941 	va.va_mask = AT_TYPE | AT_MODE | AT_UID | AT_GID;
942 	va.va_type = VDIR;
943 	va.va_mode = S_IFDIR | S_ISVTX | 0777;
944 	zfs_fuid_map_ids(zp, cr, &va.va_uid, &va.va_gid);
945 
946 	error = zfs_make_xattrdir(zp, &va, xvpp, cr);
947 	zfs_dirent_unlock(dl);
948 
949 	if (error == ERESTART && zfsvfs->z_assign == TXG_NOWAIT) {
950 		/* NB: we already did dmu_tx_wait() if necessary */
951 		goto top;
952 	}
953 
954 	return (error);
955 }
956 
957 /*
958  * Decide whether it is okay to remove within a sticky directory.
959  *
960  * In sticky directories, write access is not sufficient;
961  * you can remove entries from a directory only if:
962  *
963  *	you own the directory,
964  *	you own the entry,
965  *	the entry is a plain file and you have write access,
966  *	or you are privileged (checked in secpolicy...).
967  *
968  * The function returns 0 if remove access is granted.
969  */
970 int
971 zfs_sticky_remove_access(znode_t *zdp, znode_t *zp, cred_t *cr)
972 {
973 	uid_t  		uid;
974 	uid_t		downer;
975 	uid_t		fowner;
976 	zfsvfs_t	*zfsvfs = zdp->z_zfsvfs;
977 
978 	if (zdp->z_zfsvfs->z_assign >= TXG_INITIAL)	/* ZIL replay */
979 		return (0);
980 
981 	if ((zdp->z_phys->zp_mode & S_ISVTX) == 0)
982 		return (0);
983 
984 	downer = zfs_fuid_map_id(zfsvfs, zdp->z_phys->zp_uid, cr, ZFS_OWNER);
985 	fowner = zfs_fuid_map_id(zfsvfs, zp->z_phys->zp_uid, cr, ZFS_OWNER);
986 
987 	if ((uid = crgetuid(cr)) == downer || uid == fowner ||
988 	    (ZTOV(zp)->v_type == VREG &&
989 	    zfs_zaccess(zp, ACE_WRITE_DATA, 0, B_FALSE, cr) == 0))
990 		return (0);
991 	else
992 		return (secpolicy_vnode_remove(cr));
993 }
994