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