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