xref: /illumos-gate/usr/src/uts/common/fs/zfs/zfs_dir.c (revision a3905a45920de250d181b66ac0b6b71bd200d9ef)
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 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2013, 2016 by Delphix. All rights reserved.
25  * Copyright 2017 Nexenta Systems, Inc.
26  */
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/sa.h>
58 #include <sys/zfs_sa.h>
59 #include <sys/dnlc.h>
60 #include <sys/extdirent.h>
61 
62 /*
63  * zfs_match_find() is used by zfs_dirent_lock() to peform zap lookups
64  * of names after deciding which is the appropriate lookup interface.
65  */
66 static int
67 zfs_match_find(zfsvfs_t *zfsvfs, znode_t *dzp, char *name, matchtype_t mt,
68     boolean_t update, int *deflags, pathname_t *rpnp, uint64_t *zoid)
69 {
70 	int error;
71 
72 	if (zfsvfs->z_norm) {
73 		boolean_t conflict = B_FALSE;
74 		size_t bufsz = 0;
75 		char *buf = NULL;
76 
77 		if (rpnp) {
78 			buf = rpnp->pn_buf;
79 			bufsz = rpnp->pn_bufsize;
80 		}
81 
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  *		  ZHAVELOCK: Don't grab the z_name_lock for this call. The
120  *			     current thread already holds it.
121  *
122  * Output arguments:
123  *	zpp	- pointer to the znode for the entry (NULL if there isn't one)
124  *	dlpp	- pointer to the dirlock for this entry (NULL on error)
125  *      direntflags - (case-insensitive lookup only)
126  *		flags if multiple case-sensitive matches exist in directory
127  *      realpnp     - (case-insensitive lookup only)
128  *		actual name matched within the directory
129  *
130  * Return value: 0 on success or errno on failure.
131  *
132  * NOTE: Always checks for, and rejects, '.' and '..'.
133  * NOTE: For case-insensitive file systems we take wide locks (see below),
134  *	 but return znode pointers to a single match.
135  */
136 int
137 zfs_dirent_lock(zfs_dirlock_t **dlpp, znode_t *dzp, char *name, znode_t **zpp,
138     int flag, int *direntflags, pathname_t *realpnp)
139 {
140 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
141 	zfs_dirlock_t	*dl;
142 	boolean_t	update;
143 	matchtype_t	mt = 0;
144 	uint64_t	zoid;
145 	vnode_t		*vp = NULL;
146 	int		error = 0;
147 	int		cmpflags;
148 
149 	*zpp = NULL;
150 	*dlpp = NULL;
151 
152 	/*
153 	 * Verify that we are not trying to lock '.', '..', or '.zfs'
154 	 */
155 	if (name[0] == '.' &&
156 	    (name[1] == '\0' || (name[1] == '.' && name[2] == '\0')) ||
157 	    zfs_has_ctldir(dzp) && strcmp(name, ZFS_CTLDIR_NAME) == 0)
158 		return (SET_ERROR(EEXIST));
159 
160 	/*
161 	 * Case sensitivity and normalization preferences are set when
162 	 * the file system is created.  These are stored in the
163 	 * zfsvfs->z_case and zfsvfs->z_norm fields.  These choices
164 	 * affect what vnodes can be cached in the DNLC, how we
165 	 * perform zap lookups, and the "width" of our dirlocks.
166 	 *
167 	 * A normal dirlock locks a single name.  Note that with
168 	 * normalization a name can be composed multiple ways, but
169 	 * when normalized, these names all compare equal.  A wide
170 	 * dirlock locks multiple names.  We need these when the file
171 	 * system is supporting mixed-mode access.  It is sometimes
172 	 * necessary to lock all case permutations of file name at
173 	 * once so that simultaneous case-insensitive/case-sensitive
174 	 * behaves as rationally as possible.
175 	 */
176 
177 	/*
178 	 * When matching we may need to normalize & change case according to
179 	 * FS settings.
180 	 *
181 	 * Note that a normalized match is necessary for a case insensitive
182 	 * filesystem when the lookup request is not exact because normalization
183 	 * can fold case independent of normalizing code point sequences.
184 	 *
185 	 * See the table above zfs_dropname().
186 	 */
187 	if (zfsvfs->z_norm != 0) {
188 		mt = MT_NORMALIZE;
189 
190 		/*
191 		 * Determine if the match needs to honor the case specified in
192 		 * lookup, and if so keep track of that so that during
193 		 * normalization we don't fold case.
194 		 */
195 		if ((zfsvfs->z_case == ZFS_CASE_INSENSITIVE &&
196 		    (flag & ZCIEXACT)) ||
197 		    (zfsvfs->z_case == ZFS_CASE_MIXED && !(flag & ZCILOOK))) {
198 			mt |= MT_MATCH_CASE;
199 		}
200 	}
201 
202 	/*
203 	 * Only look in or update the DNLC if we are looking for the
204 	 * name on a file system that does not require normalization
205 	 * or case folding.  We can also look there if we happen to be
206 	 * on a non-normalizing, mixed sensitivity file system IF we
207 	 * are looking for the exact name.
208 	 *
209 	 * Maybe can add TO-UPPERed version of name to dnlc in ci-only
210 	 * case for performance improvement?
211 	 */
212 	update = !zfsvfs->z_norm ||
213 	    (zfsvfs->z_case == ZFS_CASE_MIXED &&
214 	    !(zfsvfs->z_norm & ~U8_TEXTPREP_TOUPPER) && !(flag & ZCILOOK));
215 
216 	/*
217 	 * ZRENAMING indicates we are in a situation where we should
218 	 * take narrow locks regardless of the file system's
219 	 * preferences for normalizing and case folding.  This will
220 	 * prevent us deadlocking trying to grab the same wide lock
221 	 * twice if the two names happen to be case-insensitive
222 	 * matches.
223 	 */
224 	if (flag & ZRENAMING)
225 		cmpflags = 0;
226 	else
227 		cmpflags = zfsvfs->z_norm;
228 
229 	/*
230 	 * Wait until there are no locks on this name.
231 	 *
232 	 * Don't grab the the lock if it is already held. However, cannot
233 	 * have both ZSHARED and ZHAVELOCK together.
234 	 */
235 	ASSERT(!(flag & ZSHARED) || !(flag & ZHAVELOCK));
236 	if (!(flag & ZHAVELOCK))
237 		rw_enter(&dzp->z_name_lock, RW_READER);
238 
239 	mutex_enter(&dzp->z_lock);
240 	for (;;) {
241 		if (dzp->z_unlinked) {
242 			mutex_exit(&dzp->z_lock);
243 			if (!(flag & ZHAVELOCK))
244 				rw_exit(&dzp->z_name_lock);
245 			return (SET_ERROR(ENOENT));
246 		}
247 		for (dl = dzp->z_dirlocks; dl != NULL; dl = dl->dl_next) {
248 			if ((u8_strcmp(name, dl->dl_name, 0, cmpflags,
249 			    U8_UNICODE_LATEST, &error) == 0) || error != 0)
250 				break;
251 		}
252 		if (error != 0) {
253 			mutex_exit(&dzp->z_lock);
254 			if (!(flag & ZHAVELOCK))
255 				rw_exit(&dzp->z_name_lock);
256 			return (SET_ERROR(ENOENT));
257 		}
258 		if (dl == NULL)	{
259 			/*
260 			 * Allocate a new dirlock and add it to the list.
261 			 */
262 			dl = kmem_alloc(sizeof (zfs_dirlock_t), KM_SLEEP);
263 			cv_init(&dl->dl_cv, NULL, CV_DEFAULT, NULL);
264 			dl->dl_name = name;
265 			dl->dl_sharecnt = 0;
266 			dl->dl_namelock = 0;
267 			dl->dl_namesize = 0;
268 			dl->dl_dzp = dzp;
269 			dl->dl_next = dzp->z_dirlocks;
270 			dzp->z_dirlocks = dl;
271 			break;
272 		}
273 		if ((flag & ZSHARED) && dl->dl_sharecnt != 0)
274 			break;
275 		cv_wait(&dl->dl_cv, &dzp->z_lock);
276 	}
277 
278 	/*
279 	 * If the z_name_lock was NOT held for this dirlock record it.
280 	 */
281 	if (flag & ZHAVELOCK)
282 		dl->dl_namelock = 1;
283 
284 	if ((flag & ZSHARED) && ++dl->dl_sharecnt > 1 && dl->dl_namesize == 0) {
285 		/*
286 		 * We're the second shared reference to dl.  Make a copy of
287 		 * dl_name in case the first thread goes away before we do.
288 		 * Note that we initialize the new name before storing its
289 		 * pointer into dl_name, because the first thread may load
290 		 * dl->dl_name at any time.  It'll either see the old value,
291 		 * which belongs to it, or the new shared copy; either is OK.
292 		 */
293 		dl->dl_namesize = strlen(dl->dl_name) + 1;
294 		name = kmem_alloc(dl->dl_namesize, KM_SLEEP);
295 		bcopy(dl->dl_name, name, dl->dl_namesize);
296 		dl->dl_name = name;
297 	}
298 
299 	mutex_exit(&dzp->z_lock);
300 
301 	/*
302 	 * We have a dirlock on the name.  (Note that it is the dirlock,
303 	 * not the dzp's z_lock, that protects the name in the zap object.)
304 	 * See if there's an object by this name; if so, put a hold on it.
305 	 */
306 	if (flag & ZXATTR) {
307 		error = sa_lookup(dzp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs), &zoid,
308 		    sizeof (zoid));
309 		if (error == 0)
310 			error = (zoid == 0 ? ENOENT : 0);
311 	} else {
312 		if (update)
313 			vp = dnlc_lookup(ZTOV(dzp), name);
314 		if (vp == DNLC_NO_VNODE) {
315 			VN_RELE(vp);
316 			error = SET_ERROR(ENOENT);
317 		} else if (vp) {
318 			if (flag & ZNEW) {
319 				zfs_dirent_unlock(dl);
320 				VN_RELE(vp);
321 				return (SET_ERROR(EEXIST));
322 			}
323 			*dlpp = dl;
324 			*zpp = VTOZ(vp);
325 			return (0);
326 		} else {
327 			error = zfs_match_find(zfsvfs, dzp, name, mt,
328 			    update, direntflags, realpnp, &zoid);
329 		}
330 	}
331 	if (error) {
332 		if (error != ENOENT || (flag & ZEXISTS)) {
333 			zfs_dirent_unlock(dl);
334 			return (error);
335 		}
336 	} else {
337 		if (flag & ZNEW) {
338 			zfs_dirent_unlock(dl);
339 			return (SET_ERROR(EEXIST));
340 		}
341 		error = zfs_zget(zfsvfs, zoid, zpp);
342 		if (error) {
343 			zfs_dirent_unlock(dl);
344 			return (error);
345 		}
346 		if (!(flag & ZXATTR) && update)
347 			dnlc_update(ZTOV(dzp), name, ZTOV(*zpp));
348 	}
349 
350 	*dlpp = dl;
351 
352 	return (0);
353 }
354 
355 /*
356  * Unlock this directory entry and wake anyone who was waiting for it.
357  */
358 void
359 zfs_dirent_unlock(zfs_dirlock_t *dl)
360 {
361 	znode_t *dzp = dl->dl_dzp;
362 	zfs_dirlock_t **prev_dl, *cur_dl;
363 
364 	mutex_enter(&dzp->z_lock);
365 
366 	if (!dl->dl_namelock)
367 		rw_exit(&dzp->z_name_lock);
368 
369 	if (dl->dl_sharecnt > 1) {
370 		dl->dl_sharecnt--;
371 		mutex_exit(&dzp->z_lock);
372 		return;
373 	}
374 	prev_dl = &dzp->z_dirlocks;
375 	while ((cur_dl = *prev_dl) != dl)
376 		prev_dl = &cur_dl->dl_next;
377 	*prev_dl = dl->dl_next;
378 	cv_broadcast(&dl->dl_cv);
379 	mutex_exit(&dzp->z_lock);
380 
381 	if (dl->dl_namesize != 0)
382 		kmem_free(dl->dl_name, dl->dl_namesize);
383 	cv_destroy(&dl->dl_cv);
384 	kmem_free(dl, sizeof (*dl));
385 }
386 
387 /*
388  * Look up an entry in a directory.
389  *
390  * NOTE: '.' and '..' are handled as special cases because
391  *	no directory entries are actually stored for them.  If this is
392  *	the root of a filesystem, then '.zfs' is also treated as a
393  *	special pseudo-directory.
394  */
395 int
396 zfs_dirlook(znode_t *dzp, char *name, vnode_t **vpp, int flags,
397     int *deflg, pathname_t *rpnp)
398 {
399 	zfs_dirlock_t *dl;
400 	znode_t *zp;
401 	int error = 0;
402 	uint64_t parent;
403 
404 	if (name[0] == 0 || (name[0] == '.' && name[1] == 0)) {
405 		*vpp = ZTOV(dzp);
406 		VN_HOLD(*vpp);
407 	} else if (name[0] == '.' && name[1] == '.' && name[2] == 0) {
408 		zfsvfs_t *zfsvfs = dzp->z_zfsvfs;
409 
410 		/*
411 		 * If we are a snapshot mounted under .zfs, return
412 		 * the vp for the snapshot directory.
413 		 */
414 		if ((error = sa_lookup(dzp->z_sa_hdl,
415 		    SA_ZPL_PARENT(zfsvfs), &parent, sizeof (parent))) != 0)
416 			return (error);
417 		if (parent == dzp->z_id && zfsvfs->z_parent != zfsvfs) {
418 			error = zfsctl_root_lookup(zfsvfs->z_parent->z_ctldir,
419 			    "snapshot", vpp, NULL, 0, NULL, kcred,
420 			    NULL, NULL, NULL);
421 			return (error);
422 		}
423 		rw_enter(&dzp->z_parent_lock, RW_READER);
424 		error = zfs_zget(zfsvfs, parent, &zp);
425 		if (error == 0)
426 			*vpp = ZTOV(zp);
427 		rw_exit(&dzp->z_parent_lock);
428 	} else if (zfs_has_ctldir(dzp) && strcmp(name, ZFS_CTLDIR_NAME) == 0) {
429 		*vpp = zfsctl_root(dzp);
430 	} else {
431 		int zf;
432 
433 		zf = ZEXISTS | ZSHARED;
434 		if (flags & FIGNORECASE)
435 			zf |= ZCILOOK;
436 
437 		error = zfs_dirent_lock(&dl, dzp, name, &zp, zf, deflg, rpnp);
438 		if (error == 0) {
439 			*vpp = ZTOV(zp);
440 			zfs_dirent_unlock(dl);
441 			dzp->z_zn_prefetch = B_TRUE; /* enable prefetching */
442 		}
443 		rpnp = NULL;
444 	}
445 
446 	if ((flags & FIGNORECASE) && rpnp && !error)
447 		(void) strlcpy(rpnp->pn_buf, name, rpnp->pn_bufsize);
448 
449 	return (error);
450 }
451 
452 /*
453  * unlinked Set (formerly known as the "delete queue") Error Handling
454  *
455  * When dealing with the unlinked set, we dmu_tx_hold_zap(), but we
456  * don't specify the name of the entry that we will be manipulating.  We
457  * also fib and say that we won't be adding any new entries to the
458  * unlinked set, even though we might (this is to lower the minimum file
459  * size that can be deleted in a full filesystem).  So on the small
460  * chance that the nlink list is using a fat zap (ie. has more than
461  * 2000 entries), we *may* not pre-read a block that's needed.
462  * Therefore it is remotely possible for some of the assertions
463  * regarding the unlinked set below to fail due to i/o error.  On a
464  * nondebug system, this will result in the space being leaked.
465  */
466 void
467 zfs_unlinked_add(znode_t *zp, dmu_tx_t *tx)
468 {
469 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
470 
471 	ASSERT(zp->z_unlinked);
472 	ASSERT(zp->z_links == 0);
473 
474 	VERIFY3U(0, ==,
475 	    zap_add_int(zfsvfs->z_os, zfsvfs->z_unlinkedobj, zp->z_id, tx));
476 }
477 
478 /*
479  * Clean up any znodes that had no links when we either crashed or
480  * (force) umounted the file system.
481  */
482 void
483 zfs_unlinked_drain(zfsvfs_t *zfsvfs)
484 {
485 	zap_cursor_t	zc;
486 	zap_attribute_t zap;
487 	dmu_object_info_t doi;
488 	znode_t		*zp;
489 	int		error;
490 
491 	/*
492 	 * Interate over the contents of the unlinked set.
493 	 */
494 	for (zap_cursor_init(&zc, zfsvfs->z_os, zfsvfs->z_unlinkedobj);
495 	    zap_cursor_retrieve(&zc, &zap) == 0;
496 	    zap_cursor_advance(&zc)) {
497 
498 		/*
499 		 * See what kind of object we have in list
500 		 */
501 
502 		error = dmu_object_info(zfsvfs->z_os,
503 		    zap.za_first_integer, &doi);
504 		if (error != 0)
505 			continue;
506 
507 		ASSERT((doi.doi_type == DMU_OT_PLAIN_FILE_CONTENTS) ||
508 		    (doi.doi_type == DMU_OT_DIRECTORY_CONTENTS));
509 		/*
510 		 * We need to re-mark these list entries for deletion,
511 		 * so we pull them back into core and set zp->z_unlinked.
512 		 */
513 		error = zfs_zget(zfsvfs, zap.za_first_integer, &zp);
514 
515 		/*
516 		 * We may pick up znodes that are already marked for deletion.
517 		 * This could happen during the purge of an extended attribute
518 		 * directory.  All we need to do is skip over them, since they
519 		 * are already in the system marked z_unlinked.
520 		 */
521 		if (error != 0)
522 			continue;
523 
524 		zp->z_unlinked = B_TRUE;
525 		VN_RELE(ZTOV(zp));
526 	}
527 	zap_cursor_fini(&zc);
528 }
529 
530 /*
531  * Delete the entire contents of a directory.  Return a count
532  * of the number of entries that could not be deleted. If we encounter
533  * an error, return a count of at least one so that the directory stays
534  * in the unlinked set.
535  *
536  * NOTE: this function assumes that the directory is inactive,
537  *	so there is no need to lock its entries before deletion.
538  *	Also, it assumes the directory contents is *only* regular
539  *	files.
540  */
541 static int
542 zfs_purgedir(znode_t *dzp)
543 {
544 	zap_cursor_t	zc;
545 	zap_attribute_t	zap;
546 	znode_t		*xzp;
547 	dmu_tx_t	*tx;
548 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
549 	zfs_dirlock_t	dl;
550 	int skipped = 0;
551 	int error;
552 
553 	for (zap_cursor_init(&zc, zfsvfs->z_os, dzp->z_id);
554 	    (error = zap_cursor_retrieve(&zc, &zap)) == 0;
555 	    zap_cursor_advance(&zc)) {
556 		error = zfs_zget(zfsvfs,
557 		    ZFS_DIRENT_OBJ(zap.za_first_integer), &xzp);
558 		if (error) {
559 			skipped += 1;
560 			continue;
561 		}
562 
563 		ASSERT((ZTOV(xzp)->v_type == VREG) ||
564 		    (ZTOV(xzp)->v_type == VLNK));
565 
566 		tx = dmu_tx_create(zfsvfs->z_os);
567 		dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
568 		dmu_tx_hold_zap(tx, dzp->z_id, FALSE, zap.za_name);
569 		dmu_tx_hold_sa(tx, xzp->z_sa_hdl, B_FALSE);
570 		dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
571 		/* Is this really needed ? */
572 		zfs_sa_upgrade_txholds(tx, xzp);
573 		dmu_tx_mark_netfree(tx);
574 		error = dmu_tx_assign(tx, TXG_WAIT);
575 		if (error) {
576 			dmu_tx_abort(tx);
577 			VN_RELE(ZTOV(xzp));
578 			skipped += 1;
579 			continue;
580 		}
581 		bzero(&dl, sizeof (dl));
582 		dl.dl_dzp = dzp;
583 		dl.dl_name = zap.za_name;
584 
585 		error = zfs_link_destroy(&dl, xzp, tx, 0, NULL);
586 		if (error)
587 			skipped += 1;
588 		dmu_tx_commit(tx);
589 
590 		VN_RELE(ZTOV(xzp));
591 	}
592 	zap_cursor_fini(&zc);
593 	if (error != ENOENT)
594 		skipped += 1;
595 	return (skipped);
596 }
597 
598 void
599 zfs_rmnode(znode_t *zp)
600 {
601 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
602 	objset_t	*os = zfsvfs->z_os;
603 	znode_t		*xzp = NULL;
604 	dmu_tx_t	*tx;
605 	uint64_t	acl_obj;
606 	uint64_t	xattr_obj;
607 	int		error;
608 
609 	ASSERT(zp->z_links == 0);
610 	ASSERT(ZTOV(zp)->v_count == 0);
611 
612 	/*
613 	 * If this is an attribute directory, purge its contents.
614 	 */
615 	if (ZTOV(zp)->v_type == VDIR && (zp->z_pflags & ZFS_XATTR)) {
616 		if (zfs_purgedir(zp) != 0) {
617 			/*
618 			 * Not enough space to delete some xattrs.
619 			 * Leave it in the unlinked set.
620 			 */
621 			zfs_znode_dmu_fini(zp);
622 			zfs_znode_free(zp);
623 			return;
624 		}
625 	} else {
626 		/*
627 		 * Free up all the data in the file.  We don't do this for
628 		 * XATTR directories because we need truncate and remove to be
629 		 * in the same tx, like in zfs_znode_delete(). Otherwise, if
630 		 * we crash here we'll end up with an inconsistent truncated
631 		 * zap object in the delete queue.  Note a truncated file is
632 		 * harmless since it only contains user data.
633 		 */
634 		error = dmu_free_long_range(os, zp->z_id, 0, DMU_OBJECT_END);
635 		if (error) {
636 			/*
637 			 * Not enough space or we were interrupted by unmount.
638 			 * Leave the file in the unlinked set.
639 			 */
640 			zfs_znode_dmu_fini(zp);
641 			zfs_znode_free(zp);
642 			return;
643 		}
644 	}
645 
646 	/*
647 	 * If the file has extended attributes, we're going to unlink
648 	 * the xattr dir.
649 	 */
650 	error = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
651 	    &xattr_obj, sizeof (xattr_obj));
652 	if (error == 0 && xattr_obj) {
653 		error = zfs_zget(zfsvfs, xattr_obj, &xzp);
654 		ASSERT(error == 0);
655 	}
656 
657 	acl_obj = zfs_external_acl(zp);
658 
659 	/*
660 	 * Set up the final transaction.
661 	 */
662 	tx = dmu_tx_create(os);
663 	dmu_tx_hold_free(tx, zp->z_id, 0, DMU_OBJECT_END);
664 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
665 	if (xzp) {
666 		dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, TRUE, NULL);
667 		dmu_tx_hold_sa(tx, xzp->z_sa_hdl, B_FALSE);
668 	}
669 	if (acl_obj)
670 		dmu_tx_hold_free(tx, acl_obj, 0, DMU_OBJECT_END);
671 
672 	zfs_sa_upgrade_txholds(tx, zp);
673 	error = dmu_tx_assign(tx, TXG_WAIT);
674 	if (error) {
675 		/*
676 		 * Not enough space to delete the file.  Leave it in the
677 		 * unlinked set, leaking it until the fs is remounted (at
678 		 * which point we'll call zfs_unlinked_drain() to process it).
679 		 */
680 		dmu_tx_abort(tx);
681 		zfs_znode_dmu_fini(zp);
682 		zfs_znode_free(zp);
683 		goto out;
684 	}
685 
686 	if (xzp) {
687 		ASSERT(error == 0);
688 		mutex_enter(&xzp->z_lock);
689 		xzp->z_unlinked = B_TRUE;	/* mark xzp for deletion */
690 		xzp->z_links = 0;	/* no more links to it */
691 		VERIFY(0 == sa_update(xzp->z_sa_hdl, SA_ZPL_LINKS(zfsvfs),
692 		    &xzp->z_links, sizeof (xzp->z_links), tx));
693 		mutex_exit(&xzp->z_lock);
694 		zfs_unlinked_add(xzp, tx);
695 	}
696 
697 	/* Remove this znode from the unlinked set */
698 	VERIFY3U(0, ==,
699 	    zap_remove_int(zfsvfs->z_os, zfsvfs->z_unlinkedobj, zp->z_id, tx));
700 
701 	zfs_znode_delete(zp, tx);
702 
703 	dmu_tx_commit(tx);
704 out:
705 	if (xzp)
706 		VN_RELE(ZTOV(xzp));
707 }
708 
709 static uint64_t
710 zfs_dirent(znode_t *zp, uint64_t mode)
711 {
712 	uint64_t de = zp->z_id;
713 
714 	if (zp->z_zfsvfs->z_version >= ZPL_VERSION_DIRENT_TYPE)
715 		de |= IFTODT(mode) << 60;
716 	return (de);
717 }
718 
719 /*
720  * Link zp into dl.  Can only fail if zp has been unlinked.
721  */
722 int
723 zfs_link_create(zfs_dirlock_t *dl, znode_t *zp, dmu_tx_t *tx, int flag)
724 {
725 	znode_t *dzp = dl->dl_dzp;
726 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
727 	vnode_t *vp = ZTOV(zp);
728 	uint64_t value;
729 	int zp_is_dir = (vp->v_type == VDIR);
730 	sa_bulk_attr_t bulk[5];
731 	uint64_t mtime[2], ctime[2];
732 	int count = 0;
733 	int error;
734 
735 	mutex_enter(&zp->z_lock);
736 
737 	if (!(flag & ZRENAMING)) {
738 		if (zp->z_unlinked) {	/* no new links to unlinked zp */
739 			ASSERT(!(flag & (ZNEW | ZEXISTS)));
740 			mutex_exit(&zp->z_lock);
741 			return (SET_ERROR(ENOENT));
742 		}
743 		zp->z_links++;
744 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs), NULL,
745 		    &zp->z_links, sizeof (zp->z_links));
746 
747 	}
748 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_PARENT(zfsvfs), NULL,
749 	    &dzp->z_id, sizeof (dzp->z_id));
750 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
751 	    &zp->z_pflags, sizeof (zp->z_pflags));
752 
753 	if (!(flag & ZNEW)) {
754 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
755 		    ctime, sizeof (ctime));
756 		zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime,
757 		    ctime, B_TRUE);
758 	}
759 	error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
760 	ASSERT(error == 0);
761 
762 	mutex_exit(&zp->z_lock);
763 
764 	mutex_enter(&dzp->z_lock);
765 	dzp->z_size++;
766 	dzp->z_links += zp_is_dir;
767 	count = 0;
768 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
769 	    &dzp->z_size, sizeof (dzp->z_size));
770 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs), NULL,
771 	    &dzp->z_links, sizeof (dzp->z_links));
772 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
773 	    mtime, sizeof (mtime));
774 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
775 	    ctime, sizeof (ctime));
776 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
777 	    &dzp->z_pflags, sizeof (dzp->z_pflags));
778 	zfs_tstamp_update_setup(dzp, CONTENT_MODIFIED, mtime, ctime, B_TRUE);
779 	error = sa_bulk_update(dzp->z_sa_hdl, bulk, count, tx);
780 	ASSERT(error == 0);
781 	mutex_exit(&dzp->z_lock);
782 
783 	value = zfs_dirent(zp, zp->z_mode);
784 	error = zap_add(zp->z_zfsvfs->z_os, dzp->z_id, dl->dl_name,
785 	    8, 1, &value, tx);
786 	ASSERT(error == 0);
787 
788 	dnlc_update(ZTOV(dzp), dl->dl_name, vp);
789 
790 	return (0);
791 }
792 
793 /*
794  * The match type in the code for this function should conform to:
795  *
796  * ------------------------------------------------------------------------
797  * fs type  | z_norm      | lookup type | match type
798  * ---------|-------------|-------------|----------------------------------
799  * CS !norm | 0           |           0 | 0 (exact)
800  * CS  norm | formX       |           0 | MT_NORMALIZE
801  * CI !norm | upper       |   !ZCIEXACT | MT_NORMALIZE
802  * CI !norm | upper       |    ZCIEXACT | MT_NORMALIZE | MT_MATCH_CASE
803  * CI  norm | upper|formX |   !ZCIEXACT | MT_NORMALIZE
804  * CI  norm | upper|formX |    ZCIEXACT | MT_NORMALIZE | MT_MATCH_CASE
805  * CM !norm | upper       |    !ZCILOOK | MT_NORMALIZE | MT_MATCH_CASE
806  * CM !norm | upper       |     ZCILOOK | MT_NORMALIZE
807  * CM  norm | upper|formX |    !ZCILOOK | MT_NORMALIZE | MT_MATCH_CASE
808  * CM  norm | upper|formX |     ZCILOOK | MT_NORMALIZE
809  *
810  * Abbreviations:
811  *    CS = Case Sensitive, CI = Case Insensitive, CM = Case Mixed
812  *    upper = case folding set by fs type on creation (U8_TEXTPREP_TOUPPER)
813  *    formX = unicode normalization form set on fs creation
814  */
815 static int
816 zfs_dropname(zfs_dirlock_t *dl, znode_t *zp, znode_t *dzp, dmu_tx_t *tx,
817     int flag)
818 {
819 	int error;
820 
821 	if (zp->z_zfsvfs->z_norm) {
822 		matchtype_t mt = MT_NORMALIZE;
823 
824 		if ((zp->z_zfsvfs->z_case == ZFS_CASE_INSENSITIVE &&
825 		    (flag & ZCIEXACT)) ||
826 		    (zp->z_zfsvfs->z_case == ZFS_CASE_MIXED &&
827 		    !(flag & ZCILOOK))) {
828 			mt |= MT_MATCH_CASE;
829 		}
830 
831 		error = zap_remove_norm(zp->z_zfsvfs->z_os, dzp->z_id,
832 		    dl->dl_name, mt, tx);
833 	} else {
834 		error = zap_remove(zp->z_zfsvfs->z_os, dzp->z_id, dl->dl_name,
835 		    tx);
836 	}
837 
838 	return (error);
839 }
840 
841 /*
842  * Unlink zp from dl, and mark zp for deletion if this was the last link.
843  * Can fail if zp is a mount point (EBUSY) or a non-empty directory (EEXIST).
844  * If 'unlinkedp' is NULL, we put unlinked znodes on the unlinked list.
845  * If it's non-NULL, we use it to indicate whether the znode needs deletion,
846  * and it's the caller's job to do it.
847  */
848 int
849 zfs_link_destroy(zfs_dirlock_t *dl, znode_t *zp, dmu_tx_t *tx, int flag,
850     boolean_t *unlinkedp)
851 {
852 	znode_t *dzp = dl->dl_dzp;
853 	zfsvfs_t *zfsvfs = dzp->z_zfsvfs;
854 	vnode_t *vp = ZTOV(zp);
855 	int zp_is_dir = (vp->v_type == VDIR);
856 	boolean_t unlinked = B_FALSE;
857 	sa_bulk_attr_t bulk[5];
858 	uint64_t mtime[2], ctime[2];
859 	int count = 0;
860 	int error;
861 
862 	dnlc_remove(ZTOV(dzp), dl->dl_name);
863 
864 	if (!(flag & ZRENAMING)) {
865 		if (vn_vfswlock(vp))		/* prevent new mounts on zp */
866 			return (SET_ERROR(EBUSY));
867 
868 		if (vn_ismntpt(vp)) {		/* don't remove mount point */
869 			vn_vfsunlock(vp);
870 			return (SET_ERROR(EBUSY));
871 		}
872 
873 		mutex_enter(&zp->z_lock);
874 
875 		if (zp_is_dir && !zfs_dirempty(zp)) {
876 			mutex_exit(&zp->z_lock);
877 			vn_vfsunlock(vp);
878 			return (SET_ERROR(EEXIST));
879 		}
880 
881 		/*
882 		 * If we get here, we are going to try to remove the object.
883 		 * First try removing the name from the directory; if that
884 		 * fails, return the error.
885 		 */
886 		error = zfs_dropname(dl, zp, dzp, tx, flag);
887 		if (error != 0) {
888 			mutex_exit(&zp->z_lock);
889 			vn_vfsunlock(vp);
890 			return (error);
891 		}
892 
893 		if (zp->z_links <= zp_is_dir) {
894 			zfs_panic_recover("zfs: link count on %s is %u, "
895 			    "should be at least %u",
896 			    zp->z_vnode->v_path ? zp->z_vnode->v_path :
897 			    "<unknown>", (int)zp->z_links,
898 			    zp_is_dir + 1);
899 			zp->z_links = zp_is_dir + 1;
900 		}
901 		if (--zp->z_links == zp_is_dir) {
902 			zp->z_unlinked = B_TRUE;
903 			zp->z_links = 0;
904 			unlinked = B_TRUE;
905 		} else {
906 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs),
907 			    NULL, &ctime, sizeof (ctime));
908 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs),
909 			    NULL, &zp->z_pflags, sizeof (zp->z_pflags));
910 			zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime, ctime,
911 			    B_TRUE);
912 		}
913 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs),
914 		    NULL, &zp->z_links, sizeof (zp->z_links));
915 		error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
916 		count = 0;
917 		ASSERT(error == 0);
918 		mutex_exit(&zp->z_lock);
919 		vn_vfsunlock(vp);
920 	} else {
921 		error = zfs_dropname(dl, zp, dzp, tx, flag);
922 		if (error != 0)
923 			return (error);
924 	}
925 
926 	mutex_enter(&dzp->z_lock);
927 	dzp->z_size--;		/* one dirent removed */
928 	dzp->z_links -= zp_is_dir;	/* ".." link from zp */
929 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs),
930 	    NULL, &dzp->z_links, sizeof (dzp->z_links));
931 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs),
932 	    NULL, &dzp->z_size, sizeof (dzp->z_size));
933 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs),
934 	    NULL, ctime, sizeof (ctime));
935 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs),
936 	    NULL, mtime, sizeof (mtime));
937 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs),
938 	    NULL, &dzp->z_pflags, sizeof (dzp->z_pflags));
939 	zfs_tstamp_update_setup(dzp, CONTENT_MODIFIED, mtime, ctime, B_TRUE);
940 	error = sa_bulk_update(dzp->z_sa_hdl, bulk, count, tx);
941 	ASSERT(error == 0);
942 	mutex_exit(&dzp->z_lock);
943 
944 	if (unlinkedp != NULL)
945 		*unlinkedp = unlinked;
946 	else if (unlinked)
947 		zfs_unlinked_add(zp, tx);
948 
949 	return (0);
950 }
951 
952 /*
953  * Indicate whether the directory is empty.  Works with or without z_lock
954  * held, but can only be consider a hint in the latter case.  Returns true
955  * if only "." and ".." remain and there's no work in progress.
956  */
957 boolean_t
958 zfs_dirempty(znode_t *dzp)
959 {
960 	return (dzp->z_size == 2 && dzp->z_dirlocks == 0);
961 }
962 
963 int
964 zfs_make_xattrdir(znode_t *zp, vattr_t *vap, vnode_t **xvpp, cred_t *cr)
965 {
966 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
967 	znode_t *xzp;
968 	dmu_tx_t *tx;
969 	int error;
970 	zfs_acl_ids_t acl_ids;
971 	boolean_t fuid_dirtied;
972 	uint64_t parent;
973 
974 	*xvpp = NULL;
975 
976 	if (error = zfs_zaccess(zp, ACE_WRITE_NAMED_ATTRS, 0, B_FALSE, cr))
977 		return (error);
978 
979 	if ((error = zfs_acl_ids_create(zp, IS_XATTR, vap, cr, NULL,
980 	    &acl_ids)) != 0)
981 		return (error);
982 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids)) {
983 		zfs_acl_ids_free(&acl_ids);
984 		return (SET_ERROR(EDQUOT));
985 	}
986 
987 	tx = dmu_tx_create(zfsvfs->z_os);
988 	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
989 	    ZFS_SA_BASE_ATTR_SIZE);
990 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
991 	dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
992 	fuid_dirtied = zfsvfs->z_fuid_dirty;
993 	if (fuid_dirtied)
994 		zfs_fuid_txhold(zfsvfs, tx);
995 	error = dmu_tx_assign(tx, TXG_WAIT);
996 	if (error) {
997 		zfs_acl_ids_free(&acl_ids);
998 		dmu_tx_abort(tx);
999 		return (error);
1000 	}
1001 	zfs_mknode(zp, vap, tx, cr, IS_XATTR, &xzp, &acl_ids);
1002 
1003 	if (fuid_dirtied)
1004 		zfs_fuid_sync(zfsvfs, tx);
1005 
1006 #ifdef DEBUG
1007 	error = sa_lookup(xzp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
1008 	    &parent, sizeof (parent));
1009 	ASSERT(error == 0 && parent == zp->z_id);
1010 #endif
1011 
1012 	VERIFY(0 == sa_update(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs), &xzp->z_id,
1013 	    sizeof (xzp->z_id), tx));
1014 
1015 	(void) zfs_log_create(zfsvfs->z_log, tx, TX_MKXATTR, zp,
1016 	    xzp, "", NULL, acl_ids.z_fuidp, vap);
1017 
1018 	zfs_acl_ids_free(&acl_ids);
1019 	dmu_tx_commit(tx);
1020 
1021 	*xvpp = ZTOV(xzp);
1022 
1023 	return (0);
1024 }
1025 
1026 /*
1027  * Return a znode for the extended attribute directory for zp.
1028  * ** If the directory does not already exist, it is created **
1029  *
1030  *	IN:	zp	- znode to obtain attribute directory from
1031  *		cr	- credentials of caller
1032  *		flags	- flags from the VOP_LOOKUP call
1033  *
1034  *	OUT:	xzpp	- pointer to extended attribute znode
1035  *
1036  *	RETURN:	0 on success
1037  *		error number on failure
1038  */
1039 int
1040 zfs_get_xattrdir(znode_t *zp, vnode_t **xvpp, cred_t *cr, int flags)
1041 {
1042 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
1043 	znode_t		*xzp;
1044 	zfs_dirlock_t	*dl;
1045 	vattr_t		va;
1046 	int		error;
1047 top:
1048 	error = zfs_dirent_lock(&dl, zp, "", &xzp, ZXATTR, NULL, NULL);
1049 	if (error)
1050 		return (error);
1051 
1052 	if (xzp != NULL) {
1053 		*xvpp = ZTOV(xzp);
1054 		zfs_dirent_unlock(dl);
1055 		return (0);
1056 	}
1057 
1058 
1059 	if (!(flags & CREATE_XATTR_DIR)) {
1060 		zfs_dirent_unlock(dl);
1061 		return (SET_ERROR(ENOENT));
1062 	}
1063 
1064 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
1065 		zfs_dirent_unlock(dl);
1066 		return (SET_ERROR(EROFS));
1067 	}
1068 
1069 	/*
1070 	 * The ability to 'create' files in an attribute
1071 	 * directory comes from the write_xattr permission on the base file.
1072 	 *
1073 	 * The ability to 'search' an attribute directory requires
1074 	 * read_xattr permission on the base file.
1075 	 *
1076 	 * Once in a directory the ability to read/write attributes
1077 	 * is controlled by the permissions on the attribute file.
1078 	 */
1079 	va.va_mask = AT_TYPE | AT_MODE | AT_UID | AT_GID;
1080 	va.va_type = VDIR;
1081 	va.va_mode = S_IFDIR | S_ISVTX | 0777;
1082 	zfs_fuid_map_ids(zp, cr, &va.va_uid, &va.va_gid);
1083 
1084 	error = zfs_make_xattrdir(zp, &va, xvpp, cr);
1085 	zfs_dirent_unlock(dl);
1086 
1087 	if (error == ERESTART) {
1088 		/* NB: we already did dmu_tx_wait() if necessary */
1089 		goto top;
1090 	}
1091 
1092 	return (error);
1093 }
1094 
1095 /*
1096  * Decide whether it is okay to remove within a sticky directory.
1097  *
1098  * In sticky directories, write access is not sufficient;
1099  * you can remove entries from a directory only if:
1100  *
1101  *	you own the directory,
1102  *	you own the entry,
1103  *	the entry is a plain file and you have write access,
1104  *	or you are privileged (checked in secpolicy...).
1105  *
1106  * The function returns 0 if remove access is granted.
1107  */
1108 int
1109 zfs_sticky_remove_access(znode_t *zdp, znode_t *zp, cred_t *cr)
1110 {
1111 	uid_t  		uid;
1112 	uid_t		downer;
1113 	uid_t		fowner;
1114 	zfsvfs_t	*zfsvfs = zdp->z_zfsvfs;
1115 
1116 	if (zdp->z_zfsvfs->z_replay)
1117 		return (0);
1118 
1119 	if ((zdp->z_mode & S_ISVTX) == 0)
1120 		return (0);
1121 
1122 	downer = zfs_fuid_map_id(zfsvfs, zdp->z_uid, cr, ZFS_OWNER);
1123 	fowner = zfs_fuid_map_id(zfsvfs, zp->z_uid, cr, ZFS_OWNER);
1124 
1125 	if ((uid = crgetuid(cr)) == downer || uid == fowner ||
1126 	    (ZTOV(zp)->v_type == VREG &&
1127 	    zfs_zaccess(zp, ACE_WRITE_DATA, 0, B_FALSE, cr) == 0))
1128 		return (0);
1129 	else
1130 		return (secpolicy_vnode_remove(cr));
1131 }
1132