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