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