xref: /freebsd/sys/fs/tmpfs/tmpfs_subr.c (revision 3c91c65a2b999a8d27e99bcc6493de7cf812c948)
1 /*	$NetBSD: tmpfs_subr.c,v 1.35 2007/07/09 21:10:50 ad Exp $	*/
2 
3 /*-
4  * Copyright (c) 2005 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Julio M. Merino Vidal, developed as part of Google's Summer of Code
9  * 2005 program.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 /*
34  * Efficient memory file system supporting functions.
35  */
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38 
39 #include <sys/param.h>
40 #include <sys/fnv_hash.h>
41 #include <sys/namei.h>
42 #include <sys/priv.h>
43 #include <sys/proc.h>
44 #include <sys/stat.h>
45 #include <sys/systm.h>
46 #include <sys/sysctl.h>
47 #include <sys/vnode.h>
48 #include <sys/vmmeter.h>
49 
50 #include <vm/vm.h>
51 #include <vm/vm_param.h>
52 #include <vm/vm_object.h>
53 #include <vm/vm_page.h>
54 #include <vm/vm_pageout.h>
55 #include <vm/vm_pager.h>
56 #include <vm/vm_extern.h>
57 
58 #include <fs/tmpfs/tmpfs.h>
59 #include <fs/tmpfs/tmpfs_fifoops.h>
60 #include <fs/tmpfs/tmpfs_vnops.h>
61 
62 struct tmpfs_dir_cursor {
63 	struct tmpfs_dirent	*tdc_current;
64 	struct tmpfs_dirent	*tdc_tree;
65 };
66 
67 SYSCTL_NODE(_vfs, OID_AUTO, tmpfs, CTLFLAG_RW, 0, "tmpfs file system");
68 
69 static long tmpfs_pages_reserved = TMPFS_PAGES_MINRESERVED;
70 
71 static int
72 sysctl_mem_reserved(SYSCTL_HANDLER_ARGS)
73 {
74 	int error;
75 	long pages, bytes;
76 
77 	pages = *(long *)arg1;
78 	bytes = pages * PAGE_SIZE;
79 
80 	error = sysctl_handle_long(oidp, &bytes, 0, req);
81 	if (error || !req->newptr)
82 		return (error);
83 
84 	pages = bytes / PAGE_SIZE;
85 	if (pages < TMPFS_PAGES_MINRESERVED)
86 		return (EINVAL);
87 
88 	*(long *)arg1 = pages;
89 	return (0);
90 }
91 
92 SYSCTL_PROC(_vfs_tmpfs, OID_AUTO, memory_reserved, CTLTYPE_LONG|CTLFLAG_RW,
93     &tmpfs_pages_reserved, 0, sysctl_mem_reserved, "L",
94     "Amount of available memory and swap below which tmpfs growth stops");
95 
96 static __inline int tmpfs_dirtree_cmp(struct tmpfs_dirent *a,
97     struct tmpfs_dirent *b);
98 RB_PROTOTYPE_STATIC(tmpfs_dir, tmpfs_dirent, uh.td_entries, tmpfs_dirtree_cmp);
99 
100 size_t
101 tmpfs_mem_avail(void)
102 {
103 	vm_ooffset_t avail;
104 
105 	avail = swap_pager_avail + cnt.v_free_count + cnt.v_cache_count -
106 	    tmpfs_pages_reserved;
107 	if (__predict_false(avail < 0))
108 		avail = 0;
109 	return (avail);
110 }
111 
112 size_t
113 tmpfs_pages_used(struct tmpfs_mount *tmp)
114 {
115 	const size_t node_size = sizeof(struct tmpfs_node) +
116 	    sizeof(struct tmpfs_dirent);
117 	size_t meta_pages;
118 
119 	meta_pages = howmany((uintmax_t)tmp->tm_nodes_inuse * node_size,
120 	    PAGE_SIZE);
121 	return (meta_pages + tmp->tm_pages_used);
122 }
123 
124 static size_t
125 tmpfs_pages_check_avail(struct tmpfs_mount *tmp, size_t req_pages)
126 {
127 	if (tmpfs_mem_avail() < req_pages)
128 		return (0);
129 
130 	if (tmp->tm_pages_max != SIZE_MAX &&
131 	    tmp->tm_pages_max < req_pages + tmpfs_pages_used(tmp))
132 			return (0);
133 
134 	return (1);
135 }
136 
137 /* --------------------------------------------------------------------- */
138 
139 /*
140  * Allocates a new node of type 'type' inside the 'tmp' mount point, with
141  * its owner set to 'uid', its group to 'gid' and its mode set to 'mode',
142  * using the credentials of the process 'p'.
143  *
144  * If the node type is set to 'VDIR', then the parent parameter must point
145  * to the parent directory of the node being created.  It may only be NULL
146  * while allocating the root node.
147  *
148  * If the node type is set to 'VBLK' or 'VCHR', then the rdev parameter
149  * specifies the device the node represents.
150  *
151  * If the node type is set to 'VLNK', then the parameter target specifies
152  * the file name of the target file for the symbolic link that is being
153  * created.
154  *
155  * Note that new nodes are retrieved from the available list if it has
156  * items or, if it is empty, from the node pool as long as there is enough
157  * space to create them.
158  *
159  * Returns zero on success or an appropriate error code on failure.
160  */
161 int
162 tmpfs_alloc_node(struct tmpfs_mount *tmp, enum vtype type,
163     uid_t uid, gid_t gid, mode_t mode, struct tmpfs_node *parent,
164     char *target, dev_t rdev, struct tmpfs_node **node)
165 {
166 	struct tmpfs_node *nnode;
167 
168 	/* If the root directory of the 'tmp' file system is not yet
169 	 * allocated, this must be the request to do it. */
170 	MPASS(IMPLIES(tmp->tm_root == NULL, parent == NULL && type == VDIR));
171 
172 	MPASS(IFF(type == VLNK, target != NULL));
173 	MPASS(IFF(type == VBLK || type == VCHR, rdev != VNOVAL));
174 
175 	if (tmp->tm_nodes_inuse >= tmp->tm_nodes_max)
176 		return (ENOSPC);
177 	if (tmpfs_pages_check_avail(tmp, 1) == 0)
178 		return (ENOSPC);
179 
180 	nnode = (struct tmpfs_node *)uma_zalloc_arg(
181 				tmp->tm_node_pool, tmp, M_WAITOK);
182 
183 	/* Generic initialization. */
184 	nnode->tn_type = type;
185 	vfs_timestamp(&nnode->tn_atime);
186 	nnode->tn_birthtime = nnode->tn_ctime = nnode->tn_mtime =
187 	    nnode->tn_atime;
188 	nnode->tn_uid = uid;
189 	nnode->tn_gid = gid;
190 	nnode->tn_mode = mode;
191 	nnode->tn_id = alloc_unr(tmp->tm_ino_unr);
192 
193 	/* Type-specific initialization. */
194 	switch (nnode->tn_type) {
195 	case VBLK:
196 	case VCHR:
197 		nnode->tn_rdev = rdev;
198 		break;
199 
200 	case VDIR:
201 		RB_INIT(&nnode->tn_dir.tn_dirhead);
202 		LIST_INIT(&nnode->tn_dir.tn_dupindex);
203 		MPASS(parent != nnode);
204 		MPASS(IMPLIES(parent == NULL, tmp->tm_root == NULL));
205 		nnode->tn_dir.tn_parent = (parent == NULL) ? nnode : parent;
206 		nnode->tn_dir.tn_readdir_lastn = 0;
207 		nnode->tn_dir.tn_readdir_lastp = NULL;
208 		nnode->tn_links++;
209 		TMPFS_NODE_LOCK(nnode->tn_dir.tn_parent);
210 		nnode->tn_dir.tn_parent->tn_links++;
211 		TMPFS_NODE_UNLOCK(nnode->tn_dir.tn_parent);
212 		break;
213 
214 	case VFIFO:
215 		/* FALLTHROUGH */
216 	case VSOCK:
217 		break;
218 
219 	case VLNK:
220 		MPASS(strlen(target) < MAXPATHLEN);
221 		nnode->tn_size = strlen(target);
222 		nnode->tn_link = malloc(nnode->tn_size, M_TMPFSNAME,
223 		    M_WAITOK);
224 		memcpy(nnode->tn_link, target, nnode->tn_size);
225 		break;
226 
227 	case VREG:
228 		nnode->tn_reg.tn_aobj =
229 		    vm_pager_allocate(OBJT_SWAP, NULL, 0, VM_PROT_DEFAULT, 0,
230 			NULL /* XXXKIB - tmpfs needs swap reservation */);
231 		break;
232 
233 	default:
234 		panic("tmpfs_alloc_node: type %p %d", nnode, (int)nnode->tn_type);
235 	}
236 
237 	TMPFS_LOCK(tmp);
238 	LIST_INSERT_HEAD(&tmp->tm_nodes_used, nnode, tn_entries);
239 	tmp->tm_nodes_inuse++;
240 	TMPFS_UNLOCK(tmp);
241 
242 	*node = nnode;
243 	return 0;
244 }
245 
246 /* --------------------------------------------------------------------- */
247 
248 /*
249  * Destroys the node pointed to by node from the file system 'tmp'.
250  * If the node does not belong to the given mount point, the results are
251  * unpredicted.
252  *
253  * If the node references a directory; no entries are allowed because
254  * their removal could need a recursive algorithm, something forbidden in
255  * kernel space.  Furthermore, there is not need to provide such
256  * functionality (recursive removal) because the only primitives offered
257  * to the user are the removal of empty directories and the deletion of
258  * individual files.
259  *
260  * Note that nodes are not really deleted; in fact, when a node has been
261  * allocated, it cannot be deleted during the whole life of the file
262  * system.  Instead, they are moved to the available list and remain there
263  * until reused.
264  */
265 void
266 tmpfs_free_node(struct tmpfs_mount *tmp, struct tmpfs_node *node)
267 {
268 	vm_object_t uobj;
269 
270 #ifdef INVARIANTS
271 	TMPFS_NODE_LOCK(node);
272 	MPASS(node->tn_vnode == NULL);
273 	MPASS((node->tn_vpstate & TMPFS_VNODE_ALLOCATING) == 0);
274 	TMPFS_NODE_UNLOCK(node);
275 #endif
276 
277 	TMPFS_LOCK(tmp);
278 	LIST_REMOVE(node, tn_entries);
279 	tmp->tm_nodes_inuse--;
280 	TMPFS_UNLOCK(tmp);
281 
282 	switch (node->tn_type) {
283 	case VNON:
284 		/* Do not do anything.  VNON is provided to let the
285 		 * allocation routine clean itself easily by avoiding
286 		 * duplicating code in it. */
287 		/* FALLTHROUGH */
288 	case VBLK:
289 		/* FALLTHROUGH */
290 	case VCHR:
291 		/* FALLTHROUGH */
292 	case VDIR:
293 		/* FALLTHROUGH */
294 	case VFIFO:
295 		/* FALLTHROUGH */
296 	case VSOCK:
297 		break;
298 
299 	case VLNK:
300 		free(node->tn_link, M_TMPFSNAME);
301 		break;
302 
303 	case VREG:
304 		uobj = node->tn_reg.tn_aobj;
305 		if (uobj != NULL) {
306 			TMPFS_LOCK(tmp);
307 			tmp->tm_pages_used -= uobj->size;
308 			TMPFS_UNLOCK(tmp);
309 			vm_object_deallocate(uobj);
310 		}
311 		break;
312 
313 	default:
314 		panic("tmpfs_free_node: type %p %d", node, (int)node->tn_type);
315 	}
316 
317 	free_unr(tmp->tm_ino_unr, node->tn_id);
318 	uma_zfree(tmp->tm_node_pool, node);
319 }
320 
321 /* --------------------------------------------------------------------- */
322 
323 static __inline uint32_t
324 tmpfs_dirent_hash(const char *name, u_int len)
325 {
326 	uint32_t hash;
327 
328 	hash = fnv_32_buf(name, len, FNV1_32_INIT + len) & TMPFS_DIRCOOKIE_MASK;
329 #ifdef TMPFS_DEBUG_DIRCOOKIE_DUP
330 	hash &= 0xf;
331 #endif
332 	if (hash < TMPFS_DIRCOOKIE_MIN)
333 		hash += TMPFS_DIRCOOKIE_MIN;
334 
335 	return (hash);
336 }
337 
338 static __inline off_t
339 tmpfs_dirent_cookie(struct tmpfs_dirent *de)
340 {
341 	MPASS(de->td_cookie >= TMPFS_DIRCOOKIE_MIN);
342 
343 	return (de->td_cookie);
344 }
345 
346 static __inline boolean_t
347 tmpfs_dirent_dup(struct tmpfs_dirent *de)
348 {
349 	return ((de->td_cookie & TMPFS_DIRCOOKIE_DUP) != 0);
350 }
351 
352 static __inline boolean_t
353 tmpfs_dirent_duphead(struct tmpfs_dirent *de)
354 {
355 	return ((de->td_cookie & TMPFS_DIRCOOKIE_DUPHEAD) != 0);
356 }
357 
358 void
359 tmpfs_dirent_init(struct tmpfs_dirent *de, const char *name, u_int namelen)
360 {
361 	de->td_hash = de->td_cookie = tmpfs_dirent_hash(name, namelen);
362 	memcpy(de->ud.td_name, name, namelen);
363 	de->td_namelen = namelen;
364 }
365 
366 /*
367  * Allocates a new directory entry for the node node with a name of name.
368  * The new directory entry is returned in *de.
369  *
370  * The link count of node is increased by one to reflect the new object
371  * referencing it.
372  *
373  * Returns zero on success or an appropriate error code on failure.
374  */
375 int
376 tmpfs_alloc_dirent(struct tmpfs_mount *tmp, struct tmpfs_node *node,
377     const char *name, u_int len, struct tmpfs_dirent **de)
378 {
379 	struct tmpfs_dirent *nde;
380 
381 	nde = uma_zalloc(tmp->tm_dirent_pool, M_WAITOK);
382 	nde->td_node = node;
383 	if (name != NULL) {
384 		nde->ud.td_name = malloc(len, M_TMPFSNAME, M_WAITOK);
385 		tmpfs_dirent_init(nde, name, len);
386 	} else
387 		nde->td_namelen = 0;
388 	if (node != NULL)
389 		node->tn_links++;
390 
391 	*de = nde;
392 
393 	return 0;
394 }
395 
396 /* --------------------------------------------------------------------- */
397 
398 /*
399  * Frees a directory entry.  It is the caller's responsibility to destroy
400  * the node referenced by it if needed.
401  *
402  * The link count of node is decreased by one to reflect the removal of an
403  * object that referenced it.  This only happens if 'node_exists' is true;
404  * otherwise the function will not access the node referred to by the
405  * directory entry, as it may already have been released from the outside.
406  */
407 void
408 tmpfs_free_dirent(struct tmpfs_mount *tmp, struct tmpfs_dirent *de)
409 {
410 	struct tmpfs_node *node;
411 
412 	node = de->td_node;
413 	if (node != NULL) {
414 		MPASS(node->tn_links > 0);
415 		node->tn_links--;
416 	}
417 	if (!tmpfs_dirent_duphead(de) && de->ud.td_name != NULL)
418 		free(de->ud.td_name, M_TMPFSNAME);
419 	uma_zfree(tmp->tm_dirent_pool, de);
420 }
421 
422 /* --------------------------------------------------------------------- */
423 
424 /*
425  * Allocates a new vnode for the node node or returns a new reference to
426  * an existing one if the node had already a vnode referencing it.  The
427  * resulting locked vnode is returned in *vpp.
428  *
429  * Returns zero on success or an appropriate error code on failure.
430  */
431 int
432 tmpfs_alloc_vp(struct mount *mp, struct tmpfs_node *node, int lkflag,
433     struct vnode **vpp)
434 {
435 	int error = 0;
436 	struct vnode *vp;
437 
438 loop:
439 	TMPFS_NODE_LOCK(node);
440 	if ((vp = node->tn_vnode) != NULL) {
441 		MPASS((node->tn_vpstate & TMPFS_VNODE_DOOMED) == 0);
442 		VI_LOCK(vp);
443 		TMPFS_NODE_UNLOCK(node);
444 		error = vget(vp, lkflag | LK_INTERLOCK, curthread);
445 		if (error != 0) {
446 			vp = NULL;
447 			goto out;
448 		}
449 
450 		/*
451 		 * Make sure the vnode is still there after
452 		 * getting the interlock to avoid racing a free.
453 		 */
454 		if (node->tn_vnode == NULL || node->tn_vnode != vp) {
455 			vput(vp);
456 			goto loop;
457 		}
458 
459 		goto out;
460 	}
461 
462 	if ((node->tn_vpstate & TMPFS_VNODE_DOOMED) ||
463 	    (node->tn_type == VDIR && node->tn_dir.tn_parent == NULL)) {
464 		TMPFS_NODE_UNLOCK(node);
465 		error = ENOENT;
466 		vp = NULL;
467 		goto out;
468 	}
469 
470 	/*
471 	 * otherwise lock the vp list while we call getnewvnode
472 	 * since that can block.
473 	 */
474 	if (node->tn_vpstate & TMPFS_VNODE_ALLOCATING) {
475 		node->tn_vpstate |= TMPFS_VNODE_WANT;
476 		error = msleep((caddr_t) &node->tn_vpstate,
477 		    TMPFS_NODE_MTX(node), PDROP | PCATCH,
478 		    "tmpfs_alloc_vp", 0);
479 		if (error)
480 			return error;
481 
482 		goto loop;
483 	} else
484 		node->tn_vpstate |= TMPFS_VNODE_ALLOCATING;
485 
486 	TMPFS_NODE_UNLOCK(node);
487 
488 	/* Get a new vnode and associate it with our node. */
489 	error = getnewvnode("tmpfs", mp, &tmpfs_vnodeop_entries, &vp);
490 	if (error != 0)
491 		goto unlock;
492 	MPASS(vp != NULL);
493 
494 	(void) vn_lock(vp, lkflag | LK_RETRY);
495 
496 	vp->v_data = node;
497 	vp->v_type = node->tn_type;
498 
499 	/* Type-specific initialization. */
500 	switch (node->tn_type) {
501 	case VBLK:
502 		/* FALLTHROUGH */
503 	case VCHR:
504 		/* FALLTHROUGH */
505 	case VLNK:
506 		/* FALLTHROUGH */
507 	case VREG:
508 		/* FALLTHROUGH */
509 	case VSOCK:
510 		break;
511 	case VFIFO:
512 		vp->v_op = &tmpfs_fifoop_entries;
513 		break;
514 	case VDIR:
515 		MPASS(node->tn_dir.tn_parent != NULL);
516 		if (node->tn_dir.tn_parent == node)
517 			vp->v_vflag |= VV_ROOT;
518 		break;
519 
520 	default:
521 		panic("tmpfs_alloc_vp: type %p %d", node, (int)node->tn_type);
522 	}
523 
524 	vnode_pager_setsize(vp, node->tn_size);
525 	error = insmntque(vp, mp);
526 	if (error)
527 		vp = NULL;
528 
529 unlock:
530 	TMPFS_NODE_LOCK(node);
531 
532 	MPASS(node->tn_vpstate & TMPFS_VNODE_ALLOCATING);
533 	node->tn_vpstate &= ~TMPFS_VNODE_ALLOCATING;
534 	node->tn_vnode = vp;
535 
536 	if (node->tn_vpstate & TMPFS_VNODE_WANT) {
537 		node->tn_vpstate &= ~TMPFS_VNODE_WANT;
538 		TMPFS_NODE_UNLOCK(node);
539 		wakeup((caddr_t) &node->tn_vpstate);
540 	} else
541 		TMPFS_NODE_UNLOCK(node);
542 
543 out:
544 	*vpp = vp;
545 
546 #ifdef INVARIANTS
547 	if (error == 0) {
548 		MPASS(*vpp != NULL && VOP_ISLOCKED(*vpp));
549 		TMPFS_NODE_LOCK(node);
550 		MPASS(*vpp == node->tn_vnode);
551 		TMPFS_NODE_UNLOCK(node);
552 	}
553 #endif
554 
555 	return error;
556 }
557 
558 /* --------------------------------------------------------------------- */
559 
560 /*
561  * Destroys the association between the vnode vp and the node it
562  * references.
563  */
564 void
565 tmpfs_free_vp(struct vnode *vp)
566 {
567 	struct tmpfs_node *node;
568 
569 	node = VP_TO_TMPFS_NODE(vp);
570 
571 	mtx_assert(TMPFS_NODE_MTX(node), MA_OWNED);
572 	node->tn_vnode = NULL;
573 	vp->v_data = NULL;
574 }
575 
576 /* --------------------------------------------------------------------- */
577 
578 /*
579  * Allocates a new file of type 'type' and adds it to the parent directory
580  * 'dvp'; this addition is done using the component name given in 'cnp'.
581  * The ownership of the new file is automatically assigned based on the
582  * credentials of the caller (through 'cnp'), the group is set based on
583  * the parent directory and the mode is determined from the 'vap' argument.
584  * If successful, *vpp holds a vnode to the newly created file and zero
585  * is returned.  Otherwise *vpp is NULL and the function returns an
586  * appropriate error code.
587  */
588 int
589 tmpfs_alloc_file(struct vnode *dvp, struct vnode **vpp, struct vattr *vap,
590     struct componentname *cnp, char *target)
591 {
592 	int error;
593 	struct tmpfs_dirent *de;
594 	struct tmpfs_mount *tmp;
595 	struct tmpfs_node *dnode;
596 	struct tmpfs_node *node;
597 	struct tmpfs_node *parent;
598 
599 	MPASS(VOP_ISLOCKED(dvp));
600 	MPASS(cnp->cn_flags & HASBUF);
601 
602 	tmp = VFS_TO_TMPFS(dvp->v_mount);
603 	dnode = VP_TO_TMPFS_DIR(dvp);
604 	*vpp = NULL;
605 
606 	/* If the entry we are creating is a directory, we cannot overflow
607 	 * the number of links of its parent, because it will get a new
608 	 * link. */
609 	if (vap->va_type == VDIR) {
610 		/* Ensure that we do not overflow the maximum number of links
611 		 * imposed by the system. */
612 		MPASS(dnode->tn_links <= LINK_MAX);
613 		if (dnode->tn_links == LINK_MAX) {
614 			error = EMLINK;
615 			goto out;
616 		}
617 
618 		parent = dnode;
619 		MPASS(parent != NULL);
620 	} else
621 		parent = NULL;
622 
623 	/* Allocate a node that represents the new file. */
624 	error = tmpfs_alloc_node(tmp, vap->va_type, cnp->cn_cred->cr_uid,
625 	    dnode->tn_gid, vap->va_mode, parent, target, vap->va_rdev, &node);
626 	if (error != 0)
627 		goto out;
628 
629 	/* Allocate a directory entry that points to the new file. */
630 	error = tmpfs_alloc_dirent(tmp, node, cnp->cn_nameptr, cnp->cn_namelen,
631 	    &de);
632 	if (error != 0) {
633 		tmpfs_free_node(tmp, node);
634 		goto out;
635 	}
636 
637 	/* Allocate a vnode for the new file. */
638 	error = tmpfs_alloc_vp(dvp->v_mount, node, LK_EXCLUSIVE, vpp);
639 	if (error != 0) {
640 		tmpfs_free_dirent(tmp, de);
641 		tmpfs_free_node(tmp, node);
642 		goto out;
643 	}
644 
645 	/* Now that all required items are allocated, we can proceed to
646 	 * insert the new node into the directory, an operation that
647 	 * cannot fail. */
648 	if (cnp->cn_flags & ISWHITEOUT)
649 		tmpfs_dir_whiteout_remove(dvp, cnp);
650 	tmpfs_dir_attach(dvp, de);
651 
652 out:
653 
654 	return error;
655 }
656 
657 /* --------------------------------------------------------------------- */
658 
659 static struct tmpfs_dirent *
660 tmpfs_dir_first(struct tmpfs_node *dnode, struct tmpfs_dir_cursor *dc)
661 {
662 	struct tmpfs_dirent *de;
663 
664 	de = RB_MIN(tmpfs_dir, &dnode->tn_dir.tn_dirhead);
665 	dc->tdc_tree = de;
666 	if (de != NULL && tmpfs_dirent_duphead(de))
667 		de = LIST_FIRST(&de->ud.td_duphead);
668 	dc->tdc_current = de;
669 
670 	return (dc->tdc_current);
671 }
672 
673 static struct tmpfs_dirent *
674 tmpfs_dir_next(struct tmpfs_node *dnode, struct tmpfs_dir_cursor *dc)
675 {
676 	struct tmpfs_dirent *de;
677 
678 	MPASS(dc->tdc_tree != NULL);
679 	if (tmpfs_dirent_dup(dc->tdc_current)) {
680 		dc->tdc_current = LIST_NEXT(dc->tdc_current, uh.td_dup.entries);
681 		if (dc->tdc_current != NULL)
682 			return (dc->tdc_current);
683 	}
684 	dc->tdc_tree = dc->tdc_current = RB_NEXT(tmpfs_dir,
685 	    &dnode->tn_dir.tn_dirhead, dc->tdc_tree);
686 	if ((de = dc->tdc_current) != NULL && tmpfs_dirent_duphead(de)) {
687 		dc->tdc_current = LIST_FIRST(&de->ud.td_duphead);
688 		MPASS(dc->tdc_current != NULL);
689 	}
690 
691 	return (dc->tdc_current);
692 }
693 
694 /* Lookup directory entry in RB-Tree. Function may return duphead entry. */
695 static struct tmpfs_dirent *
696 tmpfs_dir_xlookup_hash(struct tmpfs_node *dnode, uint32_t hash)
697 {
698 	struct tmpfs_dirent *de, dekey;
699 
700 	dekey.td_hash = hash;
701 	de = RB_FIND(tmpfs_dir, &dnode->tn_dir.tn_dirhead, &dekey);
702 	return (de);
703 }
704 
705 /* Lookup directory entry by cookie, initialize directory cursor accordingly. */
706 static struct tmpfs_dirent *
707 tmpfs_dir_lookup_cookie(struct tmpfs_node *node, off_t cookie,
708     struct tmpfs_dir_cursor *dc)
709 {
710 	struct tmpfs_dir *dirhead = &node->tn_dir.tn_dirhead;
711 	struct tmpfs_dirent *de, dekey;
712 
713 	MPASS(cookie >= TMPFS_DIRCOOKIE_MIN);
714 
715 	if (cookie == node->tn_dir.tn_readdir_lastn &&
716 	    (de = node->tn_dir.tn_readdir_lastp) != NULL) {
717 		/* Protect against possible race, tn_readdir_last[pn]
718 		 * may be updated with only shared vnode lock held. */
719 		if (cookie == tmpfs_dirent_cookie(de))
720 			goto out;
721 	}
722 
723 	if ((cookie & TMPFS_DIRCOOKIE_DUP) != 0) {
724 		LIST_FOREACH(de, &node->tn_dir.tn_dupindex,
725 		    uh.td_dup.index_entries) {
726 			MPASS(tmpfs_dirent_dup(de));
727 			if (de->td_cookie == cookie)
728 				goto out;
729 			/* dupindex list is sorted. */
730 			if (de->td_cookie < cookie) {
731 				de = NULL;
732 				goto out;
733 			}
734 		}
735 		MPASS(de == NULL);
736 		goto out;
737 	}
738 
739 	MPASS((cookie & TMPFS_DIRCOOKIE_MASK) == cookie);
740 	dekey.td_hash = cookie;
741 	/* Recover if direntry for cookie was removed */
742 	de = RB_NFIND(tmpfs_dir, dirhead, &dekey);
743 	dc->tdc_tree = de;
744 	dc->tdc_current = de;
745 	if (de != NULL && tmpfs_dirent_duphead(de)) {
746 		dc->tdc_current = LIST_FIRST(&de->ud.td_duphead);
747 		MPASS(dc->tdc_current != NULL);
748 	}
749 	return (dc->tdc_current);
750 
751 out:
752 	dc->tdc_tree = de;
753 	dc->tdc_current = de;
754 	if (de != NULL && tmpfs_dirent_dup(de))
755 		dc->tdc_tree = tmpfs_dir_xlookup_hash(node,
756 		    de->td_hash);
757 	return (dc->tdc_current);
758 }
759 
760 /*
761  * Looks for a directory entry in the directory represented by node.
762  * 'cnp' describes the name of the entry to look for.  Note that the .
763  * and .. components are not allowed as they do not physically exist
764  * within directories.
765  *
766  * Returns a pointer to the entry when found, otherwise NULL.
767  */
768 struct tmpfs_dirent *
769 tmpfs_dir_lookup(struct tmpfs_node *node, struct tmpfs_node *f,
770     struct componentname *cnp)
771 {
772 	struct tmpfs_dir_duphead *duphead;
773 	struct tmpfs_dirent *de;
774 	uint32_t hash;
775 
776 	MPASS(IMPLIES(cnp->cn_namelen == 1, cnp->cn_nameptr[0] != '.'));
777 	MPASS(IMPLIES(cnp->cn_namelen == 2, !(cnp->cn_nameptr[0] == '.' &&
778 	    cnp->cn_nameptr[1] == '.')));
779 	TMPFS_VALIDATE_DIR(node);
780 
781 	hash = tmpfs_dirent_hash(cnp->cn_nameptr, cnp->cn_namelen);
782 	de = tmpfs_dir_xlookup_hash(node, hash);
783 	if (de != NULL && tmpfs_dirent_duphead(de)) {
784 		duphead = &de->ud.td_duphead;
785 		LIST_FOREACH(de, duphead, uh.td_dup.entries) {
786 			if (TMPFS_DIRENT_MATCHES(de, cnp->cn_nameptr,
787 			    cnp->cn_namelen))
788 				break;
789 		}
790 	} else if (de != NULL) {
791 		if (!TMPFS_DIRENT_MATCHES(de, cnp->cn_nameptr,
792 		    cnp->cn_namelen))
793 			de = NULL;
794 	}
795 	if (de != NULL && f != NULL && de->td_node != f)
796 		de = NULL;
797 
798 	return (de);
799 }
800 
801 /*
802  * Attach duplicate-cookie directory entry nde to dnode and insert to dupindex
803  * list, allocate new cookie value.
804  */
805 static void
806 tmpfs_dir_attach_dup(struct tmpfs_node *dnode,
807     struct tmpfs_dir_duphead *duphead, struct tmpfs_dirent *nde)
808 {
809 	struct tmpfs_dir_duphead *dupindex;
810 	struct tmpfs_dirent *de, *pde;
811 
812 	dupindex = &dnode->tn_dir.tn_dupindex;
813 	de = LIST_FIRST(dupindex);
814 	if (de == NULL || de->td_cookie < TMPFS_DIRCOOKIE_DUP_MAX) {
815 		if (de == NULL)
816 			nde->td_cookie = TMPFS_DIRCOOKIE_DUP_MIN;
817 		else
818 			nde->td_cookie = de->td_cookie + 1;
819 		MPASS(tmpfs_dirent_dup(nde));
820 		LIST_INSERT_HEAD(dupindex, nde, uh.td_dup.index_entries);
821 		LIST_INSERT_HEAD(duphead, nde, uh.td_dup.entries);
822 		return;
823 	}
824 
825 	/*
826 	 * Cookie numbers are near exhaustion. Scan dupindex list for unused
827 	 * numbers. dupindex list is sorted in descending order. Keep it so
828 	 * after inserting nde.
829 	 */
830 	while (1) {
831 		pde = de;
832 		de = LIST_NEXT(de, uh.td_dup.index_entries);
833 		if (de == NULL && pde->td_cookie != TMPFS_DIRCOOKIE_DUP_MIN) {
834 			/*
835 			 * Last element of the index doesn't have minimal cookie
836 			 * value, use it.
837 			 */
838 			nde->td_cookie = TMPFS_DIRCOOKIE_DUP_MIN;
839 			LIST_INSERT_AFTER(pde, nde, uh.td_dup.index_entries);
840 			LIST_INSERT_HEAD(duphead, nde, uh.td_dup.entries);
841 			return;
842 		} else if (de == NULL) {
843 			/*
844 			 * We are so lucky have 2^30 hash duplicates in single
845 			 * directory :) Return largest possible cookie value.
846 			 * It should be fine except possible issues with
847 			 * VOP_READDIR restart.
848 			 */
849 			nde->td_cookie = TMPFS_DIRCOOKIE_DUP_MAX;
850 			LIST_INSERT_HEAD(dupindex, nde,
851 			    uh.td_dup.index_entries);
852 			LIST_INSERT_HEAD(duphead, nde, uh.td_dup.entries);
853 			return;
854 		}
855 		if (de->td_cookie + 1 == pde->td_cookie ||
856 		    de->td_cookie >= TMPFS_DIRCOOKIE_DUP_MAX)
857 			continue;	/* No hole or invalid cookie. */
858 		nde->td_cookie = de->td_cookie + 1;
859 		MPASS(tmpfs_dirent_dup(nde));
860 		MPASS(pde->td_cookie > nde->td_cookie);
861 		MPASS(nde->td_cookie > de->td_cookie);
862 		LIST_INSERT_BEFORE(de, nde, uh.td_dup.index_entries);
863 		LIST_INSERT_HEAD(duphead, nde, uh.td_dup.entries);
864 		return;
865 	};
866 }
867 
868 /*
869  * Attaches the directory entry de to the directory represented by vp.
870  * Note that this does not change the link count of the node pointed by
871  * the directory entry, as this is done by tmpfs_alloc_dirent.
872  */
873 void
874 tmpfs_dir_attach(struct vnode *vp, struct tmpfs_dirent *de)
875 {
876 	struct tmpfs_node *dnode;
877 	struct tmpfs_dirent *xde, *nde;
878 
879 	ASSERT_VOP_ELOCKED(vp, __func__);
880 	MPASS(de->td_namelen > 0);
881 	MPASS(de->td_hash >= TMPFS_DIRCOOKIE_MIN);
882 	MPASS(de->td_cookie == de->td_hash);
883 
884 	dnode = VP_TO_TMPFS_DIR(vp);
885 	dnode->tn_dir.tn_readdir_lastn = 0;
886 	dnode->tn_dir.tn_readdir_lastp = NULL;
887 
888 	MPASS(!tmpfs_dirent_dup(de));
889 	xde = RB_INSERT(tmpfs_dir, &dnode->tn_dir.tn_dirhead, de);
890 	if (xde != NULL && tmpfs_dirent_duphead(xde))
891 		tmpfs_dir_attach_dup(dnode, &xde->ud.td_duphead, de);
892 	else if (xde != NULL) {
893 		/*
894 		 * Allocate new duphead. Swap xde with duphead to avoid
895 		 * adding/removing elements with the same hash.
896 		 */
897 		MPASS(!tmpfs_dirent_dup(xde));
898 		tmpfs_alloc_dirent(VFS_TO_TMPFS(vp->v_mount), NULL, NULL, 0,
899 		    &nde);
900 		/* *nde = *xde; XXX gcc 4.2.1 may generate invalid code. */
901 		memcpy(nde, xde, sizeof(*xde));
902 		xde->td_cookie |= TMPFS_DIRCOOKIE_DUPHEAD;
903 		LIST_INIT(&xde->ud.td_duphead);
904 		xde->td_namelen = 0;
905 		xde->td_node = NULL;
906 		tmpfs_dir_attach_dup(dnode, &xde->ud.td_duphead, nde);
907 		tmpfs_dir_attach_dup(dnode, &xde->ud.td_duphead, de);
908 	}
909 	dnode->tn_size += sizeof(struct tmpfs_dirent);
910 	dnode->tn_status |= TMPFS_NODE_ACCESSED | TMPFS_NODE_CHANGED | \
911 	    TMPFS_NODE_MODIFIED;
912 }
913 
914 /* --------------------------------------------------------------------- */
915 
916 /*
917  * Detaches the directory entry de from the directory represented by vp.
918  * Note that this does not change the link count of the node pointed by
919  * the directory entry, as this is done by tmpfs_free_dirent.
920  */
921 void
922 tmpfs_dir_detach(struct vnode *vp, struct tmpfs_dirent *de)
923 {
924 	struct tmpfs_mount *tmp;
925 	struct tmpfs_dir *head;
926 	struct tmpfs_node *dnode;
927 	struct tmpfs_dirent *xde;
928 
929 	ASSERT_VOP_ELOCKED(vp, __func__);
930 
931 	dnode = VP_TO_TMPFS_DIR(vp);
932 	head = &dnode->tn_dir.tn_dirhead;
933 	dnode->tn_dir.tn_readdir_lastn = 0;
934 	dnode->tn_dir.tn_readdir_lastp = NULL;
935 
936 	if (tmpfs_dirent_dup(de)) {
937 		/* Remove duphead if de was last entry. */
938 		if (LIST_NEXT(de, uh.td_dup.entries) == NULL) {
939 			xde = tmpfs_dir_xlookup_hash(dnode, de->td_hash);
940 			MPASS(tmpfs_dirent_duphead(xde));
941 		} else
942 			xde = NULL;
943 		LIST_REMOVE(de, uh.td_dup.entries);
944 		LIST_REMOVE(de, uh.td_dup.index_entries);
945 		if (xde != NULL) {
946 			if (LIST_EMPTY(&xde->ud.td_duphead)) {
947 				RB_REMOVE(tmpfs_dir, head, xde);
948 				tmp = VFS_TO_TMPFS(vp->v_mount);
949 				MPASS(xde->td_node == NULL);
950 				tmpfs_free_dirent(tmp, xde);
951 			}
952 		}
953 	} else
954 		RB_REMOVE(tmpfs_dir, head, de);
955 
956 	dnode->tn_size -= sizeof(struct tmpfs_dirent);
957 	dnode->tn_status |= TMPFS_NODE_ACCESSED | TMPFS_NODE_CHANGED | \
958 	    TMPFS_NODE_MODIFIED;
959 }
960 
961 void
962 tmpfs_dir_destroy(struct tmpfs_mount *tmp, struct tmpfs_node *dnode)
963 {
964 	struct tmpfs_dirent *de, *dde, *nde;
965 
966 	RB_FOREACH_SAFE(de, tmpfs_dir, &dnode->tn_dir.tn_dirhead, nde) {
967 		RB_REMOVE(tmpfs_dir, &dnode->tn_dir.tn_dirhead, de);
968 		/* Node may already be destroyed. */
969 		de->td_node = NULL;
970 		if (tmpfs_dirent_duphead(de)) {
971 			while ((dde = LIST_FIRST(&de->ud.td_duphead)) != NULL) {
972 				LIST_REMOVE(dde, uh.td_dup.entries);
973 				dde->td_node = NULL;
974 				tmpfs_free_dirent(tmp, dde);
975 			}
976 		}
977 		tmpfs_free_dirent(tmp, de);
978 	}
979 }
980 
981 /* --------------------------------------------------------------------- */
982 
983 /*
984  * Helper function for tmpfs_readdir.  Creates a '.' entry for the given
985  * directory and returns it in the uio space.  The function returns 0
986  * on success, -1 if there was not enough space in the uio structure to
987  * hold the directory entry or an appropriate error code if another
988  * error happens.
989  */
990 static int
991 tmpfs_dir_getdotdent(struct tmpfs_node *node, struct uio *uio)
992 {
993 	int error;
994 	struct dirent dent;
995 
996 	TMPFS_VALIDATE_DIR(node);
997 	MPASS(uio->uio_offset == TMPFS_DIRCOOKIE_DOT);
998 
999 	dent.d_fileno = node->tn_id;
1000 	dent.d_type = DT_DIR;
1001 	dent.d_namlen = 1;
1002 	dent.d_name[0] = '.';
1003 	dent.d_name[1] = '\0';
1004 	dent.d_reclen = GENERIC_DIRSIZ(&dent);
1005 
1006 	if (dent.d_reclen > uio->uio_resid)
1007 		error = EJUSTRETURN;
1008 	else
1009 		error = uiomove(&dent, dent.d_reclen, uio);
1010 
1011 	node->tn_status |= TMPFS_NODE_ACCESSED;
1012 
1013 	return error;
1014 }
1015 
1016 /* --------------------------------------------------------------------- */
1017 
1018 /*
1019  * Helper function for tmpfs_readdir.  Creates a '..' entry for the given
1020  * directory and returns it in the uio space.  The function returns 0
1021  * on success, -1 if there was not enough space in the uio structure to
1022  * hold the directory entry or an appropriate error code if another
1023  * error happens.
1024  */
1025 static int
1026 tmpfs_dir_getdotdotdent(struct tmpfs_node *node, struct uio *uio)
1027 {
1028 	int error;
1029 	struct dirent dent;
1030 
1031 	TMPFS_VALIDATE_DIR(node);
1032 	MPASS(uio->uio_offset == TMPFS_DIRCOOKIE_DOTDOT);
1033 
1034 	/*
1035 	 * Return ENOENT if the current node is already removed.
1036 	 */
1037 	TMPFS_ASSERT_LOCKED(node);
1038 	if (node->tn_dir.tn_parent == NULL) {
1039 		return (ENOENT);
1040 	}
1041 
1042 	TMPFS_NODE_LOCK(node->tn_dir.tn_parent);
1043 	dent.d_fileno = node->tn_dir.tn_parent->tn_id;
1044 	TMPFS_NODE_UNLOCK(node->tn_dir.tn_parent);
1045 
1046 	dent.d_type = DT_DIR;
1047 	dent.d_namlen = 2;
1048 	dent.d_name[0] = '.';
1049 	dent.d_name[1] = '.';
1050 	dent.d_name[2] = '\0';
1051 	dent.d_reclen = GENERIC_DIRSIZ(&dent);
1052 
1053 	if (dent.d_reclen > uio->uio_resid)
1054 		error = EJUSTRETURN;
1055 	else
1056 		error = uiomove(&dent, dent.d_reclen, uio);
1057 
1058 	node->tn_status |= TMPFS_NODE_ACCESSED;
1059 
1060 	return error;
1061 }
1062 
1063 /* --------------------------------------------------------------------- */
1064 
1065 /*
1066  * Helper function for tmpfs_readdir.  Returns as much directory entries
1067  * as can fit in the uio space.  The read starts at uio->uio_offset.
1068  * The function returns 0 on success, -1 if there was not enough space
1069  * in the uio structure to hold the directory entry or an appropriate
1070  * error code if another error happens.
1071  */
1072 int
1073 tmpfs_dir_getdents(struct tmpfs_node *node, struct uio *uio, int cnt,
1074     u_long *cookies, int *ncookies)
1075 {
1076 	struct tmpfs_dir_cursor dc;
1077 	struct tmpfs_dirent *de;
1078 	off_t off;
1079 	int error;
1080 
1081 	TMPFS_VALIDATE_DIR(node);
1082 
1083 	off = 0;
1084 	switch (uio->uio_offset) {
1085 	case TMPFS_DIRCOOKIE_DOT:
1086 		error = tmpfs_dir_getdotdent(node, uio);
1087 		if (error != 0)
1088 			return (error);
1089 		uio->uio_offset = TMPFS_DIRCOOKIE_DOTDOT;
1090 		if (cnt != 0)
1091 			cookies[(*ncookies)++] = off = uio->uio_offset;
1092 	case TMPFS_DIRCOOKIE_DOTDOT:
1093 		error = tmpfs_dir_getdotdotdent(node, uio);
1094 		if (error != 0)
1095 			return (error);
1096 		de = tmpfs_dir_first(node, &dc);
1097 		if (de == NULL)
1098 			uio->uio_offset = TMPFS_DIRCOOKIE_EOF;
1099 		else
1100 			uio->uio_offset = tmpfs_dirent_cookie(de);
1101 		if (cnt != 0)
1102 			cookies[(*ncookies)++] = off = uio->uio_offset;
1103 		if (de == NULL)
1104 			return (0);
1105 		break;
1106 	case TMPFS_DIRCOOKIE_EOF:
1107 		return (0);
1108 	default:
1109 		de = tmpfs_dir_lookup_cookie(node, uio->uio_offset, &dc);
1110 		if (de == NULL)
1111 			return (EINVAL);
1112 		if (cnt != 0)
1113 			off = tmpfs_dirent_cookie(de);
1114 	}
1115 
1116 	/* Read as much entries as possible; i.e., until we reach the end of
1117 	 * the directory or we exhaust uio space. */
1118 	do {
1119 		struct dirent d;
1120 
1121 		/* Create a dirent structure representing the current
1122 		 * tmpfs_node and fill it. */
1123 		if (de->td_node == NULL) {
1124 			d.d_fileno = 1;
1125 			d.d_type = DT_WHT;
1126 		} else {
1127 			d.d_fileno = de->td_node->tn_id;
1128 			switch (de->td_node->tn_type) {
1129 			case VBLK:
1130 				d.d_type = DT_BLK;
1131 				break;
1132 
1133 			case VCHR:
1134 				d.d_type = DT_CHR;
1135 				break;
1136 
1137 			case VDIR:
1138 				d.d_type = DT_DIR;
1139 				break;
1140 
1141 			case VFIFO:
1142 				d.d_type = DT_FIFO;
1143 				break;
1144 
1145 			case VLNK:
1146 				d.d_type = DT_LNK;
1147 				break;
1148 
1149 			case VREG:
1150 				d.d_type = DT_REG;
1151 				break;
1152 
1153 			case VSOCK:
1154 				d.d_type = DT_SOCK;
1155 				break;
1156 
1157 			default:
1158 				panic("tmpfs_dir_getdents: type %p %d",
1159 				    de->td_node, (int)de->td_node->tn_type);
1160 			}
1161 		}
1162 		d.d_namlen = de->td_namelen;
1163 		MPASS(de->td_namelen < sizeof(d.d_name));
1164 		(void)memcpy(d.d_name, de->ud.td_name, de->td_namelen);
1165 		d.d_name[de->td_namelen] = '\0';
1166 		d.d_reclen = GENERIC_DIRSIZ(&d);
1167 
1168 		/* Stop reading if the directory entry we are treating is
1169 		 * bigger than the amount of data that can be returned. */
1170 		if (d.d_reclen > uio->uio_resid) {
1171 			error = EJUSTRETURN;
1172 			break;
1173 		}
1174 
1175 		/* Copy the new dirent structure into the output buffer and
1176 		 * advance pointers. */
1177 		error = uiomove(&d, d.d_reclen, uio);
1178 		if (error == 0) {
1179 			de = tmpfs_dir_next(node, &dc);
1180 			if (cnt != 0) {
1181 				if (de == NULL)
1182 					off = TMPFS_DIRCOOKIE_EOF;
1183 				else
1184 					off = tmpfs_dirent_cookie(de);
1185 				MPASS(*ncookies < cnt);
1186 				cookies[(*ncookies)++] = off;
1187 			}
1188 		}
1189 	} while (error == 0 && uio->uio_resid > 0 && de != NULL);
1190 
1191 	/* Update the offset and cache. */
1192 	if (cnt == 0) {
1193 		if (de == NULL)
1194 			off = TMPFS_DIRCOOKIE_EOF;
1195 		else
1196 			off = tmpfs_dirent_cookie(de);
1197 	}
1198 
1199 	uio->uio_offset = off;
1200 	node->tn_dir.tn_readdir_lastn = off;
1201 	node->tn_dir.tn_readdir_lastp = de;
1202 
1203 	node->tn_status |= TMPFS_NODE_ACCESSED;
1204 	return error;
1205 }
1206 
1207 int
1208 tmpfs_dir_whiteout_add(struct vnode *dvp, struct componentname *cnp)
1209 {
1210 	struct tmpfs_dirent *de;
1211 	int error;
1212 
1213 	error = tmpfs_alloc_dirent(VFS_TO_TMPFS(dvp->v_mount), NULL,
1214 	    cnp->cn_nameptr, cnp->cn_namelen, &de);
1215 	if (error != 0)
1216 		return (error);
1217 	tmpfs_dir_attach(dvp, de);
1218 	return (0);
1219 }
1220 
1221 void
1222 tmpfs_dir_whiteout_remove(struct vnode *dvp, struct componentname *cnp)
1223 {
1224 	struct tmpfs_dirent *de;
1225 
1226 	de = tmpfs_dir_lookup(VP_TO_TMPFS_DIR(dvp), NULL, cnp);
1227 	MPASS(de != NULL && de->td_node == NULL);
1228 	tmpfs_dir_detach(dvp, de);
1229 	tmpfs_free_dirent(VFS_TO_TMPFS(dvp->v_mount), de);
1230 }
1231 
1232 /* --------------------------------------------------------------------- */
1233 
1234 /*
1235  * Resizes the aobj associated with the regular file pointed to by 'vp' to the
1236  * size 'newsize'.  'vp' must point to a vnode that represents a regular file.
1237  * 'newsize' must be positive.
1238  *
1239  * Returns zero on success or an appropriate error code on failure.
1240  */
1241 int
1242 tmpfs_reg_resize(struct vnode *vp, off_t newsize, boolean_t ignerr)
1243 {
1244 	struct tmpfs_mount *tmp;
1245 	struct tmpfs_node *node;
1246 	vm_object_t uobj;
1247 	vm_page_t m, ma[1];
1248 	vm_pindex_t idx, newpages, oldpages;
1249 	off_t oldsize;
1250 	int base, rv;
1251 
1252 	MPASS(vp->v_type == VREG);
1253 	MPASS(newsize >= 0);
1254 
1255 	node = VP_TO_TMPFS_NODE(vp);
1256 	uobj = node->tn_reg.tn_aobj;
1257 	tmp = VFS_TO_TMPFS(vp->v_mount);
1258 
1259 	/*
1260 	 * Convert the old and new sizes to the number of pages needed to
1261 	 * store them.  It may happen that we do not need to do anything
1262 	 * because the last allocated page can accommodate the change on
1263 	 * its own.
1264 	 */
1265 	oldsize = node->tn_size;
1266 	oldpages = OFF_TO_IDX(oldsize + PAGE_MASK);
1267 	MPASS(oldpages == uobj->size);
1268 	newpages = OFF_TO_IDX(newsize + PAGE_MASK);
1269 	if (newpages > oldpages &&
1270 	    tmpfs_pages_check_avail(tmp, newpages - oldpages) == 0)
1271 		return (ENOSPC);
1272 
1273 	VM_OBJECT_LOCK(uobj);
1274 	if (newsize < oldsize) {
1275 		/*
1276 		 * Zero the truncated part of the last page.
1277 		 */
1278 		base = newsize & PAGE_MASK;
1279 		if (base != 0) {
1280 			idx = OFF_TO_IDX(newsize);
1281 retry:
1282 			m = vm_page_lookup(uobj, idx);
1283 			if (m != NULL) {
1284 				if ((m->oflags & VPO_BUSY) != 0 ||
1285 				    m->busy != 0) {
1286 					vm_page_sleep(m, "tmfssz");
1287 					goto retry;
1288 				}
1289 				MPASS(m->valid == VM_PAGE_BITS_ALL);
1290 			} else if (vm_pager_has_page(uobj, idx, NULL, NULL)) {
1291 				m = vm_page_alloc(uobj, idx, VM_ALLOC_NORMAL);
1292 				if (m == NULL) {
1293 					VM_OBJECT_UNLOCK(uobj);
1294 					VM_WAIT;
1295 					VM_OBJECT_LOCK(uobj);
1296 					goto retry;
1297 				} else if (m->valid != VM_PAGE_BITS_ALL) {
1298 					ma[0] = m;
1299 					rv = vm_pager_get_pages(uobj, ma, 1, 0);
1300 					m = vm_page_lookup(uobj, idx);
1301 				} else
1302 					/* A cached page was reactivated. */
1303 					rv = VM_PAGER_OK;
1304 				vm_page_lock(m);
1305 				if (rv == VM_PAGER_OK) {
1306 					vm_page_deactivate(m);
1307 					vm_page_unlock(m);
1308 					vm_page_wakeup(m);
1309 				} else {
1310 					vm_page_free(m);
1311 					vm_page_unlock(m);
1312 					if (ignerr)
1313 						m = NULL;
1314 					else {
1315 						VM_OBJECT_UNLOCK(uobj);
1316 						return (EIO);
1317 					}
1318 				}
1319 			}
1320 			if (m != NULL) {
1321 				pmap_zero_page_area(m, base, PAGE_SIZE - base);
1322 				vm_page_dirty(m);
1323 				vm_pager_page_unswapped(m);
1324 			}
1325 		}
1326 
1327 		/*
1328 		 * Release any swap space and free any whole pages.
1329 		 */
1330 		if (newpages < oldpages) {
1331 			swap_pager_freespace(uobj, newpages, oldpages -
1332 			    newpages);
1333 			vm_object_page_remove(uobj, newpages, 0, 0);
1334 		}
1335 	}
1336 	uobj->size = newpages;
1337 	VM_OBJECT_UNLOCK(uobj);
1338 
1339 	TMPFS_LOCK(tmp);
1340 	tmp->tm_pages_used += (newpages - oldpages);
1341 	TMPFS_UNLOCK(tmp);
1342 
1343 	node->tn_size = newsize;
1344 	vnode_pager_setsize(vp, newsize);
1345 	return (0);
1346 }
1347 
1348 /* --------------------------------------------------------------------- */
1349 
1350 /*
1351  * Change flags of the given vnode.
1352  * Caller should execute tmpfs_update on vp after a successful execution.
1353  * The vnode must be locked on entry and remain locked on exit.
1354  */
1355 int
1356 tmpfs_chflags(struct vnode *vp, int flags, struct ucred *cred, struct thread *p)
1357 {
1358 	int error;
1359 	struct tmpfs_node *node;
1360 
1361 	MPASS(VOP_ISLOCKED(vp));
1362 
1363 	node = VP_TO_TMPFS_NODE(vp);
1364 
1365 	if ((flags & ~(UF_NODUMP | UF_IMMUTABLE | UF_APPEND | UF_OPAQUE |
1366 	    UF_NOUNLINK | SF_ARCHIVED | SF_IMMUTABLE | SF_APPEND |
1367 	    SF_NOUNLINK)) != 0)
1368 		return (EOPNOTSUPP);
1369 
1370 	/* Disallow this operation if the file system is mounted read-only. */
1371 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
1372 		return EROFS;
1373 
1374 	/*
1375 	 * Callers may only modify the file flags on objects they
1376 	 * have VADMIN rights for.
1377 	 */
1378 	if ((error = VOP_ACCESS(vp, VADMIN, cred, p)))
1379 		return (error);
1380 	/*
1381 	 * Unprivileged processes are not permitted to unset system
1382 	 * flags, or modify flags if any system flags are set.
1383 	 */
1384 	if (!priv_check_cred(cred, PRIV_VFS_SYSFLAGS, 0)) {
1385 		if (node->tn_flags &
1386 		    (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND)) {
1387 			error = securelevel_gt(cred, 0);
1388 			if (error)
1389 				return (error);
1390 		}
1391 	} else {
1392 		if (node->tn_flags &
1393 		    (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND) ||
1394 		    ((flags ^ node->tn_flags) & SF_SETTABLE))
1395 			return (EPERM);
1396 	}
1397 	node->tn_flags = flags;
1398 	node->tn_status |= TMPFS_NODE_CHANGED;
1399 
1400 	MPASS(VOP_ISLOCKED(vp));
1401 
1402 	return 0;
1403 }
1404 
1405 /* --------------------------------------------------------------------- */
1406 
1407 /*
1408  * Change access mode on the given vnode.
1409  * Caller should execute tmpfs_update on vp after a successful execution.
1410  * The vnode must be locked on entry and remain locked on exit.
1411  */
1412 int
1413 tmpfs_chmod(struct vnode *vp, mode_t mode, struct ucred *cred, struct thread *p)
1414 {
1415 	int error;
1416 	struct tmpfs_node *node;
1417 
1418 	MPASS(VOP_ISLOCKED(vp));
1419 
1420 	node = VP_TO_TMPFS_NODE(vp);
1421 
1422 	/* Disallow this operation if the file system is mounted read-only. */
1423 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
1424 		return EROFS;
1425 
1426 	/* Immutable or append-only files cannot be modified, either. */
1427 	if (node->tn_flags & (IMMUTABLE | APPEND))
1428 		return EPERM;
1429 
1430 	/*
1431 	 * To modify the permissions on a file, must possess VADMIN
1432 	 * for that file.
1433 	 */
1434 	if ((error = VOP_ACCESS(vp, VADMIN, cred, p)))
1435 		return (error);
1436 
1437 	/*
1438 	 * Privileged processes may set the sticky bit on non-directories,
1439 	 * as well as set the setgid bit on a file with a group that the
1440 	 * process is not a member of.
1441 	 */
1442 	if (vp->v_type != VDIR && (mode & S_ISTXT)) {
1443 		if (priv_check_cred(cred, PRIV_VFS_STICKYFILE, 0))
1444 			return (EFTYPE);
1445 	}
1446 	if (!groupmember(node->tn_gid, cred) && (mode & S_ISGID)) {
1447 		error = priv_check_cred(cred, PRIV_VFS_SETGID, 0);
1448 		if (error)
1449 			return (error);
1450 	}
1451 
1452 
1453 	node->tn_mode &= ~ALLPERMS;
1454 	node->tn_mode |= mode & ALLPERMS;
1455 
1456 	node->tn_status |= TMPFS_NODE_CHANGED;
1457 
1458 	MPASS(VOP_ISLOCKED(vp));
1459 
1460 	return 0;
1461 }
1462 
1463 /* --------------------------------------------------------------------- */
1464 
1465 /*
1466  * Change ownership of the given vnode.  At least one of uid or gid must
1467  * be different than VNOVAL.  If one is set to that value, the attribute
1468  * is unchanged.
1469  * Caller should execute tmpfs_update on vp after a successful execution.
1470  * The vnode must be locked on entry and remain locked on exit.
1471  */
1472 int
1473 tmpfs_chown(struct vnode *vp, uid_t uid, gid_t gid, struct ucred *cred,
1474     struct thread *p)
1475 {
1476 	int error;
1477 	struct tmpfs_node *node;
1478 	uid_t ouid;
1479 	gid_t ogid;
1480 
1481 	MPASS(VOP_ISLOCKED(vp));
1482 
1483 	node = VP_TO_TMPFS_NODE(vp);
1484 
1485 	/* Assign default values if they are unknown. */
1486 	MPASS(uid != VNOVAL || gid != VNOVAL);
1487 	if (uid == VNOVAL)
1488 		uid = node->tn_uid;
1489 	if (gid == VNOVAL)
1490 		gid = node->tn_gid;
1491 	MPASS(uid != VNOVAL && gid != VNOVAL);
1492 
1493 	/* Disallow this operation if the file system is mounted read-only. */
1494 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
1495 		return EROFS;
1496 
1497 	/* Immutable or append-only files cannot be modified, either. */
1498 	if (node->tn_flags & (IMMUTABLE | APPEND))
1499 		return EPERM;
1500 
1501 	/*
1502 	 * To modify the ownership of a file, must possess VADMIN for that
1503 	 * file.
1504 	 */
1505 	if ((error = VOP_ACCESS(vp, VADMIN, cred, p)))
1506 		return (error);
1507 
1508 	/*
1509 	 * To change the owner of a file, or change the group of a file to a
1510 	 * group of which we are not a member, the caller must have
1511 	 * privilege.
1512 	 */
1513 	if ((uid != node->tn_uid ||
1514 	    (gid != node->tn_gid && !groupmember(gid, cred))) &&
1515 	    (error = priv_check_cred(cred, PRIV_VFS_CHOWN, 0)))
1516 		return (error);
1517 
1518 	ogid = node->tn_gid;
1519 	ouid = node->tn_uid;
1520 
1521 	node->tn_uid = uid;
1522 	node->tn_gid = gid;
1523 
1524 	node->tn_status |= TMPFS_NODE_CHANGED;
1525 
1526 	if ((node->tn_mode & (S_ISUID | S_ISGID)) && (ouid != uid || ogid != gid)) {
1527 		if (priv_check_cred(cred, PRIV_VFS_RETAINSUGID, 0))
1528 			node->tn_mode &= ~(S_ISUID | S_ISGID);
1529 	}
1530 
1531 	MPASS(VOP_ISLOCKED(vp));
1532 
1533 	return 0;
1534 }
1535 
1536 /* --------------------------------------------------------------------- */
1537 
1538 /*
1539  * Change size of the given vnode.
1540  * Caller should execute tmpfs_update on vp after a successful execution.
1541  * The vnode must be locked on entry and remain locked on exit.
1542  */
1543 int
1544 tmpfs_chsize(struct vnode *vp, u_quad_t size, struct ucred *cred,
1545     struct thread *p)
1546 {
1547 	int error;
1548 	struct tmpfs_node *node;
1549 
1550 	MPASS(VOP_ISLOCKED(vp));
1551 
1552 	node = VP_TO_TMPFS_NODE(vp);
1553 
1554 	/* Decide whether this is a valid operation based on the file type. */
1555 	error = 0;
1556 	switch (vp->v_type) {
1557 	case VDIR:
1558 		return EISDIR;
1559 
1560 	case VREG:
1561 		if (vp->v_mount->mnt_flag & MNT_RDONLY)
1562 			return EROFS;
1563 		break;
1564 
1565 	case VBLK:
1566 		/* FALLTHROUGH */
1567 	case VCHR:
1568 		/* FALLTHROUGH */
1569 	case VFIFO:
1570 		/* Allow modifications of special files even if in the file
1571 		 * system is mounted read-only (we are not modifying the
1572 		 * files themselves, but the objects they represent). */
1573 		return 0;
1574 
1575 	default:
1576 		/* Anything else is unsupported. */
1577 		return EOPNOTSUPP;
1578 	}
1579 
1580 	/* Immutable or append-only files cannot be modified, either. */
1581 	if (node->tn_flags & (IMMUTABLE | APPEND))
1582 		return EPERM;
1583 
1584 	error = tmpfs_truncate(vp, size);
1585 	/* tmpfs_truncate will raise the NOTE_EXTEND and NOTE_ATTRIB kevents
1586 	 * for us, as will update tn_status; no need to do that here. */
1587 
1588 	MPASS(VOP_ISLOCKED(vp));
1589 
1590 	return error;
1591 }
1592 
1593 /* --------------------------------------------------------------------- */
1594 
1595 /*
1596  * Change access and modification times of the given vnode.
1597  * Caller should execute tmpfs_update on vp after a successful execution.
1598  * The vnode must be locked on entry and remain locked on exit.
1599  */
1600 int
1601 tmpfs_chtimes(struct vnode *vp, struct timespec *atime, struct timespec *mtime,
1602 	struct timespec *birthtime, int vaflags, struct ucred *cred, struct thread *l)
1603 {
1604 	int error;
1605 	struct tmpfs_node *node;
1606 
1607 	MPASS(VOP_ISLOCKED(vp));
1608 
1609 	node = VP_TO_TMPFS_NODE(vp);
1610 
1611 	/* Disallow this operation if the file system is mounted read-only. */
1612 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
1613 		return EROFS;
1614 
1615 	/* Immutable or append-only files cannot be modified, either. */
1616 	if (node->tn_flags & (IMMUTABLE | APPEND))
1617 		return EPERM;
1618 
1619 	/* Determine if the user have proper privilege to update time. */
1620 	if (vaflags & VA_UTIMES_NULL) {
1621 		error = VOP_ACCESS(vp, VADMIN, cred, l);
1622 		if (error)
1623 			error = VOP_ACCESS(vp, VWRITE, cred, l);
1624 	} else
1625 		error = VOP_ACCESS(vp, VADMIN, cred, l);
1626 	if (error)
1627 		return (error);
1628 
1629 	if (atime->tv_sec != VNOVAL && atime->tv_nsec != VNOVAL)
1630 		node->tn_status |= TMPFS_NODE_ACCESSED;
1631 
1632 	if (mtime->tv_sec != VNOVAL && mtime->tv_nsec != VNOVAL)
1633 		node->tn_status |= TMPFS_NODE_MODIFIED;
1634 
1635 	if (birthtime->tv_nsec != VNOVAL && birthtime->tv_nsec != VNOVAL)
1636 		node->tn_status |= TMPFS_NODE_MODIFIED;
1637 
1638 	tmpfs_itimes(vp, atime, mtime);
1639 
1640 	if (birthtime->tv_nsec != VNOVAL && birthtime->tv_nsec != VNOVAL)
1641 		node->tn_birthtime = *birthtime;
1642 	MPASS(VOP_ISLOCKED(vp));
1643 
1644 	return 0;
1645 }
1646 
1647 /* --------------------------------------------------------------------- */
1648 /* Sync timestamps */
1649 void
1650 tmpfs_itimes(struct vnode *vp, const struct timespec *acc,
1651     const struct timespec *mod)
1652 {
1653 	struct tmpfs_node *node;
1654 	struct timespec now;
1655 
1656 	node = VP_TO_TMPFS_NODE(vp);
1657 
1658 	if ((node->tn_status & (TMPFS_NODE_ACCESSED | TMPFS_NODE_MODIFIED |
1659 	    TMPFS_NODE_CHANGED)) == 0)
1660 		return;
1661 
1662 	vfs_timestamp(&now);
1663 	if (node->tn_status & TMPFS_NODE_ACCESSED) {
1664 		if (acc == NULL)
1665 			 acc = &now;
1666 		node->tn_atime = *acc;
1667 	}
1668 	if (node->tn_status & TMPFS_NODE_MODIFIED) {
1669 		if (mod == NULL)
1670 			mod = &now;
1671 		node->tn_mtime = *mod;
1672 	}
1673 	if (node->tn_status & TMPFS_NODE_CHANGED) {
1674 		node->tn_ctime = now;
1675 	}
1676 	node->tn_status &=
1677 	    ~(TMPFS_NODE_ACCESSED | TMPFS_NODE_MODIFIED | TMPFS_NODE_CHANGED);
1678 }
1679 
1680 /* --------------------------------------------------------------------- */
1681 
1682 void
1683 tmpfs_update(struct vnode *vp)
1684 {
1685 
1686 	tmpfs_itimes(vp, NULL, NULL);
1687 }
1688 
1689 /* --------------------------------------------------------------------- */
1690 
1691 int
1692 tmpfs_truncate(struct vnode *vp, off_t length)
1693 {
1694 	int error;
1695 	struct tmpfs_node *node;
1696 
1697 	node = VP_TO_TMPFS_NODE(vp);
1698 
1699 	if (length < 0) {
1700 		error = EINVAL;
1701 		goto out;
1702 	}
1703 
1704 	if (node->tn_size == length) {
1705 		error = 0;
1706 		goto out;
1707 	}
1708 
1709 	if (length > VFS_TO_TMPFS(vp->v_mount)->tm_maxfilesize)
1710 		return (EFBIG);
1711 
1712 	error = tmpfs_reg_resize(vp, length, FALSE);
1713 	if (error == 0) {
1714 		node->tn_status |= TMPFS_NODE_CHANGED | TMPFS_NODE_MODIFIED;
1715 	}
1716 
1717 out:
1718 	tmpfs_update(vp);
1719 
1720 	return error;
1721 }
1722 
1723 static __inline int
1724 tmpfs_dirtree_cmp(struct tmpfs_dirent *a, struct tmpfs_dirent *b)
1725 {
1726 	if (a->td_hash > b->td_hash)
1727 		return (1);
1728 	else if (a->td_hash < b->td_hash)
1729 		return (-1);
1730 	return (0);
1731 }
1732 
1733 RB_GENERATE_STATIC(tmpfs_dir, tmpfs_dirent, uh.td_entries, tmpfs_dirtree_cmp);
1734