xref: /freebsd-src/sys/contrib/openzfs/module/os/freebsd/zfs/zfs_dir.c (revision c14e17a49cdd72c8c05d12fbec631c409b14b9cb)
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/extdirent.h>
37 #include <sys/file.h>
38 #include <sys/kmem.h>
39 #include <sys/uio.h>
40 #include <sys/cmn_err.h>
41 #include <sys/errno.h>
42 #include <sys/stat.h>
43 #include <sys/unistd.h>
44 #include <sys/sunddi.h>
45 #include <sys/random.h>
46 #include <sys/policy.h>
47 #include <sys/condvar.h>
48 #include <sys/callb.h>
49 #include <sys/smp.h>
50 #include <sys/zfs_dir.h>
51 #include <sys/zfs_acl.h>
52 #include <sys/fs/zfs.h>
53 #include <sys/zap.h>
54 #include <sys/dmu.h>
55 #include <sys/atomic.h>
56 #include <sys/zfs_ctldir.h>
57 #include <sys/zfs_fuid.h>
58 #include <sys/sa.h>
59 #include <sys/zfs_sa.h>
60 #include <sys/dmu_objset.h>
61 #include <sys/dsl_dir.h>
62 
63 #include <sys/ccompat.h>
64 
65 /*
66  * zfs_match_find() is used by zfs_dirent_lookup() to perform zap lookups
67  * of names after deciding which is the appropriate lookup interface.
68  */
69 static int
70 zfs_match_find(zfsvfs_t *zfsvfs, znode_t *dzp, const char *name,
71     matchtype_t mt, uint64_t *zoid)
72 {
73 	int error;
74 
75 	if (zfsvfs->z_norm) {
76 
77 		/*
78 		 * In the non-mixed case we only expect there would ever
79 		 * be one match, but we need to use the normalizing lookup.
80 		 */
81 		error = zap_lookup_norm(zfsvfs->z_os, dzp->z_id, name, 8, 1,
82 		    zoid, mt, NULL, 0, NULL);
83 	} else {
84 		error = zap_lookup(zfsvfs->z_os, dzp->z_id, name, 8, 1, zoid);
85 	}
86 	*zoid = ZFS_DIRENT_OBJ(*zoid);
87 
88 	return (error);
89 }
90 
91 /*
92  * Look up a directory entry under a locked vnode.
93  * dvp being locked gives us a guarantee that there are no concurrent
94  * modification of the directory and, thus, if a node can be found in
95  * the directory, then it must not be unlinked.
96  *
97  * Input arguments:
98  *	dzp	- znode for directory
99  *	name	- name of entry to lock
100  *	flag	- ZNEW: if the entry already exists, fail with EEXIST.
101  *		  ZEXISTS: if the entry does not exist, fail with ENOENT.
102  *		  ZXATTR: we want dzp's xattr directory
103  *
104  * Output arguments:
105  *	zpp	- pointer to the znode for the entry (NULL if there isn't one)
106  *
107  * Return value: 0 on success or errno on failure.
108  *
109  * NOTE: Always checks for, and rejects, '.' and '..'.
110  */
111 int
112 zfs_dirent_lookup(znode_t *dzp, const char *name, znode_t **zpp, int flag)
113 {
114 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
115 	znode_t		*zp;
116 	matchtype_t	mt = 0;
117 	uint64_t	zoid;
118 	int		error = 0;
119 
120 	if (zfsvfs->z_replay == B_FALSE)
121 		ASSERT_VOP_LOCKED(ZTOV(dzp), __func__);
122 
123 	*zpp = NULL;
124 
125 	/*
126 	 * Verify that we are not trying to lock '.', '..', or '.zfs'
127 	 */
128 	if (name[0] == '.' &&
129 	    (((name[1] == '\0') || (name[1] == '.' && name[2] == '\0')) ||
130 	    (zfs_has_ctldir(dzp) && strcmp(name, ZFS_CTLDIR_NAME) == 0)))
131 		return (SET_ERROR(EEXIST));
132 
133 	/*
134 	 * Case sensitivity and normalization preferences are set when
135 	 * the file system is created.  These are stored in the
136 	 * zfsvfs->z_case and zfsvfs->z_norm fields.  These choices
137 	 * affect how we perform zap lookups.
138 	 *
139 	 * When matching we may need to normalize & change case according to
140 	 * FS settings.
141 	 *
142 	 * Note that a normalized match is necessary for a case insensitive
143 	 * filesystem when the lookup request is not exact because normalization
144 	 * can fold case independent of normalizing code point sequences.
145 	 *
146 	 * See the table above zfs_dropname().
147 	 */
148 	if (zfsvfs->z_norm != 0) {
149 		mt = MT_NORMALIZE;
150 
151 		/*
152 		 * Determine if the match needs to honor the case specified in
153 		 * lookup, and if so keep track of that so that during
154 		 * normalization we don't fold case.
155 		 */
156 		if (zfsvfs->z_case == ZFS_CASE_MIXED) {
157 			mt |= MT_MATCH_CASE;
158 		}
159 	}
160 
161 	/*
162 	 * Only look in or update the DNLC if we are looking for the
163 	 * name on a file system that does not require normalization
164 	 * or case folding.  We can also look there if we happen to be
165 	 * on a non-normalizing, mixed sensitivity file system IF we
166 	 * are looking for the exact name.
167 	 *
168 	 * NB: we do not need to worry about this flag for ZFS_CASE_SENSITIVE
169 	 * because in that case MT_EXACT and MT_FIRST should produce exactly
170 	 * the same result.
171 	 */
172 
173 	if (dzp->z_unlinked && !(flag & ZXATTR))
174 		return (ENOENT);
175 	if (flag & ZXATTR) {
176 		error = sa_lookup(dzp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs), &zoid,
177 		    sizeof (zoid));
178 		if (error == 0)
179 			error = (zoid == 0 ? ENOENT : 0);
180 	} else {
181 		error = zfs_match_find(zfsvfs, dzp, name, mt, &zoid);
182 	}
183 	if (error) {
184 		if (error != ENOENT || (flag & ZEXISTS)) {
185 			return (error);
186 		}
187 	} else {
188 		if (flag & ZNEW) {
189 			return (SET_ERROR(EEXIST));
190 		}
191 		error = zfs_zget(zfsvfs, zoid, &zp);
192 		if (error)
193 			return (error);
194 		ASSERT(!zp->z_unlinked);
195 		*zpp = zp;
196 	}
197 
198 	return (0);
199 }
200 
201 static int
202 zfs_dd_lookup(znode_t *dzp, znode_t **zpp)
203 {
204 	zfsvfs_t *zfsvfs = dzp->z_zfsvfs;
205 	znode_t *zp;
206 	uint64_t parent;
207 	int error;
208 
209 #ifdef ZFS_DEBUG
210 	if (zfsvfs->z_replay == B_FALSE)
211 		ASSERT_VOP_LOCKED(ZTOV(dzp), __func__);
212 	ASSERT(ZFS_TEARDOWN_READ_HELD(zfsvfs));
213 #endif
214 	if (dzp->z_unlinked)
215 		return (ENOENT);
216 
217 	if ((error = sa_lookup(dzp->z_sa_hdl,
218 	    SA_ZPL_PARENT(zfsvfs), &parent, sizeof (parent))) != 0)
219 		return (error);
220 
221 	error = zfs_zget(zfsvfs, parent, &zp);
222 	if (error == 0)
223 		*zpp = zp;
224 	return (error);
225 }
226 
227 int
228 zfs_dirlook(znode_t *dzp, const char *name, znode_t **zpp)
229 {
230 	zfsvfs_t *zfsvfs __unused = dzp->z_zfsvfs;
231 	znode_t *zp = NULL;
232 	int error = 0;
233 
234 #ifdef ZFS_DEBUG
235 	if (zfsvfs->z_replay == B_FALSE)
236 		ASSERT_VOP_LOCKED(ZTOV(dzp), __func__);
237 	ASSERT(ZFS_TEARDOWN_READ_HELD(zfsvfs));
238 #endif
239 	if (dzp->z_unlinked)
240 		return (SET_ERROR(ENOENT));
241 
242 	if (name[0] == 0 || (name[0] == '.' && name[1] == 0)) {
243 		*zpp = dzp;
244 	} else if (name[0] == '.' && name[1] == '.' && name[2] == 0) {
245 		error = zfs_dd_lookup(dzp, &zp);
246 		if (error == 0)
247 			*zpp = zp;
248 	} else {
249 		error = zfs_dirent_lookup(dzp, name, &zp, ZEXISTS);
250 		if (error == 0) {
251 			dzp->z_zn_prefetch = B_TRUE; /* enable prefetching */
252 			*zpp = zp;
253 		}
254 	}
255 	return (error);
256 }
257 
258 /*
259  * unlinked Set (formerly known as the "delete queue") Error Handling
260  *
261  * When dealing with the unlinked set, we dmu_tx_hold_zap(), but we
262  * don't specify the name of the entry that we will be manipulating.  We
263  * also fib and say that we won't be adding any new entries to the
264  * unlinked set, even though we might (this is to lower the minimum file
265  * size that can be deleted in a full filesystem).  So on the small
266  * chance that the nlink list is using a fat zap (ie. has more than
267  * 2000 entries), we *may* not pre-read a block that's needed.
268  * Therefore it is remotely possible for some of the assertions
269  * regarding the unlinked set below to fail due to i/o error.  On a
270  * nondebug system, this will result in the space being leaked.
271  */
272 void
273 zfs_unlinked_add(znode_t *zp, dmu_tx_t *tx)
274 {
275 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
276 
277 	ASSERT(zp->z_unlinked);
278 	ASSERT(zp->z_links == 0);
279 
280 	VERIFY3U(0, ==,
281 	    zap_add_int(zfsvfs->z_os, zfsvfs->z_unlinkedobj, zp->z_id, tx));
282 
283 	dataset_kstats_update_nunlinks_kstat(&zfsvfs->z_kstat, 1);
284 }
285 
286 /*
287  * Clean up any znodes that had no links when we either crashed or
288  * (force) umounted the file system.
289  */
290 void
291 zfs_unlinked_drain(zfsvfs_t *zfsvfs)
292 {
293 	zap_cursor_t	zc;
294 	zap_attribute_t zap;
295 	dmu_object_info_t doi;
296 	znode_t		*zp;
297 	dmu_tx_t	*tx;
298 	int		error;
299 
300 	/*
301 	 * Iterate over the contents of the unlinked set.
302 	 */
303 	for (zap_cursor_init(&zc, zfsvfs->z_os, zfsvfs->z_unlinkedobj);
304 	    zap_cursor_retrieve(&zc, &zap) == 0;
305 	    zap_cursor_advance(&zc)) {
306 
307 		/*
308 		 * See what kind of object we have in list
309 		 */
310 
311 		error = dmu_object_info(zfsvfs->z_os,
312 		    zap.za_first_integer, &doi);
313 		if (error != 0)
314 			continue;
315 
316 		ASSERT((doi.doi_type == DMU_OT_PLAIN_FILE_CONTENTS) ||
317 		    (doi.doi_type == DMU_OT_DIRECTORY_CONTENTS));
318 		/*
319 		 * We need to re-mark these list entries for deletion,
320 		 * so we pull them back into core and set zp->z_unlinked.
321 		 */
322 		error = zfs_zget(zfsvfs, zap.za_first_integer, &zp);
323 
324 		/*
325 		 * We may pick up znodes that are already marked for deletion.
326 		 * This could happen during the purge of an extended attribute
327 		 * directory.  All we need to do is skip over them, since they
328 		 * are already in the system marked z_unlinked.
329 		 */
330 		if (error != 0)
331 			continue;
332 
333 		vn_lock(ZTOV(zp), LK_EXCLUSIVE | LK_RETRY);
334 
335 		/*
336 		 * Due to changes in zfs_rmnode we need to make sure the
337 		 * link count is set to zero here.
338 		 */
339 		if (zp->z_links != 0) {
340 			tx = dmu_tx_create(zfsvfs->z_os);
341 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
342 			error = dmu_tx_assign(tx, TXG_WAIT);
343 			if (error != 0) {
344 				dmu_tx_abort(tx);
345 				vput(ZTOV(zp));
346 				continue;
347 			}
348 			zp->z_links = 0;
349 			VERIFY0(sa_update(zp->z_sa_hdl, SA_ZPL_LINKS(zfsvfs),
350 			    &zp->z_links, sizeof (zp->z_links), tx));
351 			dmu_tx_commit(tx);
352 		}
353 
354 		zp->z_unlinked = B_TRUE;
355 		vput(ZTOV(zp));
356 	}
357 	zap_cursor_fini(&zc);
358 }
359 
360 /*
361  * Delete the entire contents of a directory.  Return a count
362  * of the number of entries that could not be deleted. If we encounter
363  * an error, return a count of at least one so that the directory stays
364  * in the unlinked set.
365  *
366  * NOTE: this function assumes that the directory is inactive,
367  *	so there is no need to lock its entries before deletion.
368  *	Also, it assumes the directory contents is *only* regular
369  *	files.
370  */
371 static int
372 zfs_purgedir(znode_t *dzp)
373 {
374 	zap_cursor_t	zc;
375 	zap_attribute_t	zap;
376 	znode_t		*xzp;
377 	dmu_tx_t	*tx;
378 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
379 	int skipped = 0;
380 	int error;
381 
382 	for (zap_cursor_init(&zc, zfsvfs->z_os, dzp->z_id);
383 	    (error = zap_cursor_retrieve(&zc, &zap)) == 0;
384 	    zap_cursor_advance(&zc)) {
385 		error = zfs_zget(zfsvfs,
386 		    ZFS_DIRENT_OBJ(zap.za_first_integer), &xzp);
387 		if (error) {
388 			skipped += 1;
389 			continue;
390 		}
391 
392 		vn_lock(ZTOV(xzp), LK_EXCLUSIVE | LK_RETRY);
393 		ASSERT((ZTOV(xzp)->v_type == VREG) ||
394 		    (ZTOV(xzp)->v_type == VLNK));
395 
396 		tx = dmu_tx_create(zfsvfs->z_os);
397 		dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
398 		dmu_tx_hold_zap(tx, dzp->z_id, FALSE, zap.za_name);
399 		dmu_tx_hold_sa(tx, xzp->z_sa_hdl, B_FALSE);
400 		dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
401 		/* Is this really needed ? */
402 		zfs_sa_upgrade_txholds(tx, xzp);
403 		dmu_tx_mark_netfree(tx);
404 		error = dmu_tx_assign(tx, TXG_WAIT);
405 		if (error) {
406 			dmu_tx_abort(tx);
407 			vput(ZTOV(xzp));
408 			skipped += 1;
409 			continue;
410 		}
411 
412 		error = zfs_link_destroy(dzp, zap.za_name, xzp, tx, 0, NULL);
413 		if (error)
414 			skipped += 1;
415 		dmu_tx_commit(tx);
416 
417 		vput(ZTOV(xzp));
418 	}
419 	zap_cursor_fini(&zc);
420 	if (error != ENOENT)
421 		skipped += 1;
422 	return (skipped);
423 }
424 
425 extern taskq_t *zfsvfs_taskq;
426 
427 void
428 zfs_rmnode(znode_t *zp)
429 {
430 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
431 	objset_t	*os = zfsvfs->z_os;
432 	dmu_tx_t	*tx;
433 	uint64_t	acl_obj;
434 	uint64_t	xattr_obj;
435 	uint64_t	count;
436 	int		error;
437 
438 	ASSERT(zp->z_links == 0);
439 	if (zfsvfs->z_replay == B_FALSE)
440 		ASSERT_VOP_ELOCKED(ZTOV(zp), __func__);
441 
442 	/*
443 	 * If this is an attribute directory, purge its contents.
444 	 */
445 	if (ZTOV(zp) != NULL && ZTOV(zp)->v_type == VDIR &&
446 	    (zp->z_pflags & ZFS_XATTR)) {
447 		if (zfs_purgedir(zp) != 0) {
448 			/*
449 			 * Not enough space to delete some xattrs.
450 			 * Leave it in the unlinked set.
451 			 */
452 			zfs_znode_dmu_fini(zp);
453 			zfs_znode_free(zp);
454 			return;
455 		}
456 	} else {
457 		/*
458 		 * Free up all the data in the file.  We don't do this for
459 		 * XATTR directories because we need truncate and remove to be
460 		 * in the same tx, like in zfs_znode_delete(). Otherwise, if
461 		 * we crash here we'll end up with an inconsistent truncated
462 		 * zap object in the delete queue.  Note a truncated file is
463 		 * harmless since it only contains user data.
464 		 */
465 		error = dmu_free_long_range(os, zp->z_id, 0, DMU_OBJECT_END);
466 		if (error) {
467 			/*
468 			 * Not enough space or we were interrupted by unmount.
469 			 * Leave the file in the unlinked set.
470 			 */
471 			zfs_znode_dmu_fini(zp);
472 			zfs_znode_free(zp);
473 			return;
474 		}
475 	}
476 
477 	/*
478 	 * If the file has extended attributes, we're going to unlink
479 	 * the xattr dir.
480 	 */
481 	error = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
482 	    &xattr_obj, sizeof (xattr_obj));
483 	if (error)
484 		xattr_obj = 0;
485 
486 	acl_obj = zfs_external_acl(zp);
487 
488 	/*
489 	 * Set up the final transaction.
490 	 */
491 	tx = dmu_tx_create(os);
492 	dmu_tx_hold_free(tx, zp->z_id, 0, DMU_OBJECT_END);
493 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
494 	if (xattr_obj)
495 		dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, TRUE, NULL);
496 	if (acl_obj)
497 		dmu_tx_hold_free(tx, acl_obj, 0, DMU_OBJECT_END);
498 
499 	zfs_sa_upgrade_txholds(tx, zp);
500 	error = dmu_tx_assign(tx, TXG_WAIT);
501 	if (error) {
502 		/*
503 		 * Not enough space to delete the file.  Leave it in the
504 		 * unlinked set, leaking it until the fs is remounted (at
505 		 * which point we'll call zfs_unlinked_drain() to process it).
506 		 */
507 		dmu_tx_abort(tx);
508 		zfs_znode_dmu_fini(zp);
509 		zfs_znode_free(zp);
510 		return;
511 	}
512 
513 	/*
514 	 * FreeBSD's implementation of zfs_zget requires a vnode to back it.
515 	 * This means that we could end up calling into getnewvnode while
516 	 * calling zfs_rmnode as a result of a prior call to getnewvnode
517 	 * trying to clear vnodes out of the cache. If this repeats we can
518 	 * recurse enough that we overflow our stack. To avoid this, we
519 	 * avoid calling zfs_zget on the xattr znode and instead simply add
520 	 * it to the unlinked set and schedule a call to zfs_unlinked_drain.
521 	 */
522 	if (xattr_obj) {
523 		/* Add extended attribute directory to the unlinked set. */
524 		VERIFY3U(0, ==,
525 		    zap_add_int(os, zfsvfs->z_unlinkedobj, xattr_obj, tx));
526 	}
527 
528 	mutex_enter(&os->os_dsl_dataset->ds_dir->dd_activity_lock);
529 
530 	/* Remove this znode from the unlinked set */
531 	VERIFY3U(0, ==,
532 	    zap_remove_int(os, zfsvfs->z_unlinkedobj, zp->z_id, tx));
533 
534 	if (zap_count(os, zfsvfs->z_unlinkedobj, &count) == 0 && count == 0) {
535 		cv_broadcast(&os->os_dsl_dataset->ds_dir->dd_activity_cv);
536 	}
537 
538 	mutex_exit(&os->os_dsl_dataset->ds_dir->dd_activity_lock);
539 
540 	dataset_kstats_update_nunlinked_kstat(&zfsvfs->z_kstat, 1);
541 
542 	zfs_znode_delete(zp, tx);
543 
544 	dmu_tx_commit(tx);
545 
546 	if (xattr_obj) {
547 		/*
548 		 * We're using the FreeBSD taskqueue API here instead of
549 		 * the Solaris taskq API since the FreeBSD API allows for a
550 		 * task to be enqueued multiple times but executed once.
551 		 */
552 		taskqueue_enqueue(zfsvfs_taskq->tq_queue,
553 		    &zfsvfs->z_unlinked_drain_task);
554 	}
555 }
556 
557 static uint64_t
558 zfs_dirent(znode_t *zp, uint64_t mode)
559 {
560 	uint64_t de = zp->z_id;
561 
562 	if (zp->z_zfsvfs->z_version >= ZPL_VERSION_DIRENT_TYPE)
563 		de |= IFTODT(mode) << 60;
564 	return (de);
565 }
566 
567 /*
568  * Link zp into dzp.  Can only fail if zp has been unlinked.
569  */
570 int
571 zfs_link_create(znode_t *dzp, const char *name, znode_t *zp, dmu_tx_t *tx,
572     int flag)
573 {
574 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
575 	vnode_t *vp = ZTOV(zp);
576 	uint64_t value;
577 	int zp_is_dir = (vp->v_type == VDIR);
578 	sa_bulk_attr_t bulk[5];
579 	uint64_t mtime[2], ctime[2];
580 	int count = 0;
581 	int error;
582 
583 	if (zfsvfs->z_replay == B_FALSE) {
584 		ASSERT_VOP_ELOCKED(ZTOV(dzp), __func__);
585 		ASSERT_VOP_ELOCKED(ZTOV(zp), __func__);
586 	}
587 	if (zp_is_dir) {
588 		if (dzp->z_links >= ZFS_LINK_MAX)
589 			return (SET_ERROR(EMLINK));
590 	}
591 	if (!(flag & ZRENAMING)) {
592 		if (zp->z_unlinked) {	/* no new links to unlinked zp */
593 			ASSERT(!(flag & (ZNEW | ZEXISTS)));
594 			return (SET_ERROR(ENOENT));
595 		}
596 		if (zp->z_links >= ZFS_LINK_MAX - zp_is_dir) {
597 			return (SET_ERROR(EMLINK));
598 		}
599 		zp->z_links++;
600 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs), NULL,
601 		    &zp->z_links, sizeof (zp->z_links));
602 
603 	} else {
604 		ASSERT(zp->z_unlinked == 0);
605 	}
606 	value = zfs_dirent(zp, zp->z_mode);
607 	error = zap_add(zp->z_zfsvfs->z_os, dzp->z_id, name,
608 	    8, 1, &value, tx);
609 
610 	/*
611 	 * zap_add could fail to add the entry if it exceeds the capacity of the
612 	 * leaf-block and zap_leaf_split() failed to help.
613 	 * The caller of this routine is responsible for failing the transaction
614 	 * which will rollback the SA updates done above.
615 	 */
616 	if (error != 0) {
617 		if (!(flag & ZRENAMING) && !(flag & ZNEW))
618 			zp->z_links--;
619 		return (error);
620 	}
621 
622 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_PARENT(zfsvfs), NULL,
623 	    &dzp->z_id, sizeof (dzp->z_id));
624 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
625 	    &zp->z_pflags, sizeof (zp->z_pflags));
626 
627 	if (!(flag & ZNEW)) {
628 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
629 		    ctime, sizeof (ctime));
630 		zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime,
631 		    ctime);
632 	}
633 	error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
634 	ASSERT0(error);
635 
636 	dzp->z_size++;
637 	dzp->z_links += zp_is_dir;
638 	count = 0;
639 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
640 	    &dzp->z_size, sizeof (dzp->z_size));
641 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs), NULL,
642 	    &dzp->z_links, sizeof (dzp->z_links));
643 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
644 	    mtime, sizeof (mtime));
645 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
646 	    ctime, sizeof (ctime));
647 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
648 	    &dzp->z_pflags, sizeof (dzp->z_pflags));
649 	zfs_tstamp_update_setup(dzp, CONTENT_MODIFIED, mtime, ctime);
650 	error = sa_bulk_update(dzp->z_sa_hdl, bulk, count, tx);
651 	ASSERT0(error);
652 	return (0);
653 }
654 
655 /*
656  * The match type in the code for this function should conform to:
657  *
658  * ------------------------------------------------------------------------
659  * fs type  | z_norm      | lookup type | match type
660  * ---------|-------------|-------------|----------------------------------
661  * CS !norm | 0           |           0 | 0 (exact)
662  * CS  norm | formX       |           0 | MT_NORMALIZE
663  * CI !norm | upper       |   !ZCIEXACT | MT_NORMALIZE
664  * CI !norm | upper       |    ZCIEXACT | MT_NORMALIZE | MT_MATCH_CASE
665  * CI  norm | upper|formX |   !ZCIEXACT | MT_NORMALIZE
666  * CI  norm | upper|formX |    ZCIEXACT | MT_NORMALIZE | MT_MATCH_CASE
667  * CM !norm | upper       |    !ZCILOOK | MT_NORMALIZE | MT_MATCH_CASE
668  * CM !norm | upper       |     ZCILOOK | MT_NORMALIZE
669  * CM  norm | upper|formX |    !ZCILOOK | MT_NORMALIZE | MT_MATCH_CASE
670  * CM  norm | upper|formX |     ZCILOOK | MT_NORMALIZE
671  *
672  * Abbreviations:
673  *    CS = Case Sensitive, CI = Case Insensitive, CM = Case Mixed
674  *    upper = case folding set by fs type on creation (U8_TEXTPREP_TOUPPER)
675  *    formX = unicode normalization form set on fs creation
676  */
677 static int
678 zfs_dropname(znode_t *dzp, const char *name, znode_t *zp, dmu_tx_t *tx,
679     int flag)
680 {
681 	int error;
682 
683 	if (zp->z_zfsvfs->z_norm) {
684 		matchtype_t mt = MT_NORMALIZE;
685 
686 		if (zp->z_zfsvfs->z_case == ZFS_CASE_MIXED) {
687 			mt |= MT_MATCH_CASE;
688 		}
689 
690 		error = zap_remove_norm(zp->z_zfsvfs->z_os, dzp->z_id,
691 		    name, mt, tx);
692 	} else {
693 		error = zap_remove(zp->z_zfsvfs->z_os, dzp->z_id, name, tx);
694 	}
695 
696 	return (error);
697 }
698 
699 /*
700  * Unlink zp from dzp, and mark zp for deletion if this was the last link.
701  * Can fail if zp is a mount point (EBUSY) or a non-empty directory (EEXIST).
702  * If 'unlinkedp' is NULL, we put unlinked znodes on the unlinked list.
703  * If it's non-NULL, we use it to indicate whether the znode needs deletion,
704  * and it's the caller's job to do it.
705  */
706 int
707 zfs_link_destroy(znode_t *dzp, const char *name, znode_t *zp, dmu_tx_t *tx,
708     int flag, boolean_t *unlinkedp)
709 {
710 	zfsvfs_t *zfsvfs = dzp->z_zfsvfs;
711 	vnode_t *vp = ZTOV(zp);
712 	int zp_is_dir = (vp->v_type == VDIR);
713 	boolean_t unlinked = B_FALSE;
714 	sa_bulk_attr_t bulk[5];
715 	uint64_t mtime[2], ctime[2];
716 	int count = 0;
717 	int error;
718 
719 	if (zfsvfs->z_replay == B_FALSE) {
720 		ASSERT_VOP_ELOCKED(ZTOV(dzp), __func__);
721 		ASSERT_VOP_ELOCKED(ZTOV(zp), __func__);
722 	}
723 	if (!(flag & ZRENAMING)) {
724 
725 		if (zp_is_dir && !zfs_dirempty(zp))
726 			return (SET_ERROR(ENOTEMPTY));
727 
728 		/*
729 		 * If we get here, we are going to try to remove the object.
730 		 * First try removing the name from the directory; if that
731 		 * fails, return the error.
732 		 */
733 		error = zfs_dropname(dzp, name, zp, tx, flag);
734 		if (error != 0) {
735 			return (error);
736 		}
737 
738 		if (zp->z_links <= zp_is_dir) {
739 			zfs_panic_recover("zfs: link count on vnode %p is %u, "
740 			    "should be at least %u", zp->z_vnode,
741 			    (int)zp->z_links,
742 			    zp_is_dir + 1);
743 			zp->z_links = zp_is_dir + 1;
744 		}
745 		if (--zp->z_links == zp_is_dir) {
746 			zp->z_unlinked = B_TRUE;
747 			zp->z_links = 0;
748 			unlinked = B_TRUE;
749 		} else {
750 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs),
751 			    NULL, &ctime, sizeof (ctime));
752 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs),
753 			    NULL, &zp->z_pflags, sizeof (zp->z_pflags));
754 			zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime,
755 			    ctime);
756 		}
757 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs),
758 		    NULL, &zp->z_links, sizeof (zp->z_links));
759 		error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
760 		count = 0;
761 		ASSERT0(error);
762 	} else {
763 		ASSERT(zp->z_unlinked == 0);
764 		error = zfs_dropname(dzp, name, zp, tx, flag);
765 		if (error != 0)
766 			return (error);
767 	}
768 
769 	dzp->z_size--;		/* one dirent removed */
770 	dzp->z_links -= zp_is_dir;	/* ".." link from zp */
771 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs),
772 	    NULL, &dzp->z_links, sizeof (dzp->z_links));
773 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs),
774 	    NULL, &dzp->z_size, sizeof (dzp->z_size));
775 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs),
776 	    NULL, ctime, sizeof (ctime));
777 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs),
778 	    NULL, mtime, sizeof (mtime));
779 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs),
780 	    NULL, &dzp->z_pflags, sizeof (dzp->z_pflags));
781 	zfs_tstamp_update_setup(dzp, CONTENT_MODIFIED, mtime, ctime);
782 	error = sa_bulk_update(dzp->z_sa_hdl, bulk, count, tx);
783 	ASSERT0(error);
784 
785 	if (unlinkedp != NULL)
786 		*unlinkedp = unlinked;
787 	else if (unlinked)
788 		zfs_unlinked_add(zp, tx);
789 
790 	return (0);
791 }
792 
793 /*
794  * Indicate whether the directory is empty.
795  */
796 boolean_t
797 zfs_dirempty(znode_t *dzp)
798 {
799 	return (dzp->z_size == 2);
800 }
801 
802 int
803 zfs_make_xattrdir(znode_t *zp, vattr_t *vap, znode_t **xvpp, cred_t *cr)
804 {
805 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
806 	znode_t *xzp;
807 	dmu_tx_t *tx;
808 	int error;
809 	zfs_acl_ids_t acl_ids;
810 	boolean_t fuid_dirtied;
811 	uint64_t parent __unused;
812 
813 	*xvpp = NULL;
814 
815 	if ((error = zfs_acl_ids_create(zp, IS_XATTR, vap, cr, NULL,
816 	    &acl_ids)) != 0)
817 		return (error);
818 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids, 0)) {
819 		zfs_acl_ids_free(&acl_ids);
820 		return (SET_ERROR(EDQUOT));
821 	}
822 
823 	getnewvnode_reserve_();
824 
825 	tx = dmu_tx_create(zfsvfs->z_os);
826 	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
827 	    ZFS_SA_BASE_ATTR_SIZE);
828 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
829 	dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
830 	fuid_dirtied = zfsvfs->z_fuid_dirty;
831 	if (fuid_dirtied)
832 		zfs_fuid_txhold(zfsvfs, tx);
833 	error = dmu_tx_assign(tx, TXG_WAIT);
834 	if (error) {
835 		zfs_acl_ids_free(&acl_ids);
836 		dmu_tx_abort(tx);
837 		getnewvnode_drop_reserve();
838 		return (error);
839 	}
840 	zfs_mknode(zp, vap, tx, cr, IS_XATTR, &xzp, &acl_ids);
841 
842 	if (fuid_dirtied)
843 		zfs_fuid_sync(zfsvfs, tx);
844 
845 #ifdef ZFS_DEBUG
846 	error = sa_lookup(xzp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
847 	    &parent, sizeof (parent));
848 	ASSERT(error == 0 && parent == zp->z_id);
849 #endif
850 
851 	VERIFY(0 == sa_update(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs), &xzp->z_id,
852 	    sizeof (xzp->z_id), tx));
853 
854 	(void) zfs_log_create(zfsvfs->z_log, tx, TX_MKXATTR, zp,
855 	    xzp, "", NULL, acl_ids.z_fuidp, vap);
856 
857 	zfs_acl_ids_free(&acl_ids);
858 	dmu_tx_commit(tx);
859 
860 	getnewvnode_drop_reserve();
861 
862 	*xvpp = xzp;
863 
864 	return (0);
865 }
866 
867 /*
868  * Return a znode for the extended attribute directory for zp.
869  * ** If the directory does not already exist, it is created **
870  *
871  *	IN:	zp	- znode to obtain attribute directory from
872  *		cr	- credentials of caller
873  *		flags	- flags from the VOP_LOOKUP call
874  *
875  *	OUT:	xzpp	- pointer to extended attribute znode
876  *
877  *	RETURN:	0 on success
878  *		error number on failure
879  */
880 int
881 zfs_get_xattrdir(znode_t *zp, znode_t **xzpp, cred_t *cr, int flags)
882 {
883 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
884 	znode_t		*xzp;
885 	vattr_t		va;
886 	int		error;
887 top:
888 	error = zfs_dirent_lookup(zp, "", &xzp, ZXATTR);
889 	if (error)
890 		return (error);
891 
892 	if (xzp != NULL) {
893 		*xzpp = xzp;
894 		return (0);
895 	}
896 
897 
898 	if (!(flags & CREATE_XATTR_DIR))
899 		return (SET_ERROR(ENOATTR));
900 
901 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
902 		return (SET_ERROR(EROFS));
903 	}
904 
905 	/*
906 	 * The ability to 'create' files in an attribute
907 	 * directory comes from the write_xattr permission on the base file.
908 	 *
909 	 * The ability to 'search' an attribute directory requires
910 	 * read_xattr permission on the base file.
911 	 *
912 	 * Once in a directory the ability to read/write attributes
913 	 * is controlled by the permissions on the attribute file.
914 	 */
915 	va.va_mask = AT_MODE | AT_UID | AT_GID;
916 	va.va_type = VDIR;
917 	va.va_mode = S_IFDIR | S_ISVTX | 0777;
918 	zfs_fuid_map_ids(zp, cr, &va.va_uid, &va.va_gid);
919 
920 	error = zfs_make_xattrdir(zp, &va, xzpp, cr);
921 
922 	if (error == ERESTART) {
923 		/* NB: we already did dmu_tx_wait() if necessary */
924 		goto top;
925 	}
926 	if (error == 0)
927 		VOP_UNLOCK1(ZTOV(*xzpp));
928 
929 	return (error);
930 }
931 
932 /*
933  * Decide whether it is okay to remove within a sticky directory.
934  *
935  * In sticky directories, write access is not sufficient;
936  * you can remove entries from a directory only if:
937  *
938  *	you own the directory,
939  *	you own the entry,
940  *	the entry is a plain file and you have write access,
941  *	or you are privileged (checked in secpolicy...).
942  *
943  * The function returns 0 if remove access is granted.
944  */
945 int
946 zfs_sticky_remove_access(znode_t *zdp, znode_t *zp, cred_t *cr)
947 {
948 	uid_t  		uid;
949 	uid_t		downer;
950 	uid_t		fowner;
951 	zfsvfs_t	*zfsvfs = zdp->z_zfsvfs;
952 
953 	if (zdp->z_zfsvfs->z_replay)
954 		return (0);
955 
956 	if ((zdp->z_mode & S_ISVTX) == 0)
957 		return (0);
958 
959 	downer = zfs_fuid_map_id(zfsvfs, zdp->z_uid, cr, ZFS_OWNER);
960 	fowner = zfs_fuid_map_id(zfsvfs, zp->z_uid, cr, ZFS_OWNER);
961 
962 	if ((uid = crgetuid(cr)) == downer || uid == fowner ||
963 	    (ZTOV(zp)->v_type == VREG &&
964 	    zfs_zaccess(zp, ACE_WRITE_DATA, 0, B_FALSE, cr) == 0))
965 		return (0);
966 	else
967 		return (secpolicy_vnode_remove(ZTOV(zp), cr));
968 }
969