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