xref: /freebsd/sys/contrib/openzfs/module/os/linux/zfs/zfs_dir.c (revision 22649d4dba730d46244fd2dff4fd174903c8379f)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * This file and its contents are supplied under the terms of the
4  * Common Development and Distribution License ("CDDL"), version 1.0.
5  * You may only use this file in accordance with the terms of version
6  * 1.0 of the CDDL.
7  *
8  * A full copy of the text of the CDDL should have accompanied this
9  * source.  A copy of the CDDL is also available via the Internet at
10  * https://opensource.org/license/CDDL-1.0.
11  */
12 
13 /*
14  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
15  * Copyright (c) 2013, 2016 by Delphix. All rights reserved.
16  * Copyright 2017 Nexenta Systems, Inc.
17  */
18 
19 #include <sys/types.h>
20 #include <sys/param.h>
21 #include <sys/time.h>
22 #include <sys/sysmacros.h>
23 #include <sys/vfs.h>
24 #include <sys/vnode.h>
25 #include <sys/file.h>
26 #include <sys/kmem.h>
27 #include <sys/uio.h>
28 #include <sys/pathname.h>
29 #include <sys/cmn_err.h>
30 #include <sys/errno.h>
31 #include <sys/stat.h>
32 #include <sys/sunddi.h>
33 #include <sys/random.h>
34 #include <sys/policy.h>
35 #include <sys/zfs_dir.h>
36 #include <sys/zfs_acl_impl.h>
37 #include <sys/zfs_vnops.h>
38 #include <sys/fs/zfs.h>
39 #include <sys/zap.h>
40 #include <sys/dmu.h>
41 #include <sys/atomic.h>
42 #include <sys/zfs_ctldir.h>
43 #include <sys/zfs_fuid.h>
44 #include <sys/sa.h>
45 #include <sys/zfs_sa.h>
46 #include <sys/dmu_objset.h>
47 #include <sys/dsl_dir.h>
48 
49 /*
50  * zfs_match_find() is used by zfs_dirent_lock() to perform zap lookups
51  * of names after deciding which is the appropriate lookup interface.
52  */
53 static int
zfs_match_find(zfsvfs_t * zfsvfs,znode_t * dzp,const char * name,matchtype_t mt,boolean_t update,int * deflags,pathname_t * rpnp,uint64_t * zoid)54 zfs_match_find(zfsvfs_t *zfsvfs, znode_t *dzp, const char *name,
55     matchtype_t mt, boolean_t update, int *deflags, pathname_t *rpnp,
56     uint64_t *zoid)
57 {
58 	boolean_t conflict = B_FALSE;
59 	int error;
60 
61 	if (zfsvfs->z_norm) {
62 		size_t bufsz = 0;
63 		char *buf = NULL;
64 
65 		if (rpnp) {
66 			buf = rpnp->pn_buf;
67 			bufsz = rpnp->pn_bufsize;
68 		}
69 
70 		/*
71 		 * In the non-mixed case we only expect there would ever
72 		 * be one match, but we need to use the normalizing lookup.
73 		 */
74 		error = zap_lookup_norm(zfsvfs->z_os, dzp->z_id, name, 8, 1,
75 		    zoid, mt, buf, bufsz, &conflict);
76 	} else {
77 		error = zap_lookup(zfsvfs->z_os, dzp->z_id, name, 8, 1, zoid);
78 	}
79 
80 	/*
81 	 * Allow multiple entries provided the first entry is
82 	 * the object id.  Non-zpl consumers may safely make
83 	 * use of the additional space.
84 	 *
85 	 * XXX: This should be a feature flag for compatibility
86 	 */
87 	if (error == EOVERFLOW)
88 		error = 0;
89 
90 	if (zfsvfs->z_norm && !error && deflags)
91 		*deflags = conflict ? ED_CASE_CONFLICT : 0;
92 
93 	*zoid = ZFS_DIRENT_OBJ(*zoid);
94 
95 	return (error);
96 }
97 
98 /*
99  * Lock a directory entry.  A dirlock on <dzp, name> protects that name
100  * in dzp's directory zap object.  As long as you hold a dirlock, you can
101  * assume two things: (1) dzp cannot be reaped, and (2) no other thread
102  * can change the zap entry for (i.e. link or unlink) this name.
103  *
104  * Input arguments:
105  *	dzp	- znode for directory
106  *	name	- name of entry to lock
107  *	flag	- ZNEW: if the entry already exists, fail with EEXIST.
108  *		  ZEXISTS: if the entry does not exist, fail with ENOENT.
109  *		  ZSHARED: allow concurrent access with other ZSHARED callers.
110  *		  ZXATTR: we want dzp's xattr directory
111  *		  ZCILOOK: On a mixed sensitivity file system,
112  *			   this lookup should be case-insensitive.
113  *		  ZCIEXACT: On a purely case-insensitive file system,
114  *			    this lookup should be case-sensitive.
115  *		  ZRENAMING: we are locking for renaming, force narrow locks
116  *		  ZHAVELOCK: Don't grab the z_name_lock for this call. The
117  *			     current thread already holds it.
118  *
119  * Output arguments:
120  *	zpp	- pointer to the znode for the entry (NULL if there isn't one)
121  *	dlpp	- pointer to the dirlock for this entry (NULL on error)
122  *      direntflags - (case-insensitive lookup only)
123  *		flags if multiple case-sensitive matches exist in directory
124  *      realpnp     - (case-insensitive lookup only)
125  *		actual name matched within the directory
126  *
127  * Return value: 0 on success or errno on failure.
128  *
129  * NOTE: Always checks for, and rejects, '.' and '..'.
130  * NOTE: For case-insensitive file systems we take wide locks (see below),
131  *	 but return znode pointers to a single match.
132  */
133 int
zfs_dirent_lock(zfs_dirlock_t ** dlpp,znode_t * dzp,char * name,znode_t ** zpp,int flag,int * direntflags,pathname_t * realpnp)134 zfs_dirent_lock(zfs_dirlock_t **dlpp, znode_t *dzp, char *name,
135     znode_t **zpp, int flag, int *direntflags, pathname_t *realpnp)
136 {
137 	zfsvfs_t	*zfsvfs = ZTOZSB(dzp);
138 	zfs_dirlock_t	*dl;
139 	boolean_t	update;
140 	matchtype_t	mt = 0;
141 	uint64_t	zoid;
142 	int		error = 0;
143 	int		cmpflags;
144 
145 	*zpp = NULL;
146 	*dlpp = NULL;
147 
148 	/*
149 	 * Verify that we are not trying to lock '.', '..', or '.zfs'
150 	 */
151 	if ((name[0] == '.' &&
152 	    (name[1] == '\0' || (name[1] == '.' && name[2] == '\0'))) ||
153 	    (zfs_has_ctldir(dzp) && strcmp(name, ZFS_CTLDIR_NAME) == 0))
154 		return (SET_ERROR(EEXIST));
155 
156 	/*
157 	 * Case sensitivity and normalization preferences are set when
158 	 * the file system is created.  These are stored in the
159 	 * zfsvfs->z_case and zfsvfs->z_norm fields.  These choices
160 	 * affect what vnodes can be cached in the DNLC, how we
161 	 * perform zap lookups, and the "width" of our dirlocks.
162 	 *
163 	 * A normal dirlock locks a single name.  Note that with
164 	 * normalization a name can be composed multiple ways, but
165 	 * when normalized, these names all compare equal.  A wide
166 	 * dirlock locks multiple names.  We need these when the file
167 	 * system is supporting mixed-mode access.  It is sometimes
168 	 * necessary to lock all case permutations of file name at
169 	 * once so that simultaneous case-insensitive/case-sensitive
170 	 * behaves as rationally as possible.
171 	 */
172 
173 	/*
174 	 * When matching we may need to normalize & change case according to
175 	 * FS settings.
176 	 *
177 	 * Note that a normalized match is necessary for a case insensitive
178 	 * filesystem when the lookup request is not exact because normalization
179 	 * can fold case independent of normalizing code point sequences.
180 	 *
181 	 * See the table above zfs_dropname().
182 	 */
183 	if (zfsvfs->z_norm != 0) {
184 		mt = MT_NORMALIZE;
185 
186 		/*
187 		 * Determine if the match needs to honor the case specified in
188 		 * lookup, and if so keep track of that so that during
189 		 * normalization we don't fold case.
190 		 */
191 		if ((zfsvfs->z_case == ZFS_CASE_INSENSITIVE &&
192 		    (flag & ZCIEXACT)) ||
193 		    (zfsvfs->z_case == ZFS_CASE_MIXED && !(flag & ZCILOOK))) {
194 			mt |= MT_MATCH_CASE;
195 		}
196 	}
197 
198 	/*
199 	 * Only look in or update the DNLC if we are looking for the
200 	 * name on a file system that does not require normalization
201 	 * or case folding.  We can also look there if we happen to be
202 	 * on a non-normalizing, mixed sensitivity file system IF we
203 	 * are looking for the exact name.
204 	 *
205 	 * Maybe can add TO-UPPERed version of name to dnlc in ci-only
206 	 * case for performance improvement?
207 	 */
208 	update = !zfsvfs->z_norm ||
209 	    (zfsvfs->z_case == ZFS_CASE_MIXED &&
210 	    !(zfsvfs->z_norm & ~U8_TEXTPREP_TOUPPER) && !(flag & ZCILOOK));
211 
212 	/*
213 	 * ZRENAMING indicates we are in a situation where we should
214 	 * take narrow locks regardless of the file system's
215 	 * preferences for normalizing and case folding.  This will
216 	 * prevent us deadlocking trying to grab the same wide lock
217 	 * twice if the two names happen to be case-insensitive
218 	 * matches.
219 	 */
220 	if (flag & ZRENAMING)
221 		cmpflags = 0;
222 	else
223 		cmpflags = zfsvfs->z_norm;
224 
225 	/*
226 	 * Wait until there are no locks on this name.
227 	 *
228 	 * Don't grab the lock if it is already held. However, cannot
229 	 * have both ZSHARED and ZHAVELOCK together.
230 	 */
231 	ASSERT(!(flag & ZSHARED) || !(flag & ZHAVELOCK));
232 	if (!(flag & ZHAVELOCK))
233 		rw_enter(&dzp->z_name_lock, RW_READER);
234 
235 	mutex_enter(&dzp->z_lock);
236 	for (;;) {
237 		if (dzp->z_unlinked && !(flag & ZXATTR)) {
238 			mutex_exit(&dzp->z_lock);
239 			if (!(flag & ZHAVELOCK))
240 				rw_exit(&dzp->z_name_lock);
241 			return (SET_ERROR(ENOENT));
242 		}
243 		for (dl = dzp->z_dirlocks; dl != NULL; dl = dl->dl_next) {
244 			if ((u8_strcmp(name, dl->dl_name, 0, cmpflags,
245 			    U8_UNICODE_LATEST, &error) == 0) || error != 0)
246 				break;
247 		}
248 		if (error != 0) {
249 			mutex_exit(&dzp->z_lock);
250 			if (!(flag & ZHAVELOCK))
251 				rw_exit(&dzp->z_name_lock);
252 			return (SET_ERROR(ENOENT));
253 		}
254 		if (dl == NULL)	{
255 			/*
256 			 * Allocate a new dirlock and add it to the list.
257 			 */
258 			dl = kmem_alloc(sizeof (zfs_dirlock_t), KM_SLEEP);
259 			cv_init(&dl->dl_cv, NULL, CV_DEFAULT, NULL);
260 			dl->dl_name = name;
261 			dl->dl_sharecnt = 0;
262 			dl->dl_namelock = 0;
263 			dl->dl_namesize = 0;
264 			dl->dl_dzp = dzp;
265 			dl->dl_next = dzp->z_dirlocks;
266 			dzp->z_dirlocks = dl;
267 			break;
268 		}
269 		if ((flag & ZSHARED) && dl->dl_sharecnt != 0)
270 			break;
271 		cv_wait(&dl->dl_cv, &dzp->z_lock);
272 	}
273 
274 	/*
275 	 * If the z_name_lock was NOT held for this dirlock record it.
276 	 */
277 	if (flag & ZHAVELOCK)
278 		dl->dl_namelock = 1;
279 
280 	if ((flag & ZSHARED) && ++dl->dl_sharecnt > 1 && dl->dl_namesize == 0) {
281 		/*
282 		 * We're the second shared reference to dl.  Make a copy of
283 		 * dl_name in case the first thread goes away before we do.
284 		 * Note that we initialize the new name before storing its
285 		 * pointer into dl_name, because the first thread may load
286 		 * dl->dl_name at any time.  It'll either see the old value,
287 		 * which belongs to it, or the new shared copy; either is OK.
288 		 */
289 		dl->dl_namesize = strlen(dl->dl_name) + 1;
290 		name = kmem_alloc(dl->dl_namesize, KM_SLEEP);
291 		memcpy(name, dl->dl_name, dl->dl_namesize);
292 		dl->dl_name = name;
293 	}
294 
295 	mutex_exit(&dzp->z_lock);
296 
297 	/*
298 	 * We have a dirlock on the name.  (Note that it is the dirlock,
299 	 * not the dzp's z_lock, that protects the name in the zap object.)
300 	 * See if there's an object by this name; if so, put a hold on it.
301 	 */
302 	if (flag & ZXATTR) {
303 		error = sa_lookup(dzp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs), &zoid,
304 		    sizeof (zoid));
305 		if (error == 0)
306 			error = (zoid == 0 ? SET_ERROR(ENOENT) : 0);
307 	} else {
308 		error = zfs_match_find(zfsvfs, dzp, name, mt,
309 		    update, direntflags, realpnp, &zoid);
310 	}
311 	if (error) {
312 		if (error != ENOENT || (flag & ZEXISTS)) {
313 			zfs_dirent_unlock(dl);
314 			return (error);
315 		}
316 	} else {
317 		if (flag & ZNEW) {
318 			zfs_dirent_unlock(dl);
319 			return (SET_ERROR(EEXIST));
320 		}
321 		error = zfs_zget(zfsvfs, zoid, zpp);
322 		if (error) {
323 			zfs_dirent_unlock(dl);
324 			return (error);
325 		}
326 	}
327 
328 	*dlpp = dl;
329 
330 	return (0);
331 }
332 
333 /*
334  * Unlock this directory entry and wake anyone who was waiting for it.
335  */
336 void
zfs_dirent_unlock(zfs_dirlock_t * dl)337 zfs_dirent_unlock(zfs_dirlock_t *dl)
338 {
339 	znode_t *dzp = dl->dl_dzp;
340 	zfs_dirlock_t **prev_dl, *cur_dl;
341 
342 	mutex_enter(&dzp->z_lock);
343 
344 	if (!dl->dl_namelock)
345 		rw_exit(&dzp->z_name_lock);
346 
347 	if (dl->dl_sharecnt > 1) {
348 		dl->dl_sharecnt--;
349 		mutex_exit(&dzp->z_lock);
350 		return;
351 	}
352 	prev_dl = &dzp->z_dirlocks;
353 	while ((cur_dl = *prev_dl) != dl)
354 		prev_dl = &cur_dl->dl_next;
355 	*prev_dl = dl->dl_next;
356 	cv_broadcast(&dl->dl_cv);
357 	mutex_exit(&dzp->z_lock);
358 
359 	if (dl->dl_namesize != 0)
360 		kmem_free(dl->dl_name, dl->dl_namesize);
361 	cv_destroy(&dl->dl_cv);
362 	kmem_free(dl, sizeof (*dl));
363 }
364 
365 /*
366  * Look up an entry in a directory.
367  *
368  * NOTE: '.' and '..' are handled as special cases because
369  *	no directory entries are actually stored for them.  If this is
370  *	the root of a filesystem, then '.zfs' is also treated as a
371  *	special pseudo-directory.
372  */
373 int
zfs_dirlook(znode_t * dzp,char * name,znode_t ** zpp,int flags,int * deflg,pathname_t * rpnp)374 zfs_dirlook(znode_t *dzp, char *name, znode_t **zpp, int flags,
375     int *deflg, pathname_t *rpnp)
376 {
377 	zfs_dirlock_t *dl;
378 	znode_t *zp;
379 	struct inode *ip;
380 	int error = 0;
381 	uint64_t parent;
382 
383 	if (name[0] == 0 || (name[0] == '.' && name[1] == 0)) {
384 		*zpp = dzp;
385 		zhold(*zpp);
386 	} else if (name[0] == '.' && name[1] == '.' && name[2] == 0) {
387 		zfsvfs_t *zfsvfs = ZTOZSB(dzp);
388 
389 		/*
390 		 * If we are a snapshot mounted under .zfs, return
391 		 * the inode pointer for the snapshot directory.
392 		 */
393 		if ((error = sa_lookup(dzp->z_sa_hdl,
394 		    SA_ZPL_PARENT(zfsvfs), &parent, sizeof (parent))) != 0)
395 			return (error);
396 
397 		if (parent == dzp->z_id && zfsvfs->z_parent != zfsvfs) {
398 			error = zfsctl_root_lookup(zfsvfs->z_parent->z_ctldir,
399 			    "snapshot", &ip, 0, kcred, NULL, NULL);
400 			*zpp = ITOZ(ip);
401 			return (error);
402 		}
403 		rw_enter(&dzp->z_parent_lock, RW_READER);
404 		error = zfs_zget(zfsvfs, parent, &zp);
405 		if (error == 0)
406 			*zpp = zp;
407 		rw_exit(&dzp->z_parent_lock);
408 	} else if (zfs_has_ctldir(dzp) && strcmp(name, ZFS_CTLDIR_NAME) == 0) {
409 		if (ZTOZSB(dzp)->z_show_ctldir == ZFS_SNAPDIR_DISABLED) {
410 			return (SET_ERROR(ENOENT));
411 		}
412 		ip = zfsctl_root(dzp);
413 		*zpp = ITOZ(ip);
414 	} else {
415 		int zf;
416 
417 		zf = ZEXISTS | ZSHARED;
418 		if (flags & FIGNORECASE)
419 			zf |= ZCILOOK;
420 
421 		error = zfs_dirent_lock(&dl, dzp, name, &zp, zf, deflg, rpnp);
422 		if (error == 0) {
423 			*zpp = zp;
424 			zfs_dirent_unlock(dl);
425 			dzp->z_zn_prefetch = B_TRUE; /* enable prefetching */
426 		}
427 		rpnp = NULL;
428 	}
429 
430 	if ((flags & FIGNORECASE) && rpnp && !error)
431 		(void) strlcpy(rpnp->pn_buf, name, rpnp->pn_bufsize);
432 
433 	return (error);
434 }
435 
436 /*
437  * unlinked Set (formerly known as the "delete queue") Error Handling
438  *
439  * When dealing with the unlinked set, we dmu_tx_hold_zap(), but we
440  * don't specify the name of the entry that we will be manipulating.  We
441  * also fib and say that we won't be adding any new entries to the
442  * unlinked set, even though we might (this is to lower the minimum file
443  * size that can be deleted in a full filesystem).  So on the small
444  * chance that the nlink list is using a fat zap (ie. has more than
445  * 2000 entries), we *may* not pre-read a block that's needed.
446  * Therefore it is remotely possible for some of the assertions
447  * regarding the unlinked set below to fail due to i/o error.  On a
448  * nondebug system, this will result in the space being leaked.
449  */
450 void
zfs_unlinked_add(znode_t * zp,dmu_tx_t * tx)451 zfs_unlinked_add(znode_t *zp, dmu_tx_t *tx)
452 {
453 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
454 
455 	ASSERT(zp->z_unlinked);
456 	ASSERT0(ZTOI(zp)->i_nlink);
457 
458 	VERIFY3U(0, ==,
459 	    zap_add_int(zfsvfs->z_os, zfsvfs->z_unlinkedobj, zp->z_id, tx));
460 
461 	dataset_kstats_update_nunlinks_kstat(&zfsvfs->z_kstat, 1);
462 }
463 
464 /*
465  * Clean up any znodes that had no links when we either crashed or
466  * (force) umounted the file system.
467  */
468 static void
zfs_unlinked_drain_task(void * arg)469 zfs_unlinked_drain_task(void *arg)
470 {
471 	zfsvfs_t *zfsvfs = arg;
472 	zap_cursor_t	zc;
473 	zap_attribute_t *zap = zap_attribute_alloc();
474 	dmu_object_info_t doi;
475 	znode_t		*zp;
476 	int		error;
477 
478 	ASSERT3B(zfsvfs->z_draining, ==, B_TRUE);
479 
480 	/*
481 	 * Iterate over the contents of the unlinked set.
482 	 */
483 	for (zap_cursor_init(&zc, zfsvfs->z_os, zfsvfs->z_unlinkedobj);
484 	    zap_cursor_retrieve(&zc, zap) == 0 && !zfsvfs->z_drain_cancel;
485 	    zap_cursor_advance(&zc)) {
486 
487 		/*
488 		 * See what kind of object we have in list
489 		 */
490 
491 		error = dmu_object_info(zfsvfs->z_os,
492 		    zap->za_first_integer, &doi);
493 		if (error != 0)
494 			continue;
495 
496 		ASSERT((doi.doi_type == DMU_OT_PLAIN_FILE_CONTENTS) ||
497 		    (doi.doi_type == DMU_OT_DIRECTORY_CONTENTS));
498 		/*
499 		 * We need to re-mark these list entries for deletion,
500 		 * so we pull them back into core and set zp->z_unlinked.
501 		 */
502 		error = zfs_zget(zfsvfs, zap->za_first_integer, &zp);
503 
504 		/*
505 		 * We may pick up znodes that are already marked for deletion.
506 		 * This could happen during the purge of an extended attribute
507 		 * directory.  All we need to do is skip over them, since they
508 		 * are already in the system marked z_unlinked.
509 		 */
510 		if (error != 0)
511 			continue;
512 
513 		zp->z_unlinked = B_TRUE;
514 
515 		/*
516 		 * zrele() decrements the znode's ref count and may cause
517 		 * it to be synchronously freed. We interrupt freeing
518 		 * of this znode by checking the return value of
519 		 * dmu_objset_zfs_unmounting() in dmu_free_long_range()
520 		 * when an unmount is requested.
521 		 */
522 		zrele(zp);
523 		ASSERT3B(zfsvfs->z_unmounted, ==, B_FALSE);
524 	}
525 	zap_cursor_fini(&zc);
526 
527 	zfsvfs->z_draining = B_FALSE;
528 	zfsvfs->z_drain_task = TASKQID_INVALID;
529 	zap_attribute_free(zap);
530 }
531 
532 /*
533  * Sets z_draining then tries to dispatch async unlinked drain.
534  * If that fails executes synchronous unlinked drain.
535  */
536 void
zfs_unlinked_drain(zfsvfs_t * zfsvfs)537 zfs_unlinked_drain(zfsvfs_t *zfsvfs)
538 {
539 	ASSERT3B(zfsvfs->z_unmounted, ==, B_FALSE);
540 	ASSERT3B(zfsvfs->z_draining, ==, B_FALSE);
541 
542 	zfsvfs->z_draining = B_TRUE;
543 	zfsvfs->z_drain_cancel = B_FALSE;
544 
545 	zfsvfs->z_drain_task = taskq_dispatch(
546 	    dsl_pool_unlinked_drain_taskq(dmu_objset_pool(zfsvfs->z_os)),
547 	    zfs_unlinked_drain_task, zfsvfs, TQ_SLEEP);
548 	if (zfsvfs->z_drain_task == TASKQID_INVALID) {
549 		zfs_dbgmsg("async zfs_unlinked_drain dispatch failed");
550 		zfs_unlinked_drain_task(zfsvfs);
551 	}
552 }
553 
554 /*
555  * Wait for the unlinked drain taskq task to stop. This will interrupt the
556  * unlinked set processing if it is in progress.
557  */
558 void
zfs_unlinked_drain_stop_wait(zfsvfs_t * zfsvfs)559 zfs_unlinked_drain_stop_wait(zfsvfs_t *zfsvfs)
560 {
561 	ASSERT3B(zfsvfs->z_unmounted, ==, B_FALSE);
562 
563 	if (zfsvfs->z_draining) {
564 		zfsvfs->z_drain_cancel = B_TRUE;
565 		taskq_cancel_id(dsl_pool_unlinked_drain_taskq(
566 		    dmu_objset_pool(zfsvfs->z_os)), zfsvfs->z_drain_task,
567 		    B_TRUE);
568 		zfsvfs->z_drain_task = TASKQID_INVALID;
569 		zfsvfs->z_draining = B_FALSE;
570 	}
571 }
572 
573 /*
574  * Delete the entire contents of a directory.  Return a count
575  * of the number of entries that could not be deleted. If we encounter
576  * an error, return a count of at least one so that the directory stays
577  * in the unlinked set.
578  *
579  * NOTE: this function assumes that the directory is inactive,
580  *	so there is no need to lock its entries before deletion.
581  *	Also, it assumes the directory contents is *only* regular
582  *	files.
583  */
584 static int
zfs_purgedir(znode_t * dzp)585 zfs_purgedir(znode_t *dzp)
586 {
587 	zap_cursor_t	zc;
588 	zap_attribute_t	*zap = zap_attribute_alloc();
589 	znode_t		*xzp;
590 	dmu_tx_t	*tx;
591 	zfsvfs_t	*zfsvfs = ZTOZSB(dzp);
592 	zfs_dirlock_t	dl;
593 	int skipped = 0;
594 	int error;
595 
596 	for (zap_cursor_init(&zc, zfsvfs->z_os, dzp->z_id);
597 	    (error = zap_cursor_retrieve(&zc, zap)) == 0;
598 	    zap_cursor_advance(&zc)) {
599 		error = zfs_zget(zfsvfs,
600 		    ZFS_DIRENT_OBJ(zap->za_first_integer), &xzp);
601 		if (error) {
602 			skipped += 1;
603 			continue;
604 		}
605 
606 		ASSERT(S_ISREG(ZTOI(xzp)->i_mode) ||
607 		    S_ISLNK(ZTOI(xzp)->i_mode));
608 
609 		tx = dmu_tx_create(zfsvfs->z_os);
610 		dmu_tx_hold_sa(tx, dzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(dzp));
611 		dmu_tx_hold_zap(tx, dzp->z_id, FALSE, zap->za_name);
612 		dmu_tx_hold_sa(tx, xzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(xzp));
613 		dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
614 		/* Is this really needed ? */
615 		zfs_sa_upgrade_txholds(tx, xzp);
616 		dmu_tx_mark_netfree(tx);
617 		error = dmu_tx_assign(tx, DMU_TX_WAIT);
618 		if (error) {
619 			dmu_tx_abort(tx);
620 			zfs_zrele_async(xzp);
621 			skipped += 1;
622 			continue;
623 		}
624 		memset(&dl, 0, sizeof (dl));
625 		dl.dl_dzp = dzp;
626 		dl.dl_name = zap->za_name;
627 
628 		error = zfs_link_destroy(&dl, xzp, tx, 0, NULL);
629 		if (error)
630 			skipped += 1;
631 		dmu_tx_commit(tx);
632 
633 		zfs_zrele_async(xzp);
634 	}
635 	zap_cursor_fini(&zc);
636 	zap_attribute_free(zap);
637 	if (error != ENOENT)
638 		skipped += 1;
639 	return (skipped);
640 }
641 
642 void
zfs_rmnode(znode_t * zp)643 zfs_rmnode(znode_t *zp)
644 {
645 	zfsvfs_t	*zfsvfs = ZTOZSB(zp);
646 	objset_t	*os = zfsvfs->z_os;
647 	znode_t		*xzp = NULL;
648 	dmu_tx_t	*tx;
649 	znode_hold_t	*zh;
650 	uint64_t	z_id = zp->z_id;
651 	uint64_t	acl_obj;
652 	uint64_t	xattr_obj;
653 	uint64_t	links;
654 	int		error;
655 
656 	ASSERT0(ZTOI(zp)->i_nlink);
657 	ASSERT0(atomic_read(&ZTOI(zp)->i_count));
658 
659 	/*
660 	 * If this is an attribute directory, purge its contents.
661 	 */
662 	if (S_ISDIR(ZTOI(zp)->i_mode) && (zp->z_pflags & ZFS_XATTR)) {
663 		if (zfs_purgedir(zp) != 0) {
664 			/*
665 			 * Not enough space to delete some xattrs.
666 			 * Leave it in the unlinked set.
667 			 */
668 			zh = zfs_znode_hold_enter(zfsvfs, z_id);
669 			zfs_znode_dmu_fini(zp);
670 			zfs_znode_hold_exit(zfsvfs, zh);
671 			return;
672 		}
673 	}
674 
675 	/*
676 	 * Free up all the data in the file.  We don't do this for directories
677 	 * because we need truncate and remove to be in the same tx, like in
678 	 * zfs_znode_delete(). Otherwise, if we crash here we'll end up with
679 	 * an inconsistent truncated zap object in the delete queue.  Note a
680 	 * truncated file is harmless since it only contains user data.
681 	 */
682 	if (S_ISREG(ZTOI(zp)->i_mode)) {
683 		error = dmu_free_long_range(os, zp->z_id, 0, DMU_OBJECT_END);
684 		if (error) {
685 			/*
686 			 * Not enough space or we were interrupted by unmount.
687 			 * Leave the file in the unlinked set.
688 			 */
689 			zh = zfs_znode_hold_enter(zfsvfs, z_id);
690 			zfs_znode_dmu_fini(zp);
691 			zfs_znode_hold_exit(zfsvfs, zh);
692 			return;
693 		}
694 	}
695 
696 	/*
697 	 * If the file has extended attributes, we're going to unlink
698 	 * the xattr dir.
699 	 */
700 	error = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
701 	    &xattr_obj, sizeof (xattr_obj));
702 	if (error == 0 && xattr_obj) {
703 		error = zfs_zget(zfsvfs, xattr_obj, &xzp);
704 		ASSERT0(error);
705 	}
706 
707 	acl_obj = zfs_external_acl(zp);
708 
709 	/*
710 	 * Set up the final transaction.
711 	 */
712 	tx = dmu_tx_create(os);
713 	dmu_tx_hold_free(tx, zp->z_id, 0, DMU_OBJECT_END);
714 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
715 	if (xzp) {
716 		dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, TRUE, NULL);
717 		dmu_tx_hold_sa(tx, xzp->z_sa_hdl, B_FALSE);
718 	}
719 	if (acl_obj)
720 		dmu_tx_hold_free(tx, acl_obj, 0, DMU_OBJECT_END);
721 
722 	zfs_sa_upgrade_txholds(tx, zp);
723 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
724 	if (error) {
725 		/*
726 		 * Not enough space to delete the file.  Leave it in the
727 		 * unlinked set, leaking it until the fs is remounted (at
728 		 * which point we'll call zfs_unlinked_drain() to process it).
729 		 */
730 		dmu_tx_abort(tx);
731 		zh = zfs_znode_hold_enter(zfsvfs, z_id);
732 		zfs_znode_dmu_fini(zp);
733 		zfs_znode_hold_exit(zfsvfs, zh);
734 		goto out;
735 	}
736 
737 	if (xzp) {
738 		ASSERT0(error);
739 		mutex_enter(&xzp->z_lock);
740 		xzp->z_unlinked = B_TRUE;	/* mark xzp for deletion */
741 		clear_nlink(ZTOI(xzp));		/* no more links to it */
742 		links = 0;
743 		VERIFY0(sa_update(xzp->z_sa_hdl, SA_ZPL_LINKS(zfsvfs),
744 		    &links, sizeof (links), tx));
745 		mutex_exit(&xzp->z_lock);
746 		zfs_unlinked_add(xzp, tx);
747 	}
748 
749 	mutex_enter(&os->os_dsl_dataset->ds_dir->dd_activity_lock);
750 
751 	/*
752 	 * Remove this znode from the unlinked set.  If a has rollback has
753 	 * occurred while a file is open and unlinked.  Then when the file
754 	 * is closed post rollback it will not exist in the rolled back
755 	 * version of the unlinked object.
756 	 */
757 	error = zap_remove_int(zfsvfs->z_os, zfsvfs->z_unlinkedobj,
758 	    zp->z_id, tx);
759 	VERIFY(error == 0 || error == ENOENT);
760 
761 	uint64_t count;
762 	if (zap_count(os, zfsvfs->z_unlinkedobj, &count) == 0 && count == 0) {
763 		cv_broadcast(&os->os_dsl_dataset->ds_dir->dd_activity_cv);
764 	}
765 
766 	mutex_exit(&os->os_dsl_dataset->ds_dir->dd_activity_lock);
767 
768 	dataset_kstats_update_nunlinked_kstat(&zfsvfs->z_kstat, 1);
769 
770 	zfs_znode_delete(zp, tx);
771 
772 	dmu_tx_commit(tx);
773 out:
774 	if (xzp)
775 		zfs_zrele_async(xzp);
776 }
777 
778 static uint64_t
zfs_dirent(znode_t * zp,uint64_t mode)779 zfs_dirent(znode_t *zp, uint64_t mode)
780 {
781 	uint64_t de = zp->z_id;
782 
783 	if (ZTOZSB(zp)->z_version >= ZPL_VERSION_DIRENT_TYPE)
784 		de |= IFTODT(mode) << 60;
785 	return (de);
786 }
787 
788 /*
789  * Link zp into dl.  Can fail in the following cases :
790  * - if zp has been unlinked.
791  * - if the number of entries with the same hash (aka. colliding entries)
792  *    exceed the capacity of a leaf-block of fatzap and splitting of the
793  *    leaf-block does not help.
794  */
795 int
zfs_link_create(zfs_dirlock_t * dl,znode_t * zp,dmu_tx_t * tx,int flag)796 zfs_link_create(zfs_dirlock_t *dl, znode_t *zp, dmu_tx_t *tx, int flag)
797 {
798 	znode_t *dzp = dl->dl_dzp;
799 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
800 	uint64_t value;
801 	int zp_is_dir = S_ISDIR(ZTOI(zp)->i_mode);
802 	sa_bulk_attr_t bulk[6];
803 	uint64_t mtime[2], ctime[2];
804 	uint64_t links;
805 	int count = 0;
806 	int error;
807 
808 	mutex_enter(&zp->z_lock);
809 
810 	if (!(flag & ZRENAMING)) {
811 		if (zp->z_unlinked) {	/* no new links to unlinked zp */
812 			ASSERT(!(flag & (ZNEW | ZEXISTS)));
813 			mutex_exit(&zp->z_lock);
814 			return (SET_ERROR(ENOENT));
815 		}
816 		if (!(flag & ZNEW)) {
817 			/*
818 			 * ZNEW nodes come from zfs_mknode() where the link
819 			 * count has already been initialised
820 			 */
821 			inc_nlink(ZTOI(zp));
822 			links = ZTOI(zp)->i_nlink;
823 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs),
824 			    NULL, &links, sizeof (links));
825 		}
826 	}
827 
828 	value = zfs_dirent(zp, zp->z_mode);
829 	error = zap_add(ZTOZSB(zp)->z_os, dzp->z_id, dl->dl_name, 8, 1,
830 	    &value, tx);
831 
832 	/*
833 	 * zap_add could fail to add the entry if it exceeds the capacity of the
834 	 * leaf-block and zap_leaf_split() failed to help.
835 	 * The caller of this routine is responsible for failing the transaction
836 	 * which will rollback the SA updates done above.
837 	 */
838 	if (error != 0) {
839 		if (!(flag & ZRENAMING) && !(flag & ZNEW))
840 			drop_nlink(ZTOI(zp));
841 		mutex_exit(&zp->z_lock);
842 		return (error);
843 	}
844 
845 	/*
846 	 * If we added a longname activate the SPA_FEATURE_LONGNAME.
847 	 */
848 	if (strlen(dl->dl_name) >= ZAP_MAXNAMELEN) {
849 		dsl_dataset_t *ds = dmu_objset_ds(zfsvfs->z_os);
850 		ds->ds_feature_activation[SPA_FEATURE_LONGNAME] =
851 		    (void *)B_TRUE;
852 	}
853 
854 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_PARENT(zfsvfs), NULL,
855 	    &dzp->z_id, sizeof (dzp->z_id));
856 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
857 	    &zp->z_pflags, sizeof (zp->z_pflags));
858 
859 	if (!(flag & ZNEW)) {
860 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
861 		    ctime, sizeof (ctime));
862 		zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime,
863 		    ctime);
864 		ZFS_PERSIST_SEQ(zp, bulk, count);
865 	}
866 	ASSERT3S(count, <=, ARRAY_SIZE(bulk));
867 	error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
868 	ASSERT0(error);
869 
870 	mutex_exit(&zp->z_lock);
871 
872 	mutex_enter(&dzp->z_lock);
873 	dzp->z_size++;
874 	if (zp_is_dir)
875 		inc_nlink(ZTOI(dzp));
876 	links = ZTOI(dzp)->i_nlink;
877 	count = 0;
878 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
879 	    &dzp->z_size, sizeof (dzp->z_size));
880 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs), NULL,
881 	    &links, sizeof (links));
882 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
883 	    mtime, sizeof (mtime));
884 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
885 	    ctime, sizeof (ctime));
886 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
887 	    &dzp->z_pflags, sizeof (dzp->z_pflags));
888 	zfs_tstamp_update_setup(dzp, CONTENT_MODIFIED, mtime, ctime);
889 	ZFS_PERSIST_SEQ(dzp, bulk, count);
890 	ASSERT3S(count, <=, ARRAY_SIZE(bulk));
891 	error = sa_bulk_update(dzp->z_sa_hdl, bulk, count, tx);
892 	ASSERT0(error);
893 	mutex_exit(&dzp->z_lock);
894 
895 	return (0);
896 }
897 
898 /*
899  * The match type in the code for this function should conform to:
900  *
901  * ------------------------------------------------------------------------
902  * fs type  | z_norm      | lookup type | match type
903  * ---------|-------------|-------------|----------------------------------
904  * CS !norm | 0           |           0 | 0 (exact)
905  * CS  norm | formX       |           0 | MT_NORMALIZE
906  * CI !norm | upper       |   !ZCIEXACT | MT_NORMALIZE
907  * CI !norm | upper       |    ZCIEXACT | MT_NORMALIZE | MT_MATCH_CASE
908  * CI  norm | upper|formX |   !ZCIEXACT | MT_NORMALIZE
909  * CI  norm | upper|formX |    ZCIEXACT | MT_NORMALIZE | MT_MATCH_CASE
910  * CM !norm | upper       |    !ZCILOOK | MT_NORMALIZE | MT_MATCH_CASE
911  * CM !norm | upper       |     ZCILOOK | MT_NORMALIZE
912  * CM  norm | upper|formX |    !ZCILOOK | MT_NORMALIZE | MT_MATCH_CASE
913  * CM  norm | upper|formX |     ZCILOOK | MT_NORMALIZE
914  *
915  * Abbreviations:
916  *    CS = Case Sensitive, CI = Case Insensitive, CM = Case Mixed
917  *    upper = case folding set by fs type on creation (U8_TEXTPREP_TOUPPER)
918  *    formX = unicode normalization form set on fs creation
919  */
920 static int
zfs_dropname(zfs_dirlock_t * dl,znode_t * zp,znode_t * dzp,dmu_tx_t * tx,int flag)921 zfs_dropname(zfs_dirlock_t *dl, znode_t *zp, znode_t *dzp, dmu_tx_t *tx,
922     int flag)
923 {
924 	int error;
925 
926 	if (ZTOZSB(zp)->z_norm) {
927 		matchtype_t mt = MT_NORMALIZE;
928 
929 		if ((ZTOZSB(zp)->z_case == ZFS_CASE_INSENSITIVE &&
930 		    (flag & ZCIEXACT)) ||
931 		    (ZTOZSB(zp)->z_case == ZFS_CASE_MIXED &&
932 		    !(flag & ZCILOOK))) {
933 			mt |= MT_MATCH_CASE;
934 		}
935 
936 		error = zap_remove_norm(ZTOZSB(zp)->z_os, dzp->z_id,
937 		    dl->dl_name, mt, tx);
938 	} else {
939 		error = zap_remove(ZTOZSB(zp)->z_os, dzp->z_id, dl->dl_name,
940 		    tx);
941 	}
942 
943 	return (error);
944 }
945 
946 static int
zfs_drop_nlink_locked(znode_t * zp,dmu_tx_t * tx,boolean_t * unlinkedp)947 zfs_drop_nlink_locked(znode_t *zp, dmu_tx_t *tx, boolean_t *unlinkedp)
948 {
949 	zfsvfs_t	*zfsvfs = ZTOZSB(zp);
950 	int		zp_is_dir = S_ISDIR(ZTOI(zp)->i_mode);
951 	boolean_t	unlinked = B_FALSE;
952 	sa_bulk_attr_t	bulk[4];
953 	uint64_t	mtime[2], ctime[2];
954 	uint64_t	links;
955 	int		count = 0;
956 	int		error;
957 
958 	if (zp_is_dir && !zfs_dirempty(zp))
959 		return (SET_ERROR(ENOTEMPTY));
960 
961 	if (ZTOI(zp)->i_nlink <= zp_is_dir) {
962 		zfs_panic_recover("zfs: link count on %lu is %u, "
963 		    "should be at least %u", zp->z_id,
964 		    (int)ZTOI(zp)->i_nlink, zp_is_dir + 1);
965 		set_nlink(ZTOI(zp), zp_is_dir + 1);
966 	}
967 	drop_nlink(ZTOI(zp));
968 	if (ZTOI(zp)->i_nlink == zp_is_dir) {
969 		zp->z_unlinked = B_TRUE;
970 		clear_nlink(ZTOI(zp));
971 		unlinked = B_TRUE;
972 		/*
973 		 * NFS observers must see nlink=0; advance change_cookie.
974 		 * POSIX permits skipping the ctime stamp at nlink=0, and the
975 		 * znode is destined for reap so persistence would be wasted.
976 		 */
977 		atomic_inc_64(&zp->z_seq);
978 	} else {
979 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs),
980 		    NULL, &ctime, sizeof (ctime));
981 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs),
982 		    NULL, &zp->z_pflags, sizeof (zp->z_pflags));
983 		zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime,
984 		    ctime);
985 		ZFS_PERSIST_SEQ(zp, bulk, count);
986 	}
987 	links = ZTOI(zp)->i_nlink;
988 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs),
989 	    NULL, &links, sizeof (links));
990 	ASSERT3S(count, <=, ARRAY_SIZE(bulk));
991 	error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
992 	ASSERT0(error);
993 
994 	if (unlinkedp != NULL)
995 		*unlinkedp = unlinked;
996 	else if (unlinked)
997 		zfs_unlinked_add(zp, tx);
998 
999 	return (0);
1000 }
1001 
1002 /*
1003  * Forcefully drop an nlink reference from (zp) and mark it for deletion if it
1004  * was the last link. This *must* only be done to znodes which have already
1005  * been zfs_link_destroy()'d with ZRENAMING. This is explicitly only used in
1006  * the error path of zfs_rename(), where we have to correct the nlink count if
1007  * we failed to link the target as well as failing to re-link the original
1008  * znodes.
1009  */
1010 int
zfs_drop_nlink(znode_t * zp,dmu_tx_t * tx,boolean_t * unlinkedp)1011 zfs_drop_nlink(znode_t *zp, dmu_tx_t *tx, boolean_t *unlinkedp)
1012 {
1013 	int error;
1014 
1015 	mutex_enter(&zp->z_lock);
1016 	error = zfs_drop_nlink_locked(zp, tx, unlinkedp);
1017 	mutex_exit(&zp->z_lock);
1018 
1019 	return (error);
1020 }
1021 
1022 /*
1023  * Unlink zp from dl, and mark zp for deletion if this was the last link. Can
1024  * fail if zp is a mount point (EBUSY) or a non-empty directory (ENOTEMPTY).
1025  * If 'unlinkedp' is NULL, we put unlinked znodes on the unlinked list.
1026  * If it's non-NULL, we use it to indicate whether the znode needs deletion,
1027  * and it's the caller's job to do it.
1028  */
1029 int
zfs_link_destroy(zfs_dirlock_t * dl,znode_t * zp,dmu_tx_t * tx,int flag,boolean_t * unlinkedp)1030 zfs_link_destroy(zfs_dirlock_t *dl, znode_t *zp, dmu_tx_t *tx, int flag,
1031     boolean_t *unlinkedp)
1032 {
1033 	znode_t *dzp = dl->dl_dzp;
1034 	zfsvfs_t *zfsvfs = ZTOZSB(dzp);
1035 	int zp_is_dir = S_ISDIR(ZTOI(zp)->i_mode);
1036 	boolean_t unlinked = B_FALSE;
1037 	sa_bulk_attr_t bulk[6];
1038 	uint64_t mtime[2], ctime[2];
1039 	uint64_t links;
1040 	int count = 0;
1041 	int error;
1042 
1043 	if (!(flag & ZRENAMING)) {
1044 		mutex_enter(&zp->z_lock);
1045 
1046 		if (zp_is_dir && !zfs_dirempty(zp)) {
1047 			mutex_exit(&zp->z_lock);
1048 			return (SET_ERROR(ENOTEMPTY));
1049 		}
1050 
1051 		/*
1052 		 * If we get here, we are going to try to remove the object.
1053 		 * First try removing the name from the directory; if that
1054 		 * fails, return the error.
1055 		 */
1056 		error = zfs_dropname(dl, zp, dzp, tx, flag);
1057 		if (error != 0) {
1058 			mutex_exit(&zp->z_lock);
1059 			return (error);
1060 		}
1061 
1062 		/* The only error is !zfs_dirempty() and we checked earlier. */
1063 		error = zfs_drop_nlink_locked(zp, tx, &unlinked);
1064 		ASSERT0(error);
1065 		mutex_exit(&zp->z_lock);
1066 	} else {
1067 		error = zfs_dropname(dl, zp, dzp, tx, flag);
1068 		if (error != 0)
1069 			return (error);
1070 	}
1071 
1072 	mutex_enter(&dzp->z_lock);
1073 	dzp->z_size--;		/* one dirent removed */
1074 	if (zp_is_dir)
1075 		drop_nlink(ZTOI(dzp));	/* ".." link from zp */
1076 	links = ZTOI(dzp)->i_nlink;
1077 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_LINKS(zfsvfs),
1078 	    NULL, &links, sizeof (links));
1079 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs),
1080 	    NULL, &dzp->z_size, sizeof (dzp->z_size));
1081 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs),
1082 	    NULL, ctime, sizeof (ctime));
1083 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs),
1084 	    NULL, mtime, sizeof (mtime));
1085 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs),
1086 	    NULL, &dzp->z_pflags, sizeof (dzp->z_pflags));
1087 	zfs_tstamp_update_setup(dzp, CONTENT_MODIFIED, mtime, ctime);
1088 	ZFS_PERSIST_SEQ(dzp, bulk, count);
1089 	ASSERT3S(count, <=, ARRAY_SIZE(bulk));
1090 	error = sa_bulk_update(dzp->z_sa_hdl, bulk, count, tx);
1091 	ASSERT0(error);
1092 	mutex_exit(&dzp->z_lock);
1093 
1094 	if (unlinkedp != NULL)
1095 		*unlinkedp = unlinked;
1096 	else if (unlinked)
1097 		zfs_unlinked_add(zp, tx);
1098 
1099 	return (0);
1100 }
1101 
1102 /*
1103  * Indicate whether the directory is empty.  Works with or without z_lock
1104  * held, but can only be consider a hint in the latter case.  Returns true
1105  * if only "." and ".." remain and there's no work in progress.
1106  *
1107  * The internal ZAP size, rather than zp->z_size, needs to be checked since
1108  * some consumers (Lustre) do not strictly maintain an accurate SA_ZPL_SIZE.
1109  */
1110 boolean_t
zfs_dirempty(znode_t * dzp)1111 zfs_dirempty(znode_t *dzp)
1112 {
1113 	zfsvfs_t *zfsvfs = ZTOZSB(dzp);
1114 	uint64_t count;
1115 	int error;
1116 
1117 	if (dzp->z_dirlocks != NULL)
1118 		return (B_FALSE);
1119 
1120 	error = zap_count(zfsvfs->z_os, dzp->z_id, &count);
1121 	if (error != 0 || count != 0)
1122 		return (B_FALSE);
1123 
1124 	return (B_TRUE);
1125 }
1126 
1127 int
zfs_make_xattrdir(znode_t * zp,vattr_t * vap,znode_t ** xzpp,cred_t * cr)1128 zfs_make_xattrdir(znode_t *zp, vattr_t *vap, znode_t **xzpp, cred_t *cr)
1129 {
1130 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
1131 	znode_t *xzp;
1132 	dmu_tx_t *tx;
1133 	int error;
1134 	zfs_acl_ids_t acl_ids;
1135 	boolean_t fuid_dirtied;
1136 #ifdef ZFS_DEBUG
1137 	uint64_t parent;
1138 #endif
1139 
1140 	*xzpp = NULL;
1141 
1142 	if ((error = zfs_acl_ids_create(zp, IS_XATTR, vap, cr, NULL,
1143 	    &acl_ids, zfs_init_idmap)) != 0)
1144 		return (error);
1145 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids, zp->z_projid)) {
1146 		zfs_acl_ids_free(&acl_ids);
1147 		return (SET_ERROR(EDQUOT));
1148 	}
1149 
1150 	tx = dmu_tx_create(zfsvfs->z_os);
1151 	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
1152 	    ZFS_SA_BASE_ATTR_SIZE);
1153 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
1154 	dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
1155 	fuid_dirtied = zfsvfs->z_fuid_dirty;
1156 	if (fuid_dirtied)
1157 		zfs_fuid_txhold(zfsvfs, tx);
1158 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
1159 	if (error) {
1160 		zfs_acl_ids_free(&acl_ids);
1161 		dmu_tx_abort(tx);
1162 		return (error);
1163 	}
1164 	zfs_mknode(zp, vap, tx, cr, IS_XATTR, &xzp, &acl_ids);
1165 
1166 	if (fuid_dirtied)
1167 		zfs_fuid_sync(zfsvfs, tx);
1168 
1169 #ifdef ZFS_DEBUG
1170 	error = sa_lookup(xzp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
1171 	    &parent, sizeof (parent));
1172 	ASSERT(error == 0 && parent == zp->z_id);
1173 #endif
1174 
1175 	VERIFY0(sa_update(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs), &xzp->z_id,
1176 	    sizeof (xzp->z_id), tx));
1177 
1178 	if (!zp->z_unlinked)
1179 		zfs_log_create(zfsvfs->z_log, tx, TX_MKXATTR, zp, xzp, "", NULL,
1180 		    acl_ids.z_fuidp, vap);
1181 
1182 	zfs_acl_ids_free(&acl_ids);
1183 	dmu_tx_commit(tx);
1184 
1185 	/* Record that the file now has an xattr directory. */
1186 	zp->z_xattr_dir_absent = B_FALSE;
1187 
1188 	*xzpp = xzp;
1189 
1190 	return (0);
1191 }
1192 
1193 /*
1194  * Return a znode for the extended attribute directory for zp.
1195  * ** If the directory does not already exist, it is created **
1196  *
1197  *	IN:	zp	- znode to obtain attribute directory from
1198  *		cr	- credentials of caller
1199  *		flags	- flags from the VOP_LOOKUP call
1200  *
1201  *	OUT:	xipp	- pointer to extended attribute znode
1202  *
1203  *	RETURN:	0 on success
1204  *		error number on failure
1205  */
1206 int
zfs_get_xattrdir(znode_t * zp,znode_t ** xzpp,cred_t * cr,int flags)1207 zfs_get_xattrdir(znode_t *zp, znode_t **xzpp, cred_t *cr, int flags)
1208 {
1209 	zfsvfs_t	*zfsvfs = ZTOZSB(zp);
1210 	znode_t		*xzp;
1211 	zfs_dirlock_t	*dl;
1212 	vattr_t		va;
1213 	int		error;
1214 
1215 	/*
1216 	 * Fast path for a file already known to have no xattr directory.  When
1217 	 * the caller is not creating one, return ENOENT without taking the ""
1218 	 * ZXATTR dirlock or doing the SA_ZPL_XATTR lookup below, which is pure
1219 	 * overhead when an absent xattr such as security.capability is looked
1220 	 * up on every open.  z_xattr_dir_absent tracks this: it is set when the
1221 	 * lookup finds no directory and cleared when one is found or created.
1222 	 */
1223 	if (!(flags & CREATE_XATTR_DIR) && zp->z_xattr_dir_absent)
1224 		return (SET_ERROR(ENOENT));
1225 top:
1226 	error = zfs_dirent_lock(&dl, zp, "", &xzp, ZXATTR, NULL, NULL);
1227 	if (error)
1228 		return (error);
1229 
1230 	if (xzp != NULL) {
1231 		*xzpp = xzp;
1232 		zp->z_xattr_dir_absent = B_FALSE;
1233 		zfs_dirent_unlock(dl);
1234 		return (0);
1235 	}
1236 
1237 	if (!(flags & CREATE_XATTR_DIR)) {
1238 		zp->z_xattr_dir_absent = B_TRUE;
1239 		zfs_dirent_unlock(dl);
1240 		return (SET_ERROR(ENOENT));
1241 	}
1242 
1243 	if (zfs_is_readonly(zfsvfs)) {
1244 		zfs_dirent_unlock(dl);
1245 		return (SET_ERROR(EROFS));
1246 	}
1247 
1248 	/*
1249 	 * The ability to 'create' files in an attribute
1250 	 * directory comes from the write_xattr permission on the base file.
1251 	 *
1252 	 * The ability to 'search' an attribute directory requires
1253 	 * read_xattr permission on the base file.
1254 	 *
1255 	 * Once in a directory the ability to read/write attributes
1256 	 * is controlled by the permissions on the attribute file.
1257 	 */
1258 	va.va_mask = ATTR_MODE | ATTR_UID | ATTR_GID;
1259 	va.va_mode = S_IFDIR | S_ISVTX | 0777;
1260 	zfs_fuid_map_ids(zp, cr, &va.va_uid, &va.va_gid);
1261 
1262 	va.va_dentry = NULL;
1263 	error = zfs_make_xattrdir(zp, &va, xzpp, cr);
1264 	zfs_dirent_unlock(dl);
1265 
1266 	if (error == ERESTART) {
1267 		/* NB: we already did dmu_tx_wait() if necessary */
1268 		goto top;
1269 	}
1270 
1271 	return (error);
1272 }
1273 
1274 /*
1275  * Decide whether it is okay to remove within a sticky directory.
1276  *
1277  * In sticky directories, write access is not sufficient;
1278  * you can remove entries from a directory only if:
1279  *
1280  *	you own the directory,
1281  *	you own the entry,
1282  *	you have write access to the entry,
1283  *	or you are privileged (checked in secpolicy...).
1284  *
1285  * The function returns 0 if remove access is granted.
1286  */
1287 int
zfs_sticky_remove_access(znode_t * zdp,znode_t * zp,cred_t * cr)1288 zfs_sticky_remove_access(znode_t *zdp, znode_t *zp, cred_t *cr)
1289 {
1290 	uid_t		uid;
1291 	uid_t		downer;
1292 	uid_t		fowner;
1293 	zfsvfs_t	*zfsvfs = ZTOZSB(zdp);
1294 
1295 	if (zfsvfs->z_replay)
1296 		return (0);
1297 
1298 	if ((zdp->z_mode & S_ISVTX) == 0)
1299 		return (0);
1300 
1301 	downer = zfs_fuid_map_id(zfsvfs, KUID_TO_SUID(ZTOI(zdp)->i_uid),
1302 	    cr, ZFS_OWNER);
1303 	fowner = zfs_fuid_map_id(zfsvfs, KUID_TO_SUID(ZTOI(zp)->i_uid),
1304 	    cr, ZFS_OWNER);
1305 
1306 	if ((uid = crgetuid(cr)) == downer || uid == fowner ||
1307 	    zfs_zaccess(zp, ACE_WRITE_DATA, 0, B_FALSE, cr) == 0)
1308 		return (0);
1309 	else
1310 		return (secpolicy_vnode_remove(cr));
1311 }
1312