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