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