xref: /freebsd/sys/contrib/openzfs/module/os/freebsd/zfs/zfs_dir.c (revision d0abb9a6399accc9053e2808052be00a6754ecef)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or https://opensource.org/licenses/CDDL-1.0.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*
24  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
25  * Copyright (c) 2013, 2016 by Delphix. All rights reserved.
26  * Copyright 2017 Nexenta Systems, Inc.
27  */
28 
29 #include <sys/types.h>
30 #include <sys/param.h>
31 #include <sys/time.h>
32 #include <sys/systm.h>
33 #include <sys/sysmacros.h>
34 #include <sys/resource.h>
35 #include <sys/vfs.h>
36 #include <sys/vnode.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
zfs_match_find(zfsvfs_t * zfsvfs,znode_t * dzp,const char * name,matchtype_t mt,uint64_t * zoid)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
zfs_dirent_lookup(znode_t * dzp,const char * name,znode_t ** zpp,int flag)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
zfs_dd_lookup(znode_t * dzp,znode_t ** zpp)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
zfs_dirlook(znode_t * dzp,const char * name,znode_t ** zpp)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
zfs_unlinked_add(znode_t * zp,dmu_tx_t * tx)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 	ASSERT0(zp->z_links);
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
zfs_unlinked_drain(zfsvfs_t * zfsvfs)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 	zap = zap_attribute_alloc();
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, DMU_TX_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 	zap_attribute_free(zap);
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
zfs_purgedir(znode_t * dzp)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 	zap = zap_attribute_alloc();
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, DMU_TX_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 	zap_attribute_free(zap);
421 	if (error != ENOENT)
422 		skipped += 1;
423 	return (skipped);
424 }
425 
426 extern taskq_t *zfsvfs_taskq;
427 
428 void
zfs_rmnode(znode_t * zp)429 zfs_rmnode(znode_t *zp)
430 {
431 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
432 	objset_t	*os = zfsvfs->z_os;
433 	dmu_tx_t	*tx;
434 	uint64_t	z_id = zp->z_id;
435 	uint64_t	acl_obj;
436 	uint64_t	xattr_obj;
437 	uint64_t	count;
438 	int		error;
439 
440 	ASSERT0(zp->z_links);
441 	if (zfsvfs->z_replay == B_FALSE)
442 		ASSERT_VOP_ELOCKED(ZTOV(zp), __func__);
443 
444 	/*
445 	 * If this is an attribute directory, purge its contents.
446 	 */
447 	if (ZTOV(zp) != NULL && ZTOV(zp)->v_type == VDIR &&
448 	    (zp->z_pflags & ZFS_XATTR)) {
449 		if (zfs_purgedir(zp) != 0) {
450 			/*
451 			 * Not enough space to delete some xattrs.
452 			 * Leave it in the unlinked set.
453 			 */
454 			ZFS_OBJ_HOLD_ENTER(zfsvfs, z_id);
455 			zfs_znode_dmu_fini(zp);
456 			zfs_znode_free(zp);
457 			ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
458 			return;
459 		}
460 	} else {
461 		/*
462 		 * Free up all the data in the file.  We don't do this for
463 		 * XATTR directories because we need truncate and remove to be
464 		 * in the same tx, like in zfs_znode_delete(). Otherwise, if
465 		 * we crash here we'll end up with an inconsistent truncated
466 		 * zap object in the delete queue.  Note a truncated file is
467 		 * harmless since it only contains user data.
468 		 */
469 		error = dmu_free_long_range(os, zp->z_id, 0, DMU_OBJECT_END);
470 		if (error) {
471 			/*
472 			 * Not enough space or we were interrupted by unmount.
473 			 * Leave the file in the unlinked set.
474 			 */
475 			ZFS_OBJ_HOLD_ENTER(zfsvfs, z_id);
476 			zfs_znode_dmu_fini(zp);
477 			zfs_znode_free(zp);
478 			ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
479 			return;
480 		}
481 	}
482 
483 	/*
484 	 * If the file has extended attributes, we're going to unlink
485 	 * the xattr dir.
486 	 */
487 	error = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
488 	    &xattr_obj, sizeof (xattr_obj));
489 	if (error)
490 		xattr_obj = 0;
491 
492 	acl_obj = zfs_external_acl(zp);
493 
494 	/*
495 	 * Set up the final transaction.
496 	 */
497 	tx = dmu_tx_create(os);
498 	dmu_tx_hold_free(tx, zp->z_id, 0, DMU_OBJECT_END);
499 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
500 	if (xattr_obj)
501 		dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, TRUE, NULL);
502 	if (acl_obj)
503 		dmu_tx_hold_free(tx, acl_obj, 0, DMU_OBJECT_END);
504 
505 	zfs_sa_upgrade_txholds(tx, zp);
506 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
507 	if (error) {
508 		/*
509 		 * Not enough space to delete the file.  Leave it in the
510 		 * unlinked set, leaking it until the fs is remounted (at
511 		 * which point we'll call zfs_unlinked_drain() to process it).
512 		 */
513 		dmu_tx_abort(tx);
514 		ZFS_OBJ_HOLD_ENTER(zfsvfs, z_id);
515 		zfs_znode_dmu_fini(zp);
516 		zfs_znode_free(zp);
517 		ZFS_OBJ_HOLD_EXIT(zfsvfs, z_id);
518 		return;
519 	}
520 
521 	/*
522 	 * FreeBSD's implementation of zfs_zget requires a vnode to back it.
523 	 * This means that we could end up calling into getnewvnode while
524 	 * calling zfs_rmnode as a result of a prior call to getnewvnode
525 	 * trying to clear vnodes out of the cache. If this repeats we can
526 	 * recurse enough that we overflow our stack. To avoid this, we
527 	 * avoid calling zfs_zget on the xattr znode and instead simply add
528 	 * it to the unlinked set and schedule a call to zfs_unlinked_drain.
529 	 */
530 	if (xattr_obj) {
531 		/* Add extended attribute directory to the unlinked set. */
532 		VERIFY3U(0, ==,
533 		    zap_add_int(os, zfsvfs->z_unlinkedobj, xattr_obj, tx));
534 	}
535 
536 	mutex_enter(&os->os_dsl_dataset->ds_dir->dd_activity_lock);
537 
538 	/* Remove this znode from the unlinked set */
539 	VERIFY3U(0, ==,
540 	    zap_remove_int(os, zfsvfs->z_unlinkedobj, zp->z_id, tx));
541 
542 	if (zap_count(os, zfsvfs->z_unlinkedobj, &count) == 0 && count == 0) {
543 		cv_broadcast(&os->os_dsl_dataset->ds_dir->dd_activity_cv);
544 	}
545 
546 	mutex_exit(&os->os_dsl_dataset->ds_dir->dd_activity_lock);
547 
548 	dataset_kstats_update_nunlinked_kstat(&zfsvfs->z_kstat, 1);
549 
550 	zfs_znode_delete(zp, tx);
551 	zfs_znode_free(zp);
552 
553 	dmu_tx_commit(tx);
554 
555 	if (xattr_obj) {
556 		/*
557 		 * We're using the FreeBSD taskqueue API here instead of
558 		 * the Solaris taskq API since the FreeBSD API allows for a
559 		 * task to be enqueued multiple times but executed once.
560 		 */
561 		taskqueue_enqueue(zfsvfs_taskq->tq_queue,
562 		    &zfsvfs->z_unlinked_drain_task);
563 	}
564 }
565 
566 static uint64_t
zfs_dirent(znode_t * zp,uint64_t mode)567 zfs_dirent(znode_t *zp, uint64_t mode)
568 {
569 	uint64_t de = zp->z_id;
570 
571 	if (zp->z_zfsvfs->z_version >= ZPL_VERSION_DIRENT_TYPE)
572 		de |= IFTODT(mode) << 60;
573 	return (de);
574 }
575 
576 /*
577  * Link zp into dzp.  Can only fail if zp has been unlinked.
578  */
579 int
zfs_link_create(znode_t * dzp,const char * name,znode_t * zp,dmu_tx_t * tx,int flag)580 zfs_link_create(znode_t *dzp, const char *name, znode_t *zp, dmu_tx_t *tx,
581     int flag)
582 {
583 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
584 	vnode_t *vp = ZTOV(zp);
585 	uint64_t value;
586 	int zp_is_dir = (vp->v_type == VDIR);
587 	sa_bulk_attr_t bulk[5];
588 	uint64_t mtime[2], ctime[2];
589 	int count = 0;
590 	int error;
591 
592 	if (zfsvfs->z_replay == B_FALSE) {
593 		ASSERT_VOP_ELOCKED(ZTOV(dzp), __func__);
594 		ASSERT_VOP_ELOCKED(ZTOV(zp), __func__);
595 	}
596 	if (zp_is_dir) {
597 		if (dzp->z_links >= ZFS_LINK_MAX)
598 			return (SET_ERROR(EMLINK));
599 	}
600 	if (!(flag & ZRENAMING)) {
601 		if (zp->z_unlinked) {	/* no new links to unlinked zp */
602 			ASSERT(!(flag & (ZNEW | ZEXISTS)));
603 			return (SET_ERROR(ENOENT));
604 		}
605 		if (zp->z_links >= ZFS_LINK_MAX - zp_is_dir) {
606 			return (SET_ERROR(EMLINK));
607 		}
608 		zp->z_links++;
609 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs), NULL,
610 		    &zp->z_links, sizeof (zp->z_links));
611 
612 	} else {
613 		ASSERT(!zp->z_unlinked);
614 	}
615 	value = zfs_dirent(zp, zp->z_mode);
616 	error = zap_add(zp->z_zfsvfs->z_os, dzp->z_id, name,
617 	    8, 1, &value, tx);
618 
619 	/*
620 	 * zap_add could fail to add the entry if it exceeds the capacity of the
621 	 * leaf-block and zap_leaf_split() failed to help.
622 	 * The caller of this routine is responsible for failing the transaction
623 	 * which will rollback the SA updates done above.
624 	 */
625 	if (error != 0) {
626 		if (!(flag & ZRENAMING) && !(flag & ZNEW))
627 			zp->z_links--;
628 		return (error);
629 	}
630 
631 	/*
632 	 * If we added a longname activate the SPA_FEATURE_LONGNAME.
633 	 */
634 	if (strlen(name) >= ZAP_MAXNAMELEN) {
635 		dsl_dataset_t *ds = dmu_objset_ds(zfsvfs->z_os);
636 		ds->ds_feature_activation[SPA_FEATURE_LONGNAME] =
637 		    (void *)B_TRUE;
638 	}
639 
640 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_PARENT(zfsvfs), NULL,
641 	    &dzp->z_id, sizeof (dzp->z_id));
642 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
643 	    &zp->z_pflags, sizeof (zp->z_pflags));
644 
645 	if (!(flag & ZNEW)) {
646 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
647 		    ctime, sizeof (ctime));
648 		zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime,
649 		    ctime);
650 	}
651 	error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
652 	ASSERT0(error);
653 
654 	dzp->z_size++;
655 	dzp->z_links += zp_is_dir;
656 	count = 0;
657 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
658 	    &dzp->z_size, sizeof (dzp->z_size));
659 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs), NULL,
660 	    &dzp->z_links, sizeof (dzp->z_links));
661 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
662 	    mtime, sizeof (mtime));
663 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
664 	    ctime, sizeof (ctime));
665 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
666 	    &dzp->z_pflags, sizeof (dzp->z_pflags));
667 	zfs_tstamp_update_setup(dzp, CONTENT_MODIFIED, mtime, ctime);
668 	error = sa_bulk_update(dzp->z_sa_hdl, bulk, count, tx);
669 	ASSERT0(error);
670 	return (0);
671 }
672 
673 /*
674  * The match type in the code for this function should conform to:
675  *
676  * ------------------------------------------------------------------------
677  * fs type  | z_norm      | lookup type | match type
678  * ---------|-------------|-------------|----------------------------------
679  * CS !norm | 0           |           0 | 0 (exact)
680  * CS  norm | formX       |           0 | MT_NORMALIZE
681  * CI !norm | upper       |   !ZCIEXACT | MT_NORMALIZE
682  * CI !norm | upper       |    ZCIEXACT | MT_NORMALIZE | MT_MATCH_CASE
683  * CI  norm | upper|formX |   !ZCIEXACT | MT_NORMALIZE
684  * CI  norm | upper|formX |    ZCIEXACT | MT_NORMALIZE | MT_MATCH_CASE
685  * CM !norm | upper       |    !ZCILOOK | MT_NORMALIZE | MT_MATCH_CASE
686  * CM !norm | upper       |     ZCILOOK | MT_NORMALIZE
687  * CM  norm | upper|formX |    !ZCILOOK | MT_NORMALIZE | MT_MATCH_CASE
688  * CM  norm | upper|formX |     ZCILOOK | MT_NORMALIZE
689  *
690  * Abbreviations:
691  *    CS = Case Sensitive, CI = Case Insensitive, CM = Case Mixed
692  *    upper = case folding set by fs type on creation (U8_TEXTPREP_TOUPPER)
693  *    formX = unicode normalization form set on fs creation
694  */
695 static int
zfs_dropname(znode_t * dzp,const char * name,znode_t * zp,dmu_tx_t * tx,int flag)696 zfs_dropname(znode_t *dzp, const char *name, znode_t *zp, dmu_tx_t *tx,
697     int flag)
698 {
699 	int error;
700 
701 	if (zp->z_zfsvfs->z_norm) {
702 		matchtype_t mt = MT_NORMALIZE;
703 
704 		if (zp->z_zfsvfs->z_case == ZFS_CASE_MIXED) {
705 			mt |= MT_MATCH_CASE;
706 		}
707 
708 		error = zap_remove_norm(zp->z_zfsvfs->z_os, dzp->z_id,
709 		    name, mt, tx);
710 	} else {
711 		error = zap_remove(zp->z_zfsvfs->z_os, dzp->z_id, name, tx);
712 	}
713 
714 	return (error);
715 }
716 
717 /*
718  * Unlink zp from dzp, and mark zp for deletion if this was the last link.
719  * Can fail if zp is a mount point (EBUSY) or a non-empty directory (EEXIST).
720  * If 'unlinkedp' is NULL, we put unlinked znodes on the unlinked list.
721  * If it's non-NULL, we use it to indicate whether the znode needs deletion,
722  * and it's the caller's job to do it.
723  */
724 int
zfs_link_destroy(znode_t * dzp,const char * name,znode_t * zp,dmu_tx_t * tx,int flag,boolean_t * unlinkedp)725 zfs_link_destroy(znode_t *dzp, const char *name, znode_t *zp, dmu_tx_t *tx,
726     int flag, boolean_t *unlinkedp)
727 {
728 	zfsvfs_t *zfsvfs = dzp->z_zfsvfs;
729 	vnode_t *vp = ZTOV(zp);
730 	int zp_is_dir = (vp->v_type == VDIR);
731 	boolean_t unlinked = B_FALSE;
732 	sa_bulk_attr_t bulk[5];
733 	uint64_t mtime[2], ctime[2];
734 	int count = 0;
735 	int error;
736 
737 	if (zfsvfs->z_replay == B_FALSE) {
738 		ASSERT_VOP_ELOCKED(ZTOV(dzp), __func__);
739 		ASSERT_VOP_ELOCKED(ZTOV(zp), __func__);
740 	}
741 	if (!(flag & ZRENAMING)) {
742 
743 		if (zp_is_dir && !zfs_dirempty(zp))
744 			return (SET_ERROR(ENOTEMPTY));
745 
746 		/*
747 		 * If we get here, we are going to try to remove the object.
748 		 * First try removing the name from the directory; if that
749 		 * fails, return the error.
750 		 */
751 		error = zfs_dropname(dzp, name, zp, tx, flag);
752 		if (error != 0) {
753 			return (error);
754 		}
755 
756 		if (zp->z_links <= zp_is_dir) {
757 			zfs_panic_recover("zfs: link count on vnode %p is %u, "
758 			    "should be at least %u", zp->z_vnode,
759 			    (int)zp->z_links,
760 			    zp_is_dir + 1);
761 			zp->z_links = zp_is_dir + 1;
762 		}
763 		if (--zp->z_links == zp_is_dir) {
764 			zp->z_unlinked = B_TRUE;
765 			zp->z_links = 0;
766 			unlinked = B_TRUE;
767 		} else {
768 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs),
769 			    NULL, &ctime, sizeof (ctime));
770 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs),
771 			    NULL, &zp->z_pflags, sizeof (zp->z_pflags));
772 			zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime,
773 			    ctime);
774 		}
775 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs),
776 		    NULL, &zp->z_links, sizeof (zp->z_links));
777 		error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
778 		count = 0;
779 		ASSERT0(error);
780 	} else {
781 		ASSERT(!zp->z_unlinked);
782 		error = zfs_dropname(dzp, name, zp, tx, flag);
783 		if (error != 0)
784 			return (error);
785 	}
786 
787 	dzp->z_size--;		/* one dirent removed */
788 	dzp->z_links -= zp_is_dir;	/* ".." link from zp */
789 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs),
790 	    NULL, &dzp->z_links, sizeof (dzp->z_links));
791 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs),
792 	    NULL, &dzp->z_size, sizeof (dzp->z_size));
793 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs),
794 	    NULL, ctime, sizeof (ctime));
795 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs),
796 	    NULL, mtime, sizeof (mtime));
797 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs),
798 	    NULL, &dzp->z_pflags, sizeof (dzp->z_pflags));
799 	zfs_tstamp_update_setup(dzp, CONTENT_MODIFIED, mtime, ctime);
800 	error = sa_bulk_update(dzp->z_sa_hdl, bulk, count, tx);
801 	ASSERT0(error);
802 
803 	if (unlinkedp != NULL)
804 		*unlinkedp = unlinked;
805 	else if (unlinked)
806 		zfs_unlinked_add(zp, tx);
807 
808 	return (0);
809 }
810 
811 /*
812  * Indicate whether the directory is empty.
813  */
814 boolean_t
zfs_dirempty(znode_t * dzp)815 zfs_dirempty(znode_t *dzp)
816 {
817 	return (dzp->z_size == 2);
818 }
819 
820 int
zfs_make_xattrdir(znode_t * zp,vattr_t * vap,znode_t ** xvpp,cred_t * cr)821 zfs_make_xattrdir(znode_t *zp, vattr_t *vap, znode_t **xvpp, cred_t *cr)
822 {
823 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
824 	znode_t *xzp;
825 	dmu_tx_t *tx;
826 	int error;
827 	zfs_acl_ids_t acl_ids;
828 	boolean_t fuid_dirtied;
829 	uint64_t parent __maybe_unused;
830 
831 	*xvpp = NULL;
832 
833 	if ((error = zfs_acl_ids_create(zp, IS_XATTR, vap, cr, NULL,
834 	    &acl_ids, NULL)) != 0)
835 		return (error);
836 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids, zp->z_projid)) {
837 		zfs_acl_ids_free(&acl_ids);
838 		return (SET_ERROR(EDQUOT));
839 	}
840 
841 	getnewvnode_reserve();
842 
843 	tx = dmu_tx_create(zfsvfs->z_os);
844 	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
845 	    ZFS_SA_BASE_ATTR_SIZE);
846 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
847 	dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
848 	fuid_dirtied = zfsvfs->z_fuid_dirty;
849 	if (fuid_dirtied)
850 		zfs_fuid_txhold(zfsvfs, tx);
851 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
852 	if (error) {
853 		zfs_acl_ids_free(&acl_ids);
854 		dmu_tx_abort(tx);
855 		getnewvnode_drop_reserve();
856 		return (error);
857 	}
858 	zfs_mknode(zp, vap, tx, cr, IS_XATTR, &xzp, &acl_ids);
859 
860 	if (fuid_dirtied)
861 		zfs_fuid_sync(zfsvfs, tx);
862 
863 	ASSERT0(sa_lookup(xzp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs), &parent,
864 	    sizeof (parent)));
865 	ASSERT3U(parent, ==, zp->z_id);
866 
867 	VERIFY0(sa_update(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs), &xzp->z_id,
868 	    sizeof (xzp->z_id), tx));
869 
870 	zfs_log_create(zfsvfs->z_log, tx, TX_MKXATTR, zp, xzp, "", NULL,
871 	    acl_ids.z_fuidp, vap);
872 
873 	zfs_acl_ids_free(&acl_ids);
874 	dmu_tx_commit(tx);
875 
876 	getnewvnode_drop_reserve();
877 
878 	*xvpp = xzp;
879 
880 	return (0);
881 }
882 
883 /*
884  * Return a znode for the extended attribute directory for zp.
885  * ** If the directory does not already exist, it is created **
886  *
887  *	IN:	zp	- znode to obtain attribute directory from
888  *		cr	- credentials of caller
889  *		flags	- flags from the VOP_LOOKUP call
890  *
891  *	OUT:	xzpp	- pointer to extended attribute znode
892  *
893  *	RETURN:	0 on success
894  *		error number on failure
895  */
896 int
zfs_get_xattrdir(znode_t * zp,znode_t ** xzpp,cred_t * cr,int flags)897 zfs_get_xattrdir(znode_t *zp, znode_t **xzpp, cred_t *cr, int flags)
898 {
899 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
900 	znode_t		*xzp;
901 	vattr_t		va;
902 	int		error;
903 top:
904 	error = zfs_dirent_lookup(zp, "", &xzp, ZXATTR);
905 	if (error)
906 		return (error);
907 
908 	if (xzp != NULL) {
909 		*xzpp = xzp;
910 		return (0);
911 	}
912 
913 
914 	if (!(flags & CREATE_XATTR_DIR))
915 		return (SET_ERROR(ENOATTR));
916 
917 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
918 		return (SET_ERROR(EROFS));
919 	}
920 
921 	/*
922 	 * The ability to 'create' files in an attribute
923 	 * directory comes from the write_xattr permission on the base file.
924 	 *
925 	 * The ability to 'search' an attribute directory requires
926 	 * read_xattr permission on the base file.
927 	 *
928 	 * Once in a directory the ability to read/write attributes
929 	 * is controlled by the permissions on the attribute file.
930 	 */
931 	va.va_mask = AT_MODE | AT_UID | AT_GID;
932 	va.va_type = VDIR;
933 	va.va_mode = S_IFDIR | S_ISVTX | 0777;
934 	zfs_fuid_map_ids(zp, cr, &va.va_uid, &va.va_gid);
935 
936 	error = zfs_make_xattrdir(zp, &va, xzpp, cr);
937 
938 	if (error == ERESTART) {
939 		/* NB: we already did dmu_tx_wait() if necessary */
940 		goto top;
941 	}
942 	if (error == 0)
943 		VOP_UNLOCK(ZTOV(*xzpp));
944 
945 	return (error);
946 }
947 
948 /*
949  * Decide whether it is okay to remove within a sticky directory.
950  *
951  * In sticky directories, write access is not sufficient;
952  * you can remove entries from a directory only if:
953  *
954  *	you own the directory,
955  *	you own the entry,
956  *	the entry is a plain file and you have write access,
957  *	or you are privileged (checked in secpolicy...).
958  *
959  * The function returns 0 if remove access is granted.
960  */
961 int
zfs_sticky_remove_access(znode_t * zdp,znode_t * zp,cred_t * cr)962 zfs_sticky_remove_access(znode_t *zdp, znode_t *zp, cred_t *cr)
963 {
964 	uid_t  		uid;
965 	uid_t		downer;
966 	uid_t		fowner;
967 	zfsvfs_t	*zfsvfs = zdp->z_zfsvfs;
968 
969 	if (zdp->z_zfsvfs->z_replay)
970 		return (0);
971 
972 	if ((zdp->z_mode & S_ISVTX) == 0)
973 		return (0);
974 
975 	downer = zfs_fuid_map_id(zfsvfs, zdp->z_uid, cr, ZFS_OWNER);
976 	fowner = zfs_fuid_map_id(zfsvfs, zp->z_uid, cr, ZFS_OWNER);
977 
978 	if ((uid = crgetuid(cr)) == downer || uid == fowner ||
979 	    (ZTOV(zp)->v_type == VREG &&
980 	    zfs_zaccess(zp, ACE_WRITE_DATA, 0, B_FALSE, cr, NULL) == 0))
981 		return (0);
982 	else
983 		return (secpolicy_vnode_remove(ZTOV(zp), cr));
984 }
985