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