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