xref: /freebsd-14.2/sys/fs/tmpfs/tmpfs_subr.c (revision ab135e19)
1 /*	$NetBSD: tmpfs_subr.c,v 1.35 2007/07/09 21:10:50 ad Exp $	*/
2 
3 /*-
4  * SPDX-License-Identifier: BSD-2-Clause
5  *
6  * Copyright (c) 2005 The NetBSD Foundation, Inc.
7  * All rights reserved.
8  *
9  * This code is derived from software contributed to The NetBSD Foundation
10  * by Julio M. Merino Vidal, developed as part of Google's Summer of Code
11  * 2005 program.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
24  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
26  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 /*
36  * Efficient memory file system supporting functions.
37  */
38 #include <sys/cdefs.h>
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/dirent.h>
42 #include <sys/fnv_hash.h>
43 #include <sys/lock.h>
44 #include <sys/limits.h>
45 #include <sys/mount.h>
46 #include <sys/namei.h>
47 #include <sys/priv.h>
48 #include <sys/proc.h>
49 #include <sys/random.h>
50 #include <sys/refcount.h>
51 #include <sys/rwlock.h>
52 #include <sys/smr.h>
53 #include <sys/stat.h>
54 #include <sys/sysctl.h>
55 #include <sys/user.h>
56 #include <sys/vnode.h>
57 #include <sys/vmmeter.h>
58 
59 #include <vm/vm.h>
60 #include <vm/vm_param.h>
61 #include <vm/vm_object.h>
62 #include <vm/vm_page.h>
63 #include <vm/vm_pageout.h>
64 #include <vm/vm_pager.h>
65 #include <vm/vm_extern.h>
66 #include <vm/swap_pager.h>
67 
68 #include <fs/tmpfs/tmpfs.h>
69 #include <fs/tmpfs/tmpfs_fifoops.h>
70 #include <fs/tmpfs/tmpfs_vnops.h>
71 
72 SYSCTL_NODE(_vfs, OID_AUTO, tmpfs, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
73     "tmpfs file system");
74 
75 static long tmpfs_pages_reserved = TMPFS_PAGES_MINRESERVED;
76 
77 MALLOC_DEFINE(M_TMPFSDIR, "tmpfs dir", "tmpfs dirent structure");
78 static uma_zone_t tmpfs_node_pool;
79 VFS_SMR_DECLARE;
80 
81 int tmpfs_pager_type = -1;
82 
83 static vm_object_t
tmpfs_pager_alloc(void * handle,vm_ooffset_t size,vm_prot_t prot,vm_ooffset_t offset,struct ucred * cred)84 tmpfs_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot,
85     vm_ooffset_t offset, struct ucred *cred)
86 {
87 	vm_object_t object;
88 
89 	MPASS(handle == NULL);
90 	MPASS(offset == 0);
91 	object = vm_object_allocate_dyn(tmpfs_pager_type, size,
92 	    OBJ_COLORED | OBJ_SWAP);
93 	if (!swap_pager_init_object(object, NULL, NULL, size, 0)) {
94 		vm_object_deallocate(object);
95 		object = NULL;
96 	}
97 	return (object);
98 }
99 
100 /*
101  * Make sure tmpfs vnodes with writable mappings can be found on the lazy list.
102  *
103  * This allows for periodic mtime updates while only scanning vnodes which are
104  * plausibly dirty, see tmpfs_update_mtime_lazy.
105  */
106 static void
tmpfs_pager_writecount_recalc(vm_object_t object,vm_offset_t old,vm_offset_t new)107 tmpfs_pager_writecount_recalc(vm_object_t object, vm_offset_t old,
108     vm_offset_t new)
109 {
110 	struct vnode *vp;
111 
112 	VM_OBJECT_ASSERT_WLOCKED(object);
113 
114 	vp = VM_TO_TMPFS_VP(object);
115 
116 	/*
117 	 * Forced unmount?
118 	 */
119 	if (vp == NULL || vp->v_object == NULL) {
120 		KASSERT((object->flags & OBJ_TMPFS_VREF) == 0,
121 		    ("object %p with OBJ_TMPFS_VREF but without vnode",
122 		    object));
123 		VM_OBJECT_WUNLOCK(object);
124 		return;
125 	}
126 
127 	if (old == 0) {
128 		VNASSERT((object->flags & OBJ_TMPFS_VREF) == 0, vp,
129 		    ("object without writable mappings has a reference"));
130 		VNPASS(vp->v_usecount > 0, vp);
131 	} else {
132 		VNASSERT((object->flags & OBJ_TMPFS_VREF) != 0, vp,
133 		    ("object with writable mappings does not "
134 		    "have a reference"));
135 	}
136 
137 	if (old == new) {
138 		VM_OBJECT_WUNLOCK(object);
139 		return;
140 	}
141 
142 	if (new == 0) {
143 		vm_object_clear_flag(object, OBJ_TMPFS_VREF);
144 		VM_OBJECT_WUNLOCK(object);
145 		vrele(vp);
146 	} else {
147 		if ((object->flags & OBJ_TMPFS_VREF) == 0) {
148 			vref(vp);
149 			vlazy(vp);
150 			vm_object_set_flag(object, OBJ_TMPFS_VREF);
151 		}
152 		VM_OBJECT_WUNLOCK(object);
153 	}
154 }
155 
156 static void
tmpfs_pager_update_writecount(vm_object_t object,vm_offset_t start,vm_offset_t end)157 tmpfs_pager_update_writecount(vm_object_t object, vm_offset_t start,
158     vm_offset_t end)
159 {
160 	vm_offset_t new, old;
161 
162 	VM_OBJECT_WLOCK(object);
163 	KASSERT((object->flags & OBJ_ANON) == 0,
164 	    ("%s: object %p with OBJ_ANON", __func__, object));
165 	old = object->un_pager.swp.writemappings;
166 	object->un_pager.swp.writemappings += (vm_ooffset_t)end - start;
167 	new = object->un_pager.swp.writemappings;
168 	tmpfs_pager_writecount_recalc(object, old, new);
169 	VM_OBJECT_ASSERT_UNLOCKED(object);
170 }
171 
172 static void
tmpfs_pager_release_writecount(vm_object_t object,vm_offset_t start,vm_offset_t end)173 tmpfs_pager_release_writecount(vm_object_t object, vm_offset_t start,
174     vm_offset_t end)
175 {
176 	vm_offset_t new, old;
177 
178 	VM_OBJECT_WLOCK(object);
179 	KASSERT((object->flags & OBJ_ANON) == 0,
180 	    ("%s: object %p with OBJ_ANON", __func__, object));
181 	old = object->un_pager.swp.writemappings;
182 	KASSERT(old >= (vm_ooffset_t)end - start,
183 	    ("tmpfs obj %p writecount %jx dec %jx", object, (uintmax_t)old,
184 	    (uintmax_t)((vm_ooffset_t)end - start)));
185 	object->un_pager.swp.writemappings -= (vm_ooffset_t)end - start;
186 	new = object->un_pager.swp.writemappings;
187 	tmpfs_pager_writecount_recalc(object, old, new);
188 	VM_OBJECT_ASSERT_UNLOCKED(object);
189 }
190 
191 static void
tmpfs_pager_getvp(vm_object_t object,struct vnode ** vpp,bool * vp_heldp)192 tmpfs_pager_getvp(vm_object_t object, struct vnode **vpp, bool *vp_heldp)
193 {
194 	struct vnode *vp;
195 
196 	/*
197 	 * Tmpfs VREG node, which was reclaimed, has tmpfs_pager_type
198 	 * type.  In this case there is no v_writecount to adjust.
199 	 */
200 	if (vp_heldp != NULL)
201 		VM_OBJECT_RLOCK(object);
202 	else
203 		VM_OBJECT_ASSERT_LOCKED(object);
204 	if ((object->flags & OBJ_TMPFS) != 0) {
205 		vp = VM_TO_TMPFS_VP(object);
206 		if (vp != NULL) {
207 			*vpp = vp;
208 			if (vp_heldp != NULL) {
209 				vhold(vp);
210 				*vp_heldp = true;
211 			}
212 		}
213 	}
214 	if (vp_heldp != NULL)
215 		VM_OBJECT_RUNLOCK(object);
216 }
217 
218 static void
tmpfs_pager_freespace(vm_object_t obj,vm_pindex_t start,vm_size_t size)219 tmpfs_pager_freespace(vm_object_t obj, vm_pindex_t start, vm_size_t size)
220 {
221 	struct tmpfs_node *node;
222 	struct tmpfs_mount *tm;
223 	vm_size_t c;
224 
225 	swap_pager_freespace(obj, start, size, &c);
226 	if ((obj->flags & OBJ_TMPFS) == 0 || c == 0)
227 		return;
228 
229 	node = obj->un_pager.swp.swp_priv;
230 	MPASS(node->tn_type == VREG);
231 	tm = node->tn_reg.tn_tmp;
232 
233 	KASSERT(tm->tm_pages_used >= c,
234 	    ("tmpfs tm %p pages %jd free %jd", tm,
235 	    (uintmax_t)tm->tm_pages_used, (uintmax_t)c));
236 	atomic_add_long(&tm->tm_pages_used, -c);
237 	KASSERT(node->tn_reg.tn_pages >= c,
238 	    ("tmpfs node %p pages %jd free %jd", node,
239 	    (uintmax_t)node->tn_reg.tn_pages, (uintmax_t)c));
240 	node->tn_reg.tn_pages -= c;
241 }
242 
243 static void
tmpfs_page_inserted(vm_object_t obj,vm_page_t m)244 tmpfs_page_inserted(vm_object_t obj, vm_page_t m)
245 {
246 	struct tmpfs_node *node;
247 	struct tmpfs_mount *tm;
248 
249 	if ((obj->flags & OBJ_TMPFS) == 0)
250 		return;
251 
252 	node = obj->un_pager.swp.swp_priv;
253 	MPASS(node->tn_type == VREG);
254 	tm = node->tn_reg.tn_tmp;
255 
256 	if (!vm_pager_has_page(obj, m->pindex, NULL, NULL)) {
257 		atomic_add_long(&tm->tm_pages_used, 1);
258 		node->tn_reg.tn_pages += 1;
259 	}
260 }
261 
262 static void
tmpfs_page_removed(vm_object_t obj,vm_page_t m)263 tmpfs_page_removed(vm_object_t obj, vm_page_t m)
264 {
265 	struct tmpfs_node *node;
266 	struct tmpfs_mount *tm;
267 
268 	if ((obj->flags & OBJ_TMPFS) == 0)
269 		return;
270 
271 	node = obj->un_pager.swp.swp_priv;
272 	MPASS(node->tn_type == VREG);
273 	tm = node->tn_reg.tn_tmp;
274 
275 	if (!vm_pager_has_page(obj, m->pindex, NULL, NULL)) {
276 		KASSERT(tm->tm_pages_used >= 1,
277 		    ("tmpfs tm %p pages %jd free 1", tm,
278 		    (uintmax_t)tm->tm_pages_used));
279 		atomic_add_long(&tm->tm_pages_used, -1);
280 		KASSERT(node->tn_reg.tn_pages >= 1,
281 		    ("tmpfs node %p pages %jd free 1", node,
282 		    (uintmax_t)node->tn_reg.tn_pages));
283 		node->tn_reg.tn_pages -= 1;
284 	}
285 }
286 
287 static boolean_t
tmpfs_can_alloc_page(vm_object_t obj,vm_pindex_t pindex)288 tmpfs_can_alloc_page(vm_object_t obj, vm_pindex_t pindex)
289 {
290 	struct tmpfs_mount *tm;
291 
292 	tm = VM_TO_TMPFS_MP(obj);
293 	if (tm == NULL || vm_pager_has_page(obj, pindex, NULL, NULL) ||
294 	    tm->tm_pages_max == 0)
295 		return (true);
296 	return (tm->tm_pages_max > atomic_load_long(&tm->tm_pages_used));
297 }
298 
299 struct pagerops tmpfs_pager_ops = {
300 	.pgo_kvme_type = KVME_TYPE_VNODE,
301 	.pgo_alloc = tmpfs_pager_alloc,
302 	.pgo_set_writeable_dirty = vm_object_set_writeable_dirty_,
303 	.pgo_update_writecount = tmpfs_pager_update_writecount,
304 	.pgo_release_writecount = tmpfs_pager_release_writecount,
305 	.pgo_mightbedirty = vm_object_mightbedirty_,
306 	.pgo_getvp = tmpfs_pager_getvp,
307 	.pgo_freespace = tmpfs_pager_freespace,
308 	.pgo_page_inserted = tmpfs_page_inserted,
309 	.pgo_page_removed = tmpfs_page_removed,
310 	.pgo_can_alloc_page = tmpfs_can_alloc_page,
311 };
312 
313 static int
tmpfs_node_ctor(void * mem,int size,void * arg,int flags)314 tmpfs_node_ctor(void *mem, int size, void *arg, int flags)
315 {
316 	struct tmpfs_node *node;
317 
318 	node = mem;
319 	node->tn_gen++;
320 	node->tn_size = 0;
321 	node->tn_status = 0;
322 	node->tn_accessed = false;
323 	node->tn_flags = 0;
324 	node->tn_links = 0;
325 	node->tn_vnode = NULL;
326 	node->tn_vpstate = 0;
327 	return (0);
328 }
329 
330 static void
tmpfs_node_dtor(void * mem,int size,void * arg)331 tmpfs_node_dtor(void *mem, int size, void *arg)
332 {
333 	struct tmpfs_node *node;
334 
335 	node = mem;
336 	node->tn_type = VNON;
337 }
338 
339 static int
tmpfs_node_init(void * mem,int size,int flags)340 tmpfs_node_init(void *mem, int size, int flags)
341 {
342 	struct tmpfs_node *node;
343 
344 	node = mem;
345 	node->tn_id = 0;
346 	mtx_init(&node->tn_interlock, "tmpfsni", NULL, MTX_DEF);
347 	node->tn_gen = arc4random();
348 	return (0);
349 }
350 
351 static void
tmpfs_node_fini(void * mem,int size)352 tmpfs_node_fini(void *mem, int size)
353 {
354 	struct tmpfs_node *node;
355 
356 	node = mem;
357 	mtx_destroy(&node->tn_interlock);
358 }
359 
360 int
tmpfs_subr_init(void)361 tmpfs_subr_init(void)
362 {
363 	tmpfs_pager_type = vm_pager_alloc_dyn_type(&tmpfs_pager_ops,
364 	    OBJT_SWAP);
365 	if (tmpfs_pager_type == -1)
366 		return (EINVAL);
367 	tmpfs_node_pool = uma_zcreate("TMPFS node",
368 	    sizeof(struct tmpfs_node), tmpfs_node_ctor, tmpfs_node_dtor,
369 	    tmpfs_node_init, tmpfs_node_fini, UMA_ALIGN_PTR, 0);
370 	VFS_SMR_ZONE_SET(tmpfs_node_pool);
371 	return (0);
372 }
373 
374 void
tmpfs_subr_uninit(void)375 tmpfs_subr_uninit(void)
376 {
377 	if (tmpfs_pager_type != -1)
378 		vm_pager_free_dyn_type(tmpfs_pager_type);
379 	tmpfs_pager_type = -1;
380 	uma_zdestroy(tmpfs_node_pool);
381 }
382 
383 static int
sysctl_mem_reserved(SYSCTL_HANDLER_ARGS)384 sysctl_mem_reserved(SYSCTL_HANDLER_ARGS)
385 {
386 	int error;
387 	long pages, bytes;
388 
389 	pages = *(long *)arg1;
390 	bytes = pages * PAGE_SIZE;
391 
392 	error = sysctl_handle_long(oidp, &bytes, 0, req);
393 	if (error || !req->newptr)
394 		return (error);
395 
396 	pages = bytes / PAGE_SIZE;
397 	if (pages < TMPFS_PAGES_MINRESERVED)
398 		return (EINVAL);
399 
400 	*(long *)arg1 = pages;
401 	return (0);
402 }
403 
404 SYSCTL_PROC(_vfs_tmpfs, OID_AUTO, memory_reserved,
405     CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &tmpfs_pages_reserved, 0,
406     sysctl_mem_reserved, "L",
407     "Amount of available memory and swap below which tmpfs growth stops");
408 
409 static __inline int tmpfs_dirtree_cmp(struct tmpfs_dirent *a,
410     struct tmpfs_dirent *b);
411 RB_PROTOTYPE_STATIC(tmpfs_dir, tmpfs_dirent, uh.td_entries, tmpfs_dirtree_cmp);
412 
413 size_t
tmpfs_mem_avail(void)414 tmpfs_mem_avail(void)
415 {
416 	size_t avail;
417 	long reserved;
418 
419 	avail = swap_pager_avail + vm_free_count();
420 	reserved = atomic_load_long(&tmpfs_pages_reserved);
421 	if (__predict_false(avail < reserved))
422 		return (0);
423 	return (avail - reserved);
424 }
425 
426 size_t
tmpfs_pages_used(struct tmpfs_mount * tmp)427 tmpfs_pages_used(struct tmpfs_mount *tmp)
428 {
429 	const size_t node_size = sizeof(struct tmpfs_node) +
430 	    sizeof(struct tmpfs_dirent);
431 	size_t meta_pages;
432 
433 	meta_pages = howmany((uintmax_t)tmp->tm_nodes_inuse * node_size,
434 	    PAGE_SIZE);
435 	return (meta_pages + tmp->tm_pages_used);
436 }
437 
438 bool
tmpfs_pages_check_avail(struct tmpfs_mount * tmp,size_t req_pages)439 tmpfs_pages_check_avail(struct tmpfs_mount *tmp, size_t req_pages)
440 {
441 	if (tmpfs_mem_avail() < req_pages)
442 		return (false);
443 
444 	if (tmp->tm_pages_max != ULONG_MAX &&
445 	    tmp->tm_pages_max < req_pages + tmpfs_pages_used(tmp))
446 		return (false);
447 
448 	return (true);
449 }
450 
451 static int
tmpfs_partial_page_invalidate(vm_object_t object,vm_pindex_t idx,int base,int end,boolean_t ignerr)452 tmpfs_partial_page_invalidate(vm_object_t object, vm_pindex_t idx, int base,
453     int end, boolean_t ignerr)
454 {
455 	vm_page_t m;
456 	int rv, error;
457 
458 	VM_OBJECT_ASSERT_WLOCKED(object);
459 	KASSERT(base >= 0, ("%s: base %d", __func__, base));
460 	KASSERT(end - base <= PAGE_SIZE, ("%s: base %d end %d", __func__, base,
461 	    end));
462 	error = 0;
463 
464 retry:
465 	m = vm_page_grab(object, idx, VM_ALLOC_NOCREAT);
466 	if (m != NULL) {
467 		MPASS(vm_page_all_valid(m));
468 	} else if (vm_pager_has_page(object, idx, NULL, NULL)) {
469 		m = vm_page_alloc(object, idx, VM_ALLOC_NORMAL |
470 		    VM_ALLOC_WAITFAIL);
471 		if (m == NULL)
472 			goto retry;
473 		vm_object_pip_add(object, 1);
474 		VM_OBJECT_WUNLOCK(object);
475 		rv = vm_pager_get_pages(object, &m, 1, NULL, NULL);
476 		VM_OBJECT_WLOCK(object);
477 		vm_object_pip_wakeup(object);
478 		if (rv == VM_PAGER_OK) {
479 			/*
480 			 * Since the page was not resident, and therefore not
481 			 * recently accessed, immediately enqueue it for
482 			 * asynchronous laundering.  The current operation is
483 			 * not regarded as an access.
484 			 */
485 			vm_page_launder(m);
486 		} else {
487 			vm_page_free(m);
488 			m = NULL;
489 			if (!ignerr)
490 				error = EIO;
491 		}
492 	}
493 	if (m != NULL) {
494 		pmap_zero_page_area(m, base, end - base);
495 		vm_page_set_dirty(m);
496 		vm_page_xunbusy(m);
497 	}
498 
499 	return (error);
500 }
501 
502 void
tmpfs_ref_node(struct tmpfs_node * node)503 tmpfs_ref_node(struct tmpfs_node *node)
504 {
505 #ifdef INVARIANTS
506 	u_int old;
507 
508 	old =
509 #endif
510 	refcount_acquire(&node->tn_refcount);
511 #ifdef INVARIANTS
512 	KASSERT(old > 0, ("node %p zero refcount", node));
513 #endif
514 }
515 
516 /*
517  * Allocates a new node of type 'type' inside the 'tmp' mount point, with
518  * its owner set to 'uid', its group to 'gid' and its mode set to 'mode',
519  * using the credentials of the process 'p'.
520  *
521  * If the node type is set to 'VDIR', then the parent parameter must point
522  * to the parent directory of the node being created.  It may only be NULL
523  * while allocating the root node.
524  *
525  * If the node type is set to 'VBLK' or 'VCHR', then the rdev parameter
526  * specifies the device the node represents.
527  *
528  * If the node type is set to 'VLNK', then the parameter target specifies
529  * the file name of the target file for the symbolic link that is being
530  * created.
531  *
532  * Note that new nodes are retrieved from the available list if it has
533  * items or, if it is empty, from the node pool as long as there is enough
534  * space to create them.
535  *
536  * Returns zero on success or an appropriate error code on failure.
537  */
538 int
tmpfs_alloc_node(struct mount * mp,struct tmpfs_mount * tmp,__enum_uint8 (vtype)type,uid_t uid,gid_t gid,mode_t mode,struct tmpfs_node * parent,const char * target,dev_t rdev,struct tmpfs_node ** node)539 tmpfs_alloc_node(struct mount *mp, struct tmpfs_mount *tmp, __enum_uint8(vtype) type,
540     uid_t uid, gid_t gid, mode_t mode, struct tmpfs_node *parent,
541     const char *target, dev_t rdev, struct tmpfs_node **node)
542 {
543 	struct tmpfs_node *nnode;
544 	char *symlink;
545 	char symlink_smr;
546 
547 	/* If the root directory of the 'tmp' file system is not yet
548 	 * allocated, this must be the request to do it. */
549 	MPASS(IMPLIES(tmp->tm_root == NULL, parent == NULL && type == VDIR));
550 
551 	MPASS((type == VLNK) ^ (target == NULL));
552 	MPASS((type == VBLK || type == VCHR) ^ (rdev == VNOVAL));
553 
554 	if (tmp->tm_nodes_inuse >= tmp->tm_nodes_max)
555 		return (ENOSPC);
556 	if (!tmpfs_pages_check_avail(tmp, 1))
557 		return (ENOSPC);
558 
559 	if ((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0) {
560 		/*
561 		 * When a new tmpfs node is created for fully
562 		 * constructed mount point, there must be a parent
563 		 * node, which vnode is locked exclusively.  As
564 		 * consequence, if the unmount is executing in
565 		 * parallel, vflush() cannot reclaim the parent vnode.
566 		 * Due to this, the check for MNTK_UNMOUNT flag is not
567 		 * racy: if we did not see MNTK_UNMOUNT flag, then tmp
568 		 * cannot be destroyed until node construction is
569 		 * finished and the parent vnode unlocked.
570 		 *
571 		 * Tmpfs does not need to instantiate new nodes during
572 		 * unmount.
573 		 */
574 		return (EBUSY);
575 	}
576 	if ((mp->mnt_kern_flag & MNT_RDONLY) != 0)
577 		return (EROFS);
578 
579 	nnode = uma_zalloc_smr(tmpfs_node_pool, M_WAITOK);
580 
581 	/* Generic initialization. */
582 	nnode->tn_type = type;
583 	vfs_timestamp(&nnode->tn_atime);
584 	nnode->tn_birthtime = nnode->tn_ctime = nnode->tn_mtime =
585 	    nnode->tn_atime;
586 	nnode->tn_uid = uid;
587 	nnode->tn_gid = gid;
588 	nnode->tn_mode = mode;
589 	nnode->tn_id = alloc_unr64(&tmp->tm_ino_unr);
590 	nnode->tn_refcount = 1;
591 	LIST_INIT(&nnode->tn_extattrs);
592 
593 	/* Type-specific initialization. */
594 	switch (nnode->tn_type) {
595 	case VBLK:
596 	case VCHR:
597 		nnode->tn_rdev = rdev;
598 		break;
599 
600 	case VDIR:
601 		RB_INIT(&nnode->tn_dir.tn_dirhead);
602 		LIST_INIT(&nnode->tn_dir.tn_dupindex);
603 		MPASS(parent != nnode);
604 		MPASS(IMPLIES(parent == NULL, tmp->tm_root == NULL));
605 		nnode->tn_dir.tn_parent = (parent == NULL) ? nnode : parent;
606 		nnode->tn_dir.tn_readdir_lastn = 0;
607 		nnode->tn_dir.tn_readdir_lastp = NULL;
608 		nnode->tn_links++;
609 		TMPFS_NODE_LOCK(nnode->tn_dir.tn_parent);
610 		nnode->tn_dir.tn_parent->tn_links++;
611 		TMPFS_NODE_UNLOCK(nnode->tn_dir.tn_parent);
612 		break;
613 
614 	case VFIFO:
615 		/* FALLTHROUGH */
616 	case VSOCK:
617 		break;
618 
619 	case VLNK:
620 		MPASS(strlen(target) < MAXPATHLEN);
621 		nnode->tn_size = strlen(target);
622 
623 		symlink = NULL;
624 		if (!tmp->tm_nonc) {
625 			symlink = cache_symlink_alloc(nnode->tn_size + 1,
626 			    M_WAITOK);
627 			symlink_smr = true;
628 		}
629 		if (symlink == NULL) {
630 			symlink = malloc(nnode->tn_size + 1, M_TMPFSNAME,
631 			    M_WAITOK);
632 			symlink_smr = false;
633 		}
634 		memcpy(symlink, target, nnode->tn_size + 1);
635 
636 		/*
637 		 * Allow safe symlink resolving for lockless lookup.
638 		 * tmpfs_fplookup_symlink references this comment.
639 		 *
640 		 * 1. nnode is not yet visible to the world
641 		 * 2. both tn_link_target and tn_link_smr get populated
642 		 * 3. release fence publishes their content
643 		 * 4. tn_link_target content is immutable until node
644 		 *    destruction, where the pointer gets set to NULL
645 		 * 5. tn_link_smr is never changed once set
646 		 *
647 		 * As a result it is sufficient to issue load consume
648 		 * on the node pointer to also get the above content
649 		 * in a stable manner.  Worst case tn_link_smr flag
650 		 * may be set to true despite being stale, while the
651 		 * target buffer is already cleared out.
652 		 */
653 		atomic_store_ptr(&nnode->tn_link_target, symlink);
654 		atomic_store_char((char *)&nnode->tn_link_smr, symlink_smr);
655 		atomic_thread_fence_rel();
656 		break;
657 
658 	case VREG:
659 		nnode->tn_reg.tn_aobj =
660 		    vm_pager_allocate(tmpfs_pager_type, NULL, 0,
661 		    VM_PROT_DEFAULT, 0,
662 		    NULL /* XXXKIB - tmpfs needs swap reservation */);
663 		nnode->tn_reg.tn_aobj->un_pager.swp.swp_priv = nnode;
664 		vm_object_set_flag(nnode->tn_reg.tn_aobj, OBJ_TMPFS);
665 		nnode->tn_reg.tn_tmp = tmp;
666 		nnode->tn_reg.tn_pages = 0;
667 		break;
668 
669 	default:
670 		panic("tmpfs_alloc_node: type %p %d", nnode,
671 		    (int)nnode->tn_type);
672 	}
673 
674 	TMPFS_LOCK(tmp);
675 	LIST_INSERT_HEAD(&tmp->tm_nodes_used, nnode, tn_entries);
676 	nnode->tn_attached = true;
677 	tmp->tm_nodes_inuse++;
678 	tmp->tm_refcount++;
679 	TMPFS_UNLOCK(tmp);
680 
681 	*node = nnode;
682 	return (0);
683 }
684 
685 /*
686  * Destroys the node pointed to by node from the file system 'tmp'.
687  * If the node references a directory, no entries are allowed.
688  */
689 void
tmpfs_free_node(struct tmpfs_mount * tmp,struct tmpfs_node * node)690 tmpfs_free_node(struct tmpfs_mount *tmp, struct tmpfs_node *node)
691 {
692 	if (refcount_release_if_not_last(&node->tn_refcount))
693 		return;
694 
695 	TMPFS_LOCK(tmp);
696 	TMPFS_NODE_LOCK(node);
697 	if (!tmpfs_free_node_locked(tmp, node, false)) {
698 		TMPFS_NODE_UNLOCK(node);
699 		TMPFS_UNLOCK(tmp);
700 	}
701 }
702 
703 bool
tmpfs_free_node_locked(struct tmpfs_mount * tmp,struct tmpfs_node * node,bool detach)704 tmpfs_free_node_locked(struct tmpfs_mount *tmp, struct tmpfs_node *node,
705     bool detach)
706 {
707 	struct tmpfs_extattr *ea;
708 	vm_object_t uobj;
709 	char *symlink;
710 	bool last;
711 
712 	TMPFS_MP_ASSERT_LOCKED(tmp);
713 	TMPFS_NODE_ASSERT_LOCKED(node);
714 
715 	last = refcount_release(&node->tn_refcount);
716 	if (node->tn_attached && (detach || last)) {
717 		MPASS(tmp->tm_nodes_inuse > 0);
718 		tmp->tm_nodes_inuse--;
719 		LIST_REMOVE(node, tn_entries);
720 		node->tn_attached = false;
721 	}
722 	if (!last)
723 		return (false);
724 
725 	TMPFS_NODE_UNLOCK(node);
726 
727 #ifdef INVARIANTS
728 	MPASS(node->tn_vnode == NULL);
729 	MPASS((node->tn_vpstate & TMPFS_VNODE_ALLOCATING) == 0);
730 
731 	/*
732 	 * Make sure this is a node type we can deal with. Everything
733 	 * is explicitly enumerated without the 'default' clause so
734 	 * the compiler can throw an error in case a new type is
735 	 * added.
736 	 */
737 	switch (node->tn_type) {
738 	case VBLK:
739 	case VCHR:
740 	case VDIR:
741 	case VFIFO:
742 	case VSOCK:
743 	case VLNK:
744 	case VREG:
745 		break;
746 	case VNON:
747 	case VBAD:
748 	case VMARKER:
749 		panic("%s: bad type %d for node %p", __func__,
750 		    (int)node->tn_type, node);
751 	}
752 #endif
753 
754 	while ((ea = LIST_FIRST(&node->tn_extattrs)) != NULL) {
755 		LIST_REMOVE(ea, ea_extattrs);
756 		tmpfs_extattr_free(ea);
757 	}
758 
759 	switch (node->tn_type) {
760 	case VREG:
761 		uobj = node->tn_reg.tn_aobj;
762 		node->tn_reg.tn_aobj = NULL;
763 		if (uobj != NULL) {
764 			VM_OBJECT_WLOCK(uobj);
765 			KASSERT((uobj->flags & OBJ_TMPFS) != 0,
766 			    ("tmpfs node %p uobj %p not tmpfs", node, uobj));
767 			vm_object_clear_flag(uobj, OBJ_TMPFS);
768 			KASSERT(tmp->tm_pages_used >= node->tn_reg.tn_pages,
769 			    ("tmpfs tmp %p node %p pages %jd free %jd", tmp,
770 			    node, (uintmax_t)tmp->tm_pages_used,
771 			    (uintmax_t)node->tn_reg.tn_pages));
772 			atomic_add_long(&tmp->tm_pages_used,
773 			    -node->tn_reg.tn_pages);
774 			VM_OBJECT_WUNLOCK(uobj);
775 		}
776 		tmpfs_free_tmp(tmp);
777 
778 		/*
779 		 * vm_object_deallocate() must not be called while
780 		 * owning tm_allnode_lock, because deallocate might
781 		 * sleep.  Call it after tmpfs_free_tmp() does the
782 		 * unlock.
783 		 */
784 		if (uobj != NULL)
785 			vm_object_deallocate(uobj);
786 
787 		break;
788 	case VLNK:
789 		tmpfs_free_tmp(tmp);
790 
791 		symlink = node->tn_link_target;
792 		atomic_store_ptr(&node->tn_link_target, NULL);
793 		if (atomic_load_char(&node->tn_link_smr)) {
794 			cache_symlink_free(symlink, node->tn_size + 1);
795 		} else {
796 			free(symlink, M_TMPFSNAME);
797 		}
798 		break;
799 	default:
800 		tmpfs_free_tmp(tmp);
801 		break;
802 	}
803 
804 	uma_zfree_smr(tmpfs_node_pool, node);
805 	return (true);
806 }
807 
808 static __inline uint32_t
tmpfs_dirent_hash(const char * name,u_int len)809 tmpfs_dirent_hash(const char *name, u_int len)
810 {
811 	uint32_t hash;
812 
813 	hash = fnv_32_buf(name, len, FNV1_32_INIT + len) & TMPFS_DIRCOOKIE_MASK;
814 #ifdef TMPFS_DEBUG_DIRCOOKIE_DUP
815 	hash &= 0xf;
816 #endif
817 	if (hash < TMPFS_DIRCOOKIE_MIN)
818 		hash += TMPFS_DIRCOOKIE_MIN;
819 
820 	return (hash);
821 }
822 
823 static __inline off_t
tmpfs_dirent_cookie(struct tmpfs_dirent * de)824 tmpfs_dirent_cookie(struct tmpfs_dirent *de)
825 {
826 	if (de == NULL)
827 		return (TMPFS_DIRCOOKIE_EOF);
828 
829 	MPASS(de->td_cookie >= TMPFS_DIRCOOKIE_MIN);
830 
831 	return (de->td_cookie);
832 }
833 
834 static __inline boolean_t
tmpfs_dirent_dup(struct tmpfs_dirent * de)835 tmpfs_dirent_dup(struct tmpfs_dirent *de)
836 {
837 	return ((de->td_cookie & TMPFS_DIRCOOKIE_DUP) != 0);
838 }
839 
840 static __inline boolean_t
tmpfs_dirent_duphead(struct tmpfs_dirent * de)841 tmpfs_dirent_duphead(struct tmpfs_dirent *de)
842 {
843 	return ((de->td_cookie & TMPFS_DIRCOOKIE_DUPHEAD) != 0);
844 }
845 
846 void
tmpfs_dirent_init(struct tmpfs_dirent * de,const char * name,u_int namelen)847 tmpfs_dirent_init(struct tmpfs_dirent *de, const char *name, u_int namelen)
848 {
849 	de->td_hash = de->td_cookie = tmpfs_dirent_hash(name, namelen);
850 	memcpy(de->ud.td_name, name, namelen);
851 	de->td_namelen = namelen;
852 }
853 
854 /*
855  * Allocates a new directory entry for the node node with a name of name.
856  * The new directory entry is returned in *de.
857  *
858  * The link count of node is increased by one to reflect the new object
859  * referencing it.
860  *
861  * Returns zero on success or an appropriate error code on failure.
862  */
863 int
tmpfs_alloc_dirent(struct tmpfs_mount * tmp,struct tmpfs_node * node,const char * name,u_int len,struct tmpfs_dirent ** de)864 tmpfs_alloc_dirent(struct tmpfs_mount *tmp, struct tmpfs_node *node,
865     const char *name, u_int len, struct tmpfs_dirent **de)
866 {
867 	struct tmpfs_dirent *nde;
868 
869 	nde = malloc(sizeof(*nde), M_TMPFSDIR, M_WAITOK);
870 	nde->td_node = node;
871 	if (name != NULL) {
872 		nde->ud.td_name = malloc(len, M_TMPFSNAME, M_WAITOK);
873 		tmpfs_dirent_init(nde, name, len);
874 	} else
875 		nde->td_namelen = 0;
876 	if (node != NULL)
877 		node->tn_links++;
878 
879 	*de = nde;
880 
881 	return (0);
882 }
883 
884 /*
885  * Frees a directory entry.  It is the caller's responsibility to destroy
886  * the node referenced by it if needed.
887  *
888  * The link count of node is decreased by one to reflect the removal of an
889  * object that referenced it.  This only happens if 'node_exists' is true;
890  * otherwise the function will not access the node referred to by the
891  * directory entry, as it may already have been released from the outside.
892  */
893 void
tmpfs_free_dirent(struct tmpfs_mount * tmp,struct tmpfs_dirent * de)894 tmpfs_free_dirent(struct tmpfs_mount *tmp, struct tmpfs_dirent *de)
895 {
896 	struct tmpfs_node *node;
897 
898 	node = de->td_node;
899 	if (node != NULL) {
900 		MPASS(node->tn_links > 0);
901 		node->tn_links--;
902 	}
903 	if (!tmpfs_dirent_duphead(de) && de->ud.td_name != NULL)
904 		free(de->ud.td_name, M_TMPFSNAME);
905 	free(de, M_TMPFSDIR);
906 }
907 
908 void
tmpfs_destroy_vobject(struct vnode * vp,vm_object_t obj)909 tmpfs_destroy_vobject(struct vnode *vp, vm_object_t obj)
910 {
911 	bool want_vrele;
912 
913 	ASSERT_VOP_ELOCKED(vp, "tmpfs_destroy_vobject");
914 	if (vp->v_type != VREG || obj == NULL)
915 		return;
916 
917 	VM_OBJECT_WLOCK(obj);
918 	VI_LOCK(vp);
919 	vp->v_object = NULL;
920 
921 	/*
922 	 * May be going through forced unmount.
923 	 */
924 	want_vrele = false;
925 	if ((obj->flags & OBJ_TMPFS_VREF) != 0) {
926 		vm_object_clear_flag(obj, OBJ_TMPFS_VREF);
927 		want_vrele = true;
928 	}
929 
930 	if (vp->v_writecount < 0)
931 		vp->v_writecount = 0;
932 	VI_UNLOCK(vp);
933 	VM_OBJECT_WUNLOCK(obj);
934 	if (want_vrele) {
935 		vrele(vp);
936 	}
937 }
938 
939 /*
940  * Allocates a new vnode for the node node or returns a new reference to
941  * an existing one if the node had already a vnode referencing it.  The
942  * resulting locked vnode is returned in *vpp.
943  *
944  * Returns zero on success or an appropriate error code on failure.
945  */
946 int
tmpfs_alloc_vp(struct mount * mp,struct tmpfs_node * node,int lkflag,struct vnode ** vpp)947 tmpfs_alloc_vp(struct mount *mp, struct tmpfs_node *node, int lkflag,
948     struct vnode **vpp)
949 {
950 	struct vnode *vp;
951 	enum vgetstate vs;
952 	struct tmpfs_mount *tm;
953 	vm_object_t object;
954 	int error;
955 
956 	error = 0;
957 	tm = VFS_TO_TMPFS(mp);
958 	TMPFS_NODE_LOCK(node);
959 	tmpfs_ref_node(node);
960 loop:
961 	TMPFS_NODE_ASSERT_LOCKED(node);
962 	if ((vp = node->tn_vnode) != NULL) {
963 		MPASS((node->tn_vpstate & TMPFS_VNODE_DOOMED) == 0);
964 		if ((node->tn_type == VDIR && node->tn_dir.tn_parent == NULL) ||
965 		    (VN_IS_DOOMED(vp) &&
966 		     (lkflag & LK_NOWAIT) != 0)) {
967 			TMPFS_NODE_UNLOCK(node);
968 			error = ENOENT;
969 			vp = NULL;
970 			goto out;
971 		}
972 		if (VN_IS_DOOMED(vp)) {
973 			node->tn_vpstate |= TMPFS_VNODE_WRECLAIM;
974 			while ((node->tn_vpstate & TMPFS_VNODE_WRECLAIM) != 0) {
975 				msleep(&node->tn_vnode, TMPFS_NODE_MTX(node),
976 				    0, "tmpfsE", 0);
977 			}
978 			goto loop;
979 		}
980 		vs = vget_prep(vp);
981 		TMPFS_NODE_UNLOCK(node);
982 		error = vget_finish(vp, lkflag, vs);
983 		if (error == ENOENT) {
984 			TMPFS_NODE_LOCK(node);
985 			goto loop;
986 		}
987 		if (error != 0) {
988 			vp = NULL;
989 			goto out;
990 		}
991 
992 		/*
993 		 * Make sure the vnode is still there after
994 		 * getting the interlock to avoid racing a free.
995 		 */
996 		if (node->tn_vnode != vp) {
997 			vput(vp);
998 			TMPFS_NODE_LOCK(node);
999 			goto loop;
1000 		}
1001 
1002 		goto out;
1003 	}
1004 
1005 	if ((node->tn_vpstate & TMPFS_VNODE_DOOMED) ||
1006 	    (node->tn_type == VDIR && node->tn_dir.tn_parent == NULL)) {
1007 		TMPFS_NODE_UNLOCK(node);
1008 		error = ENOENT;
1009 		vp = NULL;
1010 		goto out;
1011 	}
1012 
1013 	/*
1014 	 * otherwise lock the vp list while we call getnewvnode
1015 	 * since that can block.
1016 	 */
1017 	if (node->tn_vpstate & TMPFS_VNODE_ALLOCATING) {
1018 		node->tn_vpstate |= TMPFS_VNODE_WANT;
1019 		error = msleep((caddr_t) &node->tn_vpstate,
1020 		    TMPFS_NODE_MTX(node), 0, "tmpfs_alloc_vp", 0);
1021 		if (error != 0)
1022 			goto out;
1023 		goto loop;
1024 	} else
1025 		node->tn_vpstate |= TMPFS_VNODE_ALLOCATING;
1026 
1027 	TMPFS_NODE_UNLOCK(node);
1028 
1029 	/* Get a new vnode and associate it with our node. */
1030 	error = getnewvnode("tmpfs", mp, VFS_TO_TMPFS(mp)->tm_nonc ?
1031 	    &tmpfs_vnodeop_nonc_entries : &tmpfs_vnodeop_entries, &vp);
1032 	if (error != 0)
1033 		goto unlock;
1034 	MPASS(vp != NULL);
1035 
1036 	/* lkflag is ignored, the lock is exclusive */
1037 	(void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1038 
1039 	vp->v_data = node;
1040 	vp->v_type = node->tn_type;
1041 
1042 	/* Type-specific initialization. */
1043 	switch (node->tn_type) {
1044 	case VBLK:
1045 		/* FALLTHROUGH */
1046 	case VCHR:
1047 		/* FALLTHROUGH */
1048 	case VLNK:
1049 		/* FALLTHROUGH */
1050 	case VSOCK:
1051 		break;
1052 	case VFIFO:
1053 		vp->v_op = &tmpfs_fifoop_entries;
1054 		break;
1055 	case VREG:
1056 		object = node->tn_reg.tn_aobj;
1057 		VM_OBJECT_WLOCK(object);
1058 		KASSERT((object->flags & OBJ_TMPFS_VREF) == 0,
1059 		    ("%s: object %p with OBJ_TMPFS_VREF but without vnode",
1060 		    __func__, object));
1061 		VI_LOCK(vp);
1062 		KASSERT(vp->v_object == NULL, ("Not NULL v_object in tmpfs"));
1063 		vp->v_object = object;
1064 		vn_irflag_set_locked(vp, (tm->tm_pgread ? VIRF_PGREAD : 0) |
1065 		    VIRF_TEXT_REF);
1066 		VI_UNLOCK(vp);
1067 		VNASSERT((object->flags & OBJ_TMPFS_VREF) == 0, vp,
1068 		    ("leaked OBJ_TMPFS_VREF"));
1069 		if (object->un_pager.swp.writemappings > 0) {
1070 			vrefact(vp);
1071 			vlazy(vp);
1072 			vm_object_set_flag(object, OBJ_TMPFS_VREF);
1073 		}
1074 		VM_OBJECT_WUNLOCK(object);
1075 		break;
1076 	case VDIR:
1077 		MPASS(node->tn_dir.tn_parent != NULL);
1078 		if (node->tn_dir.tn_parent == node)
1079 			vp->v_vflag |= VV_ROOT;
1080 		break;
1081 
1082 	default:
1083 		panic("tmpfs_alloc_vp: type %p %d", node, (int)node->tn_type);
1084 	}
1085 	if (vp->v_type != VFIFO)
1086 		VN_LOCK_ASHARE(vp);
1087 
1088 	error = insmntque1(vp, mp);
1089 	if (error != 0) {
1090 		/* Need to clear v_object for insmntque failure. */
1091 		tmpfs_destroy_vobject(vp, vp->v_object);
1092 		vp->v_object = NULL;
1093 		vp->v_data = NULL;
1094 		vp->v_op = &dead_vnodeops;
1095 		vgone(vp);
1096 		vput(vp);
1097 		vp = NULL;
1098 	} else {
1099 		vn_set_state(vp, VSTATE_CONSTRUCTED);
1100 	}
1101 
1102 unlock:
1103 	TMPFS_NODE_LOCK(node);
1104 
1105 	MPASS(node->tn_vpstate & TMPFS_VNODE_ALLOCATING);
1106 	node->tn_vpstate &= ~TMPFS_VNODE_ALLOCATING;
1107 	node->tn_vnode = vp;
1108 
1109 	if (node->tn_vpstate & TMPFS_VNODE_WANT) {
1110 		node->tn_vpstate &= ~TMPFS_VNODE_WANT;
1111 		TMPFS_NODE_UNLOCK(node);
1112 		wakeup((caddr_t) &node->tn_vpstate);
1113 	} else
1114 		TMPFS_NODE_UNLOCK(node);
1115 
1116 out:
1117 	if (error == 0) {
1118 		*vpp = vp;
1119 
1120 #ifdef INVARIANTS
1121 		MPASS(*vpp != NULL);
1122 		ASSERT_VOP_LOCKED(*vpp, __func__);
1123 		TMPFS_NODE_LOCK(node);
1124 		MPASS(*vpp == node->tn_vnode);
1125 		TMPFS_NODE_UNLOCK(node);
1126 #endif
1127 	}
1128 	tmpfs_free_node(tm, node);
1129 
1130 	return (error);
1131 }
1132 
1133 /*
1134  * Destroys the association between the vnode vp and the node it
1135  * references.
1136  */
1137 void
tmpfs_free_vp(struct vnode * vp)1138 tmpfs_free_vp(struct vnode *vp)
1139 {
1140 	struct tmpfs_node *node;
1141 
1142 	node = VP_TO_TMPFS_NODE(vp);
1143 
1144 	TMPFS_NODE_ASSERT_LOCKED(node);
1145 	node->tn_vnode = NULL;
1146 	if ((node->tn_vpstate & TMPFS_VNODE_WRECLAIM) != 0)
1147 		wakeup(&node->tn_vnode);
1148 	node->tn_vpstate &= ~TMPFS_VNODE_WRECLAIM;
1149 	vp->v_data = NULL;
1150 }
1151 
1152 /*
1153  * Allocates a new file of type 'type' and adds it to the parent directory
1154  * 'dvp'; this addition is done using the component name given in 'cnp'.
1155  * The ownership of the new file is automatically assigned based on the
1156  * credentials of the caller (through 'cnp'), the group is set based on
1157  * the parent directory and the mode is determined from the 'vap' argument.
1158  * If successful, *vpp holds a vnode to the newly created file and zero
1159  * is returned.  Otherwise *vpp is NULL and the function returns an
1160  * appropriate error code.
1161  */
1162 int
tmpfs_alloc_file(struct vnode * dvp,struct vnode ** vpp,struct vattr * vap,struct componentname * cnp,const char * target)1163 tmpfs_alloc_file(struct vnode *dvp, struct vnode **vpp, struct vattr *vap,
1164     struct componentname *cnp, const char *target)
1165 {
1166 	int error;
1167 	struct tmpfs_dirent *de;
1168 	struct tmpfs_mount *tmp;
1169 	struct tmpfs_node *dnode;
1170 	struct tmpfs_node *node;
1171 	struct tmpfs_node *parent;
1172 
1173 	ASSERT_VOP_ELOCKED(dvp, "tmpfs_alloc_file");
1174 
1175 	tmp = VFS_TO_TMPFS(dvp->v_mount);
1176 	dnode = VP_TO_TMPFS_DIR(dvp);
1177 	*vpp = NULL;
1178 
1179 	/* If the entry we are creating is a directory, we cannot overflow
1180 	 * the number of links of its parent, because it will get a new
1181 	 * link. */
1182 	if (vap->va_type == VDIR) {
1183 		/* Ensure that we do not overflow the maximum number of links
1184 		 * imposed by the system. */
1185 		MPASS(dnode->tn_links <= TMPFS_LINK_MAX);
1186 		if (dnode->tn_links == TMPFS_LINK_MAX) {
1187 			return (EMLINK);
1188 		}
1189 
1190 		parent = dnode;
1191 		MPASS(parent != NULL);
1192 	} else
1193 		parent = NULL;
1194 
1195 	/* Allocate a node that represents the new file. */
1196 	error = tmpfs_alloc_node(dvp->v_mount, tmp, vap->va_type,
1197 	    cnp->cn_cred->cr_uid, dnode->tn_gid, vap->va_mode, parent,
1198 	    target, vap->va_rdev, &node);
1199 	if (error != 0)
1200 		return (error);
1201 
1202 	/* Allocate a directory entry that points to the new file. */
1203 	error = tmpfs_alloc_dirent(tmp, node, cnp->cn_nameptr, cnp->cn_namelen,
1204 	    &de);
1205 	if (error != 0) {
1206 		tmpfs_free_node(tmp, node);
1207 		return (error);
1208 	}
1209 
1210 	/* Allocate a vnode for the new file. */
1211 	error = tmpfs_alloc_vp(dvp->v_mount, node, LK_EXCLUSIVE, vpp);
1212 	if (error != 0) {
1213 		tmpfs_free_dirent(tmp, de);
1214 		tmpfs_free_node(tmp, node);
1215 		return (error);
1216 	}
1217 
1218 	/* Now that all required items are allocated, we can proceed to
1219 	 * insert the new node into the directory, an operation that
1220 	 * cannot fail. */
1221 	if (cnp->cn_flags & ISWHITEOUT)
1222 		tmpfs_dir_whiteout_remove(dvp, cnp);
1223 	tmpfs_dir_attach(dvp, de);
1224 	return (0);
1225 }
1226 
1227 struct tmpfs_dirent *
tmpfs_dir_first(struct tmpfs_node * dnode,struct tmpfs_dir_cursor * dc)1228 tmpfs_dir_first(struct tmpfs_node *dnode, struct tmpfs_dir_cursor *dc)
1229 {
1230 	struct tmpfs_dirent *de;
1231 
1232 	de = RB_MIN(tmpfs_dir, &dnode->tn_dir.tn_dirhead);
1233 	dc->tdc_tree = de;
1234 	if (de != NULL && tmpfs_dirent_duphead(de))
1235 		de = LIST_FIRST(&de->ud.td_duphead);
1236 	dc->tdc_current = de;
1237 
1238 	return (dc->tdc_current);
1239 }
1240 
1241 struct tmpfs_dirent *
tmpfs_dir_next(struct tmpfs_node * dnode,struct tmpfs_dir_cursor * dc)1242 tmpfs_dir_next(struct tmpfs_node *dnode, struct tmpfs_dir_cursor *dc)
1243 {
1244 	struct tmpfs_dirent *de;
1245 
1246 	MPASS(dc->tdc_tree != NULL);
1247 	if (tmpfs_dirent_dup(dc->tdc_current)) {
1248 		dc->tdc_current = LIST_NEXT(dc->tdc_current, uh.td_dup.entries);
1249 		if (dc->tdc_current != NULL)
1250 			return (dc->tdc_current);
1251 	}
1252 	dc->tdc_tree = dc->tdc_current = RB_NEXT(tmpfs_dir,
1253 	    &dnode->tn_dir.tn_dirhead, dc->tdc_tree);
1254 	if ((de = dc->tdc_current) != NULL && tmpfs_dirent_duphead(de)) {
1255 		dc->tdc_current = LIST_FIRST(&de->ud.td_duphead);
1256 		MPASS(dc->tdc_current != NULL);
1257 	}
1258 
1259 	return (dc->tdc_current);
1260 }
1261 
1262 /* Lookup directory entry in RB-Tree. Function may return duphead entry. */
1263 static struct tmpfs_dirent *
tmpfs_dir_xlookup_hash(struct tmpfs_node * dnode,uint32_t hash)1264 tmpfs_dir_xlookup_hash(struct tmpfs_node *dnode, uint32_t hash)
1265 {
1266 	struct tmpfs_dirent *de, dekey;
1267 
1268 	dekey.td_hash = hash;
1269 	de = RB_FIND(tmpfs_dir, &dnode->tn_dir.tn_dirhead, &dekey);
1270 	return (de);
1271 }
1272 
1273 /* Lookup directory entry by cookie, initialize directory cursor accordingly. */
1274 static struct tmpfs_dirent *
tmpfs_dir_lookup_cookie(struct tmpfs_node * node,off_t cookie,struct tmpfs_dir_cursor * dc)1275 tmpfs_dir_lookup_cookie(struct tmpfs_node *node, off_t cookie,
1276     struct tmpfs_dir_cursor *dc)
1277 {
1278 	struct tmpfs_dir *dirhead = &node->tn_dir.tn_dirhead;
1279 	struct tmpfs_dirent *de, dekey;
1280 
1281 	MPASS(cookie >= TMPFS_DIRCOOKIE_MIN);
1282 
1283 	if (cookie == node->tn_dir.tn_readdir_lastn &&
1284 	    (de = node->tn_dir.tn_readdir_lastp) != NULL) {
1285 		/* Protect against possible race, tn_readdir_last[pn]
1286 		 * may be updated with only shared vnode lock held. */
1287 		if (cookie == tmpfs_dirent_cookie(de))
1288 			goto out;
1289 	}
1290 
1291 	if ((cookie & TMPFS_DIRCOOKIE_DUP) != 0) {
1292 		LIST_FOREACH(de, &node->tn_dir.tn_dupindex,
1293 		    uh.td_dup.index_entries) {
1294 			MPASS(tmpfs_dirent_dup(de));
1295 			if (de->td_cookie == cookie)
1296 				goto out;
1297 			/* dupindex list is sorted. */
1298 			if (de->td_cookie < cookie) {
1299 				de = NULL;
1300 				goto out;
1301 			}
1302 		}
1303 		MPASS(de == NULL);
1304 		goto out;
1305 	}
1306 
1307 	if ((cookie & TMPFS_DIRCOOKIE_MASK) != cookie) {
1308 		de = NULL;
1309 	} else {
1310 		dekey.td_hash = cookie;
1311 		/* Recover if direntry for cookie was removed */
1312 		de = RB_NFIND(tmpfs_dir, dirhead, &dekey);
1313 	}
1314 	dc->tdc_tree = de;
1315 	dc->tdc_current = de;
1316 	if (de != NULL && tmpfs_dirent_duphead(de)) {
1317 		dc->tdc_current = LIST_FIRST(&de->ud.td_duphead);
1318 		MPASS(dc->tdc_current != NULL);
1319 	}
1320 	return (dc->tdc_current);
1321 
1322 out:
1323 	dc->tdc_tree = de;
1324 	dc->tdc_current = de;
1325 	if (de != NULL && tmpfs_dirent_dup(de))
1326 		dc->tdc_tree = tmpfs_dir_xlookup_hash(node,
1327 		    de->td_hash);
1328 	return (dc->tdc_current);
1329 }
1330 
1331 /*
1332  * Looks for a directory entry in the directory represented by node.
1333  * 'cnp' describes the name of the entry to look for.  Note that the .
1334  * and .. components are not allowed as they do not physically exist
1335  * within directories.
1336  *
1337  * Returns a pointer to the entry when found, otherwise NULL.
1338  */
1339 struct tmpfs_dirent *
tmpfs_dir_lookup(struct tmpfs_node * node,struct tmpfs_node * f,struct componentname * cnp)1340 tmpfs_dir_lookup(struct tmpfs_node *node, struct tmpfs_node *f,
1341     struct componentname *cnp)
1342 {
1343 	struct tmpfs_dir_duphead *duphead;
1344 	struct tmpfs_dirent *de;
1345 	uint32_t hash;
1346 
1347 	MPASS(IMPLIES(cnp->cn_namelen == 1, cnp->cn_nameptr[0] != '.'));
1348 	MPASS(IMPLIES(cnp->cn_namelen == 2, !(cnp->cn_nameptr[0] == '.' &&
1349 	    cnp->cn_nameptr[1] == '.')));
1350 	TMPFS_VALIDATE_DIR(node);
1351 
1352 	hash = tmpfs_dirent_hash(cnp->cn_nameptr, cnp->cn_namelen);
1353 	de = tmpfs_dir_xlookup_hash(node, hash);
1354 	if (de != NULL && tmpfs_dirent_duphead(de)) {
1355 		duphead = &de->ud.td_duphead;
1356 		LIST_FOREACH(de, duphead, uh.td_dup.entries) {
1357 			if (TMPFS_DIRENT_MATCHES(de, cnp->cn_nameptr,
1358 			    cnp->cn_namelen))
1359 				break;
1360 		}
1361 	} else if (de != NULL) {
1362 		if (!TMPFS_DIRENT_MATCHES(de, cnp->cn_nameptr,
1363 		    cnp->cn_namelen))
1364 			de = NULL;
1365 	}
1366 	if (de != NULL && f != NULL && de->td_node != f)
1367 		de = NULL;
1368 
1369 	return (de);
1370 }
1371 
1372 /*
1373  * Attach duplicate-cookie directory entry nde to dnode and insert to dupindex
1374  * list, allocate new cookie value.
1375  */
1376 static void
tmpfs_dir_attach_dup(struct tmpfs_node * dnode,struct tmpfs_dir_duphead * duphead,struct tmpfs_dirent * nde)1377 tmpfs_dir_attach_dup(struct tmpfs_node *dnode,
1378     struct tmpfs_dir_duphead *duphead, struct tmpfs_dirent *nde)
1379 {
1380 	struct tmpfs_dir_duphead *dupindex;
1381 	struct tmpfs_dirent *de, *pde;
1382 
1383 	dupindex = &dnode->tn_dir.tn_dupindex;
1384 	de = LIST_FIRST(dupindex);
1385 	if (de == NULL || de->td_cookie < TMPFS_DIRCOOKIE_DUP_MAX) {
1386 		if (de == NULL)
1387 			nde->td_cookie = TMPFS_DIRCOOKIE_DUP_MIN;
1388 		else
1389 			nde->td_cookie = de->td_cookie + 1;
1390 		MPASS(tmpfs_dirent_dup(nde));
1391 		LIST_INSERT_HEAD(dupindex, nde, uh.td_dup.index_entries);
1392 		LIST_INSERT_HEAD(duphead, nde, uh.td_dup.entries);
1393 		return;
1394 	}
1395 
1396 	/*
1397 	 * Cookie numbers are near exhaustion. Scan dupindex list for unused
1398 	 * numbers. dupindex list is sorted in descending order. Keep it so
1399 	 * after inserting nde.
1400 	 */
1401 	while (1) {
1402 		pde = de;
1403 		de = LIST_NEXT(de, uh.td_dup.index_entries);
1404 		if (de == NULL && pde->td_cookie != TMPFS_DIRCOOKIE_DUP_MIN) {
1405 			/*
1406 			 * Last element of the index doesn't have minimal cookie
1407 			 * value, use it.
1408 			 */
1409 			nde->td_cookie = TMPFS_DIRCOOKIE_DUP_MIN;
1410 			LIST_INSERT_AFTER(pde, nde, uh.td_dup.index_entries);
1411 			LIST_INSERT_HEAD(duphead, nde, uh.td_dup.entries);
1412 			return;
1413 		} else if (de == NULL) {
1414 			/*
1415 			 * We are so lucky have 2^30 hash duplicates in single
1416 			 * directory :) Return largest possible cookie value.
1417 			 * It should be fine except possible issues with
1418 			 * VOP_READDIR restart.
1419 			 */
1420 			nde->td_cookie = TMPFS_DIRCOOKIE_DUP_MAX;
1421 			LIST_INSERT_HEAD(dupindex, nde,
1422 			    uh.td_dup.index_entries);
1423 			LIST_INSERT_HEAD(duphead, nde, uh.td_dup.entries);
1424 			return;
1425 		}
1426 		if (de->td_cookie + 1 == pde->td_cookie ||
1427 		    de->td_cookie >= TMPFS_DIRCOOKIE_DUP_MAX)
1428 			continue;	/* No hole or invalid cookie. */
1429 		nde->td_cookie = de->td_cookie + 1;
1430 		MPASS(tmpfs_dirent_dup(nde));
1431 		MPASS(pde->td_cookie > nde->td_cookie);
1432 		MPASS(nde->td_cookie > de->td_cookie);
1433 		LIST_INSERT_BEFORE(de, nde, uh.td_dup.index_entries);
1434 		LIST_INSERT_HEAD(duphead, nde, uh.td_dup.entries);
1435 		return;
1436 	}
1437 }
1438 
1439 /*
1440  * Attaches the directory entry de to the directory represented by vp.
1441  * Note that this does not change the link count of the node pointed by
1442  * the directory entry, as this is done by tmpfs_alloc_dirent.
1443  */
1444 void
tmpfs_dir_attach(struct vnode * vp,struct tmpfs_dirent * de)1445 tmpfs_dir_attach(struct vnode *vp, struct tmpfs_dirent *de)
1446 {
1447 	struct tmpfs_node *dnode;
1448 	struct tmpfs_dirent *xde, *nde;
1449 
1450 	ASSERT_VOP_ELOCKED(vp, __func__);
1451 	MPASS(de->td_namelen > 0);
1452 	MPASS(de->td_hash >= TMPFS_DIRCOOKIE_MIN);
1453 	MPASS(de->td_cookie == de->td_hash);
1454 
1455 	dnode = VP_TO_TMPFS_DIR(vp);
1456 	dnode->tn_dir.tn_readdir_lastn = 0;
1457 	dnode->tn_dir.tn_readdir_lastp = NULL;
1458 
1459 	MPASS(!tmpfs_dirent_dup(de));
1460 	xde = RB_INSERT(tmpfs_dir, &dnode->tn_dir.tn_dirhead, de);
1461 	if (xde != NULL && tmpfs_dirent_duphead(xde))
1462 		tmpfs_dir_attach_dup(dnode, &xde->ud.td_duphead, de);
1463 	else if (xde != NULL) {
1464 		/*
1465 		 * Allocate new duphead. Swap xde with duphead to avoid
1466 		 * adding/removing elements with the same hash.
1467 		 */
1468 		MPASS(!tmpfs_dirent_dup(xde));
1469 		tmpfs_alloc_dirent(VFS_TO_TMPFS(vp->v_mount), NULL, NULL, 0,
1470 		    &nde);
1471 		/* *nde = *xde; XXX gcc 4.2.1 may generate invalid code. */
1472 		memcpy(nde, xde, sizeof(*xde));
1473 		xde->td_cookie |= TMPFS_DIRCOOKIE_DUPHEAD;
1474 		LIST_INIT(&xde->ud.td_duphead);
1475 		xde->td_namelen = 0;
1476 		xde->td_node = NULL;
1477 		tmpfs_dir_attach_dup(dnode, &xde->ud.td_duphead, nde);
1478 		tmpfs_dir_attach_dup(dnode, &xde->ud.td_duphead, de);
1479 	}
1480 	dnode->tn_size += sizeof(struct tmpfs_dirent);
1481 	dnode->tn_status |= TMPFS_NODE_CHANGED | TMPFS_NODE_MODIFIED;
1482 	dnode->tn_accessed = true;
1483 	tmpfs_update(vp);
1484 }
1485 
1486 /*
1487  * Detaches the directory entry de from the directory represented by vp.
1488  * Note that this does not change the link count of the node pointed by
1489  * the directory entry, as this is done by tmpfs_free_dirent.
1490  */
1491 void
tmpfs_dir_detach(struct vnode * vp,struct tmpfs_dirent * de)1492 tmpfs_dir_detach(struct vnode *vp, struct tmpfs_dirent *de)
1493 {
1494 	struct tmpfs_mount *tmp;
1495 	struct tmpfs_dir *head;
1496 	struct tmpfs_node *dnode;
1497 	struct tmpfs_dirent *xde;
1498 
1499 	ASSERT_VOP_ELOCKED(vp, __func__);
1500 
1501 	dnode = VP_TO_TMPFS_DIR(vp);
1502 	head = &dnode->tn_dir.tn_dirhead;
1503 	dnode->tn_dir.tn_readdir_lastn = 0;
1504 	dnode->tn_dir.tn_readdir_lastp = NULL;
1505 
1506 	if (tmpfs_dirent_dup(de)) {
1507 		/* Remove duphead if de was last entry. */
1508 		if (LIST_NEXT(de, uh.td_dup.entries) == NULL) {
1509 			xde = tmpfs_dir_xlookup_hash(dnode, de->td_hash);
1510 			MPASS(tmpfs_dirent_duphead(xde));
1511 		} else
1512 			xde = NULL;
1513 		LIST_REMOVE(de, uh.td_dup.entries);
1514 		LIST_REMOVE(de, uh.td_dup.index_entries);
1515 		if (xde != NULL) {
1516 			if (LIST_EMPTY(&xde->ud.td_duphead)) {
1517 				RB_REMOVE(tmpfs_dir, head, xde);
1518 				tmp = VFS_TO_TMPFS(vp->v_mount);
1519 				MPASS(xde->td_node == NULL);
1520 				tmpfs_free_dirent(tmp, xde);
1521 			}
1522 		}
1523 		de->td_cookie = de->td_hash;
1524 	} else
1525 		RB_REMOVE(tmpfs_dir, head, de);
1526 
1527 	dnode->tn_size -= sizeof(struct tmpfs_dirent);
1528 	dnode->tn_status |= TMPFS_NODE_CHANGED | TMPFS_NODE_MODIFIED;
1529 	dnode->tn_accessed = true;
1530 	tmpfs_update(vp);
1531 }
1532 
1533 void
tmpfs_dir_destroy(struct tmpfs_mount * tmp,struct tmpfs_node * dnode)1534 tmpfs_dir_destroy(struct tmpfs_mount *tmp, struct tmpfs_node *dnode)
1535 {
1536 	struct tmpfs_dirent *de, *dde, *nde;
1537 
1538 	RB_FOREACH_SAFE(de, tmpfs_dir, &dnode->tn_dir.tn_dirhead, nde) {
1539 		RB_REMOVE(tmpfs_dir, &dnode->tn_dir.tn_dirhead, de);
1540 		/* Node may already be destroyed. */
1541 		de->td_node = NULL;
1542 		if (tmpfs_dirent_duphead(de)) {
1543 			while ((dde = LIST_FIRST(&de->ud.td_duphead)) != NULL) {
1544 				LIST_REMOVE(dde, uh.td_dup.entries);
1545 				dde->td_node = NULL;
1546 				tmpfs_free_dirent(tmp, dde);
1547 			}
1548 		}
1549 		tmpfs_free_dirent(tmp, de);
1550 	}
1551 }
1552 
1553 /*
1554  * Helper function for tmpfs_readdir.  Creates a '.' entry for the given
1555  * directory and returns it in the uio space.  The function returns 0
1556  * on success, -1 if there was not enough space in the uio structure to
1557  * hold the directory entry or an appropriate error code if another
1558  * error happens.
1559  */
1560 static int
tmpfs_dir_getdotdent(struct tmpfs_mount * tm,struct tmpfs_node * node,struct uio * uio)1561 tmpfs_dir_getdotdent(struct tmpfs_mount *tm, struct tmpfs_node *node,
1562     struct uio *uio)
1563 {
1564 	int error;
1565 	struct dirent dent;
1566 
1567 	TMPFS_VALIDATE_DIR(node);
1568 	MPASS(uio->uio_offset == TMPFS_DIRCOOKIE_DOT);
1569 
1570 	dent.d_fileno = node->tn_id;
1571 	dent.d_off = TMPFS_DIRCOOKIE_DOTDOT;
1572 	dent.d_type = DT_DIR;
1573 	dent.d_namlen = 1;
1574 	dent.d_name[0] = '.';
1575 	dent.d_reclen = GENERIC_DIRSIZ(&dent);
1576 	dirent_terminate(&dent);
1577 
1578 	if (dent.d_reclen > uio->uio_resid)
1579 		error = EJUSTRETURN;
1580 	else
1581 		error = uiomove(&dent, dent.d_reclen, uio);
1582 
1583 	tmpfs_set_accessed(tm, node);
1584 
1585 	return (error);
1586 }
1587 
1588 /*
1589  * Helper function for tmpfs_readdir.  Creates a '..' entry for the given
1590  * directory and returns it in the uio space.  The function returns 0
1591  * on success, -1 if there was not enough space in the uio structure to
1592  * hold the directory entry or an appropriate error code if another
1593  * error happens.
1594  */
1595 static int
tmpfs_dir_getdotdotdent(struct tmpfs_mount * tm,struct tmpfs_node * node,struct uio * uio,off_t next)1596 tmpfs_dir_getdotdotdent(struct tmpfs_mount *tm, struct tmpfs_node *node,
1597     struct uio *uio, off_t next)
1598 {
1599 	struct tmpfs_node *parent;
1600 	struct dirent dent;
1601 	int error;
1602 
1603 	TMPFS_VALIDATE_DIR(node);
1604 	MPASS(uio->uio_offset == TMPFS_DIRCOOKIE_DOTDOT);
1605 
1606 	/*
1607 	 * Return ENOENT if the current node is already removed.
1608 	 */
1609 	TMPFS_ASSERT_LOCKED(node);
1610 	parent = node->tn_dir.tn_parent;
1611 	if (parent == NULL)
1612 		return (ENOENT);
1613 
1614 	dent.d_fileno = parent->tn_id;
1615 	dent.d_off = next;
1616 	dent.d_type = DT_DIR;
1617 	dent.d_namlen = 2;
1618 	dent.d_name[0] = '.';
1619 	dent.d_name[1] = '.';
1620 	dent.d_reclen = GENERIC_DIRSIZ(&dent);
1621 	dirent_terminate(&dent);
1622 
1623 	if (dent.d_reclen > uio->uio_resid)
1624 		error = EJUSTRETURN;
1625 	else
1626 		error = uiomove(&dent, dent.d_reclen, uio);
1627 
1628 	tmpfs_set_accessed(tm, node);
1629 
1630 	return (error);
1631 }
1632 
1633 /*
1634  * Helper function for tmpfs_readdir.  Returns as much directory entries
1635  * as can fit in the uio space.  The read starts at uio->uio_offset.
1636  * The function returns 0 on success, -1 if there was not enough space
1637  * in the uio structure to hold the directory entry or an appropriate
1638  * error code if another error happens.
1639  */
1640 int
tmpfs_dir_getdents(struct tmpfs_mount * tm,struct tmpfs_node * node,struct uio * uio,int maxcookies,uint64_t * cookies,int * ncookies)1641 tmpfs_dir_getdents(struct tmpfs_mount *tm, struct tmpfs_node *node,
1642     struct uio *uio, int maxcookies, uint64_t *cookies, int *ncookies)
1643 {
1644 	struct tmpfs_dir_cursor dc;
1645 	struct tmpfs_dirent *de, *nde;
1646 	off_t off;
1647 	int error;
1648 
1649 	TMPFS_VALIDATE_DIR(node);
1650 
1651 	off = 0;
1652 
1653 	/*
1654 	 * Lookup the node from the current offset.  The starting offset of
1655 	 * 0 will lookup both '.' and '..', and then the first real entry,
1656 	 * or EOF if there are none.  Then find all entries for the dir that
1657 	 * fit into the buffer.  Once no more entries are found (de == NULL),
1658 	 * the offset is set to TMPFS_DIRCOOKIE_EOF, which will cause the next
1659 	 * call to return 0.
1660 	 */
1661 	switch (uio->uio_offset) {
1662 	case TMPFS_DIRCOOKIE_DOT:
1663 		error = tmpfs_dir_getdotdent(tm, node, uio);
1664 		if (error != 0)
1665 			return (error);
1666 		uio->uio_offset = off = TMPFS_DIRCOOKIE_DOTDOT;
1667 		if (cookies != NULL)
1668 			cookies[(*ncookies)++] = off;
1669 		/* FALLTHROUGH */
1670 	case TMPFS_DIRCOOKIE_DOTDOT:
1671 		de = tmpfs_dir_first(node, &dc);
1672 		off = tmpfs_dirent_cookie(de);
1673 		error = tmpfs_dir_getdotdotdent(tm, node, uio, off);
1674 		if (error != 0)
1675 			return (error);
1676 		uio->uio_offset = off;
1677 		if (cookies != NULL)
1678 			cookies[(*ncookies)++] = off;
1679 		/* EOF. */
1680 		if (de == NULL)
1681 			return (0);
1682 		break;
1683 	case TMPFS_DIRCOOKIE_EOF:
1684 		return (0);
1685 	default:
1686 		de = tmpfs_dir_lookup_cookie(node, uio->uio_offset, &dc);
1687 		if (de == NULL)
1688 			return (EINVAL);
1689 		if (cookies != NULL)
1690 			off = tmpfs_dirent_cookie(de);
1691 	}
1692 
1693 	/*
1694 	 * Read as much entries as possible; i.e., until we reach the end of the
1695 	 * directory or we exhaust uio space.
1696 	 */
1697 	do {
1698 		struct dirent d;
1699 
1700 		/*
1701 		 * Create a dirent structure representing the current tmpfs_node
1702 		 * and fill it.
1703 		 */
1704 		if (de->td_node == NULL) {
1705 			d.d_fileno = 1;
1706 			d.d_type = DT_WHT;
1707 		} else {
1708 			d.d_fileno = de->td_node->tn_id;
1709 			switch (de->td_node->tn_type) {
1710 			case VBLK:
1711 				d.d_type = DT_BLK;
1712 				break;
1713 
1714 			case VCHR:
1715 				d.d_type = DT_CHR;
1716 				break;
1717 
1718 			case VDIR:
1719 				d.d_type = DT_DIR;
1720 				break;
1721 
1722 			case VFIFO:
1723 				d.d_type = DT_FIFO;
1724 				break;
1725 
1726 			case VLNK:
1727 				d.d_type = DT_LNK;
1728 				break;
1729 
1730 			case VREG:
1731 				d.d_type = DT_REG;
1732 				break;
1733 
1734 			case VSOCK:
1735 				d.d_type = DT_SOCK;
1736 				break;
1737 
1738 			default:
1739 				panic("tmpfs_dir_getdents: type %p %d",
1740 				    de->td_node, (int)de->td_node->tn_type);
1741 			}
1742 		}
1743 		d.d_namlen = de->td_namelen;
1744 		MPASS(de->td_namelen < sizeof(d.d_name));
1745 		(void)memcpy(d.d_name, de->ud.td_name, de->td_namelen);
1746 		d.d_reclen = GENERIC_DIRSIZ(&d);
1747 
1748 		/*
1749 		 * Stop reading if the directory entry we are treating is bigger
1750 		 * than the amount of data that can be returned.
1751 		 */
1752 		if (d.d_reclen > uio->uio_resid) {
1753 			error = EJUSTRETURN;
1754 			break;
1755 		}
1756 
1757 		nde = tmpfs_dir_next(node, &dc);
1758 		d.d_off = tmpfs_dirent_cookie(nde);
1759 		dirent_terminate(&d);
1760 
1761 		/*
1762 		 * Copy the new dirent structure into the output buffer and
1763 		 * advance pointers.
1764 		 */
1765 		error = uiomove(&d, d.d_reclen, uio);
1766 		if (error == 0) {
1767 			de = nde;
1768 			if (cookies != NULL) {
1769 				off = tmpfs_dirent_cookie(de);
1770 				MPASS(*ncookies < maxcookies);
1771 				cookies[(*ncookies)++] = off;
1772 			}
1773 		}
1774 	} while (error == 0 && uio->uio_resid > 0 && de != NULL);
1775 
1776 	/* Skip setting off when using cookies as it is already done above. */
1777 	if (cookies == NULL)
1778 		off = tmpfs_dirent_cookie(de);
1779 
1780 	/* Update the offset and cache. */
1781 	uio->uio_offset = off;
1782 	node->tn_dir.tn_readdir_lastn = off;
1783 	node->tn_dir.tn_readdir_lastp = de;
1784 
1785 	tmpfs_set_accessed(tm, node);
1786 	return (error);
1787 }
1788 
1789 int
tmpfs_dir_whiteout_add(struct vnode * dvp,struct componentname * cnp)1790 tmpfs_dir_whiteout_add(struct vnode *dvp, struct componentname *cnp)
1791 {
1792 	struct tmpfs_dirent *de;
1793 	int error;
1794 
1795 	error = tmpfs_alloc_dirent(VFS_TO_TMPFS(dvp->v_mount), NULL,
1796 	    cnp->cn_nameptr, cnp->cn_namelen, &de);
1797 	if (error != 0)
1798 		return (error);
1799 	tmpfs_dir_attach(dvp, de);
1800 	return (0);
1801 }
1802 
1803 void
tmpfs_dir_whiteout_remove(struct vnode * dvp,struct componentname * cnp)1804 tmpfs_dir_whiteout_remove(struct vnode *dvp, struct componentname *cnp)
1805 {
1806 	struct tmpfs_dirent *de;
1807 
1808 	de = tmpfs_dir_lookup(VP_TO_TMPFS_DIR(dvp), NULL, cnp);
1809 	MPASS(de != NULL && de->td_node == NULL);
1810 	tmpfs_dir_detach(dvp, de);
1811 	tmpfs_free_dirent(VFS_TO_TMPFS(dvp->v_mount), de);
1812 }
1813 
1814 /*
1815  * Resizes the aobj associated with the regular file pointed to by 'vp' to the
1816  * size 'newsize'.  'vp' must point to a vnode that represents a regular file.
1817  * 'newsize' must be positive.
1818  *
1819  * Returns zero on success or an appropriate error code on failure.
1820  */
1821 int
tmpfs_reg_resize(struct vnode * vp,off_t newsize,boolean_t ignerr)1822 tmpfs_reg_resize(struct vnode *vp, off_t newsize, boolean_t ignerr)
1823 {
1824 	struct tmpfs_node *node;
1825 	vm_object_t uobj;
1826 	vm_pindex_t idx, newpages, oldpages;
1827 	off_t oldsize;
1828 	int base, error;
1829 
1830 	MPASS(vp->v_type == VREG);
1831 	MPASS(newsize >= 0);
1832 
1833 	node = VP_TO_TMPFS_NODE(vp);
1834 	uobj = node->tn_reg.tn_aobj;
1835 
1836 	/*
1837 	 * Convert the old and new sizes to the number of pages needed to
1838 	 * store them.  It may happen that we do not need to do anything
1839 	 * because the last allocated page can accommodate the change on
1840 	 * its own.
1841 	 */
1842 	oldsize = node->tn_size;
1843 	oldpages = OFF_TO_IDX(oldsize + PAGE_MASK);
1844 	MPASS(oldpages == uobj->size);
1845 	newpages = OFF_TO_IDX(newsize + PAGE_MASK);
1846 
1847 	if (__predict_true(newpages == oldpages && newsize >= oldsize)) {
1848 		node->tn_size = newsize;
1849 		return (0);
1850 	}
1851 
1852 	VM_OBJECT_WLOCK(uobj);
1853 	if (newsize < oldsize) {
1854 		/*
1855 		 * Zero the truncated part of the last page.
1856 		 */
1857 		base = newsize & PAGE_MASK;
1858 		if (base != 0) {
1859 			idx = OFF_TO_IDX(newsize);
1860 			error = tmpfs_partial_page_invalidate(uobj, idx, base,
1861 			    PAGE_SIZE, ignerr);
1862 			if (error != 0) {
1863 				VM_OBJECT_WUNLOCK(uobj);
1864 				return (error);
1865 			}
1866 		}
1867 
1868 		/*
1869 		 * Release any swap space and free any whole pages.
1870 		 */
1871 		if (newpages < oldpages)
1872 			vm_object_page_remove(uobj, newpages, 0, 0);
1873 	}
1874 	uobj->size = newpages;
1875 	VM_OBJECT_WUNLOCK(uobj);
1876 
1877 	node->tn_size = newsize;
1878 	return (0);
1879 }
1880 
1881 /*
1882  * Punch hole in the aobj associated with the regular file pointed to by 'vp'.
1883  * Requests completely beyond the end-of-file are converted to no-op.
1884  *
1885  * Returns 0 on success or error code from tmpfs_partial_page_invalidate() on
1886  * failure.
1887  */
1888 int
tmpfs_reg_punch_hole(struct vnode * vp,off_t * offset,off_t * length)1889 tmpfs_reg_punch_hole(struct vnode *vp, off_t *offset, off_t *length)
1890 {
1891 	struct tmpfs_node *node;
1892 	vm_object_t object;
1893 	vm_pindex_t pistart, pi, piend;
1894 	int startofs, endofs, end;
1895 	off_t off, len;
1896 	int error;
1897 
1898 	KASSERT(*length <= OFF_MAX - *offset, ("%s: offset + length overflows",
1899 	    __func__));
1900 	node = VP_TO_TMPFS_NODE(vp);
1901 	KASSERT(node->tn_type == VREG, ("%s: node is not regular file",
1902 	    __func__));
1903 	object = node->tn_reg.tn_aobj;
1904 	off = *offset;
1905 	len = omin(node->tn_size - off, *length);
1906 	startofs = off & PAGE_MASK;
1907 	endofs = (off + len) & PAGE_MASK;
1908 	pistart = OFF_TO_IDX(off);
1909 	piend = OFF_TO_IDX(off + len);
1910 	pi = OFF_TO_IDX((vm_ooffset_t)off + PAGE_MASK);
1911 	error = 0;
1912 
1913 	/* Handle the case when offset is on or beyond file size. */
1914 	if (len <= 0) {
1915 		*length = 0;
1916 		return (0);
1917 	}
1918 
1919 	VM_OBJECT_WLOCK(object);
1920 
1921 	/*
1922 	 * If there is a partial page at the beginning of the hole-punching
1923 	 * request, fill the partial page with zeroes.
1924 	 */
1925 	if (startofs != 0) {
1926 		end = pistart != piend ? PAGE_SIZE : endofs;
1927 		error = tmpfs_partial_page_invalidate(object, pistart, startofs,
1928 		    end, FALSE);
1929 		if (error != 0)
1930 			goto out;
1931 		off += end - startofs;
1932 		len -= end - startofs;
1933 	}
1934 
1935 	/*
1936 	 * Toss away the full pages in the affected area.
1937 	 */
1938 	if (pi < piend) {
1939 		vm_object_page_remove(object, pi, piend, 0);
1940 		off += IDX_TO_OFF(piend - pi);
1941 		len -= IDX_TO_OFF(piend - pi);
1942 	}
1943 
1944 	/*
1945 	 * If there is a partial page at the end of the hole-punching request,
1946 	 * fill the partial page with zeroes.
1947 	 */
1948 	if (endofs != 0 && pistart != piend) {
1949 		error = tmpfs_partial_page_invalidate(object, piend, 0, endofs,
1950 		    FALSE);
1951 		if (error != 0)
1952 			goto out;
1953 		off += endofs;
1954 		len -= endofs;
1955 	}
1956 
1957 out:
1958 	VM_OBJECT_WUNLOCK(object);
1959 	*offset = off;
1960 	*length = len;
1961 	return (error);
1962 }
1963 
1964 void
tmpfs_check_mtime(struct vnode * vp)1965 tmpfs_check_mtime(struct vnode *vp)
1966 {
1967 	struct tmpfs_node *node;
1968 	struct vm_object *obj;
1969 
1970 	ASSERT_VOP_ELOCKED(vp, "check_mtime");
1971 	if (vp->v_type != VREG)
1972 		return;
1973 	obj = vp->v_object;
1974 	KASSERT(obj->type == tmpfs_pager_type &&
1975 	    (obj->flags & (OBJ_SWAP | OBJ_TMPFS)) ==
1976 	    (OBJ_SWAP | OBJ_TMPFS), ("non-tmpfs obj"));
1977 	/* unlocked read */
1978 	if (obj->generation != obj->cleangeneration) {
1979 		VM_OBJECT_WLOCK(obj);
1980 		if (obj->generation != obj->cleangeneration) {
1981 			obj->cleangeneration = obj->generation;
1982 			node = VP_TO_TMPFS_NODE(vp);
1983 			node->tn_status |= TMPFS_NODE_MODIFIED |
1984 			    TMPFS_NODE_CHANGED;
1985 		}
1986 		VM_OBJECT_WUNLOCK(obj);
1987 	}
1988 }
1989 
1990 /*
1991  * Change flags of the given vnode.
1992  * Caller should execute tmpfs_update on vp after a successful execution.
1993  * The vnode must be locked on entry and remain locked on exit.
1994  */
1995 int
tmpfs_chflags(struct vnode * vp,u_long flags,struct ucred * cred,struct thread * td)1996 tmpfs_chflags(struct vnode *vp, u_long flags, struct ucred *cred,
1997     struct thread *td)
1998 {
1999 	int error;
2000 	struct tmpfs_node *node;
2001 
2002 	ASSERT_VOP_ELOCKED(vp, "chflags");
2003 
2004 	node = VP_TO_TMPFS_NODE(vp);
2005 
2006 	if ((flags & ~(SF_APPEND | SF_ARCHIVED | SF_IMMUTABLE | SF_NOUNLINK |
2007 	    UF_APPEND | UF_ARCHIVE | UF_HIDDEN | UF_IMMUTABLE | UF_NODUMP |
2008 	    UF_NOUNLINK | UF_OFFLINE | UF_OPAQUE | UF_READONLY | UF_REPARSE |
2009 	    UF_SPARSE | UF_SYSTEM)) != 0)
2010 		return (EOPNOTSUPP);
2011 
2012 	/* Disallow this operation if the file system is mounted read-only. */
2013 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
2014 		return (EROFS);
2015 
2016 	/*
2017 	 * Callers may only modify the file flags on objects they
2018 	 * have VADMIN rights for.
2019 	 */
2020 	if ((error = VOP_ACCESS(vp, VADMIN, cred, td)))
2021 		return (error);
2022 	/*
2023 	 * Unprivileged processes are not permitted to unset system
2024 	 * flags, or modify flags if any system flags are set.
2025 	 */
2026 	if (!priv_check_cred(cred, PRIV_VFS_SYSFLAGS)) {
2027 		if (node->tn_flags &
2028 		    (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND)) {
2029 			error = securelevel_gt(cred, 0);
2030 			if (error)
2031 				return (error);
2032 		}
2033 	} else {
2034 		if (node->tn_flags &
2035 		    (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND) ||
2036 		    ((flags ^ node->tn_flags) & SF_SETTABLE))
2037 			return (EPERM);
2038 	}
2039 	node->tn_flags = flags;
2040 	node->tn_status |= TMPFS_NODE_CHANGED;
2041 
2042 	ASSERT_VOP_ELOCKED(vp, "chflags2");
2043 
2044 	return (0);
2045 }
2046 
2047 /*
2048  * Change access mode on the given vnode.
2049  * Caller should execute tmpfs_update on vp after a successful execution.
2050  * The vnode must be locked on entry and remain locked on exit.
2051  */
2052 int
tmpfs_chmod(struct vnode * vp,mode_t mode,struct ucred * cred,struct thread * td)2053 tmpfs_chmod(struct vnode *vp, mode_t mode, struct ucred *cred,
2054     struct thread *td)
2055 {
2056 	int error;
2057 	struct tmpfs_node *node;
2058 	mode_t newmode;
2059 
2060 	ASSERT_VOP_ELOCKED(vp, "chmod");
2061 	ASSERT_VOP_IN_SEQC(vp);
2062 
2063 	node = VP_TO_TMPFS_NODE(vp);
2064 
2065 	/* Disallow this operation if the file system is mounted read-only. */
2066 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
2067 		return (EROFS);
2068 
2069 	/* Immutable or append-only files cannot be modified, either. */
2070 	if (node->tn_flags & (IMMUTABLE | APPEND))
2071 		return (EPERM);
2072 
2073 	/*
2074 	 * To modify the permissions on a file, must possess VADMIN
2075 	 * for that file.
2076 	 */
2077 	if ((error = VOP_ACCESS(vp, VADMIN, cred, td)))
2078 		return (error);
2079 
2080 	/*
2081 	 * Privileged processes may set the sticky bit on non-directories,
2082 	 * as well as set the setgid bit on a file with a group that the
2083 	 * process is not a member of.
2084 	 */
2085 	if (vp->v_type != VDIR && (mode & S_ISTXT)) {
2086 		if (priv_check_cred(cred, PRIV_VFS_STICKYFILE))
2087 			return (EFTYPE);
2088 	}
2089 	if (!groupmember(node->tn_gid, cred) && (mode & S_ISGID)) {
2090 		error = priv_check_cred(cred, PRIV_VFS_SETGID);
2091 		if (error)
2092 			return (error);
2093 	}
2094 
2095 	newmode = node->tn_mode & ~ALLPERMS;
2096 	newmode |= mode & ALLPERMS;
2097 	atomic_store_short(&node->tn_mode, newmode);
2098 
2099 	node->tn_status |= TMPFS_NODE_CHANGED;
2100 
2101 	ASSERT_VOP_ELOCKED(vp, "chmod2");
2102 
2103 	return (0);
2104 }
2105 
2106 /*
2107  * Change ownership of the given vnode.  At least one of uid or gid must
2108  * be different than VNOVAL.  If one is set to that value, the attribute
2109  * is unchanged.
2110  * Caller should execute tmpfs_update on vp after a successful execution.
2111  * The vnode must be locked on entry and remain locked on exit.
2112  */
2113 int
tmpfs_chown(struct vnode * vp,uid_t uid,gid_t gid,struct ucred * cred,struct thread * td)2114 tmpfs_chown(struct vnode *vp, uid_t uid, gid_t gid, struct ucred *cred,
2115     struct thread *td)
2116 {
2117 	int error;
2118 	struct tmpfs_node *node;
2119 	uid_t ouid;
2120 	gid_t ogid;
2121 	mode_t newmode;
2122 
2123 	ASSERT_VOP_ELOCKED(vp, "chown");
2124 	ASSERT_VOP_IN_SEQC(vp);
2125 
2126 	node = VP_TO_TMPFS_NODE(vp);
2127 
2128 	/* Assign default values if they are unknown. */
2129 	MPASS(uid != VNOVAL || gid != VNOVAL);
2130 	if (uid == VNOVAL)
2131 		uid = node->tn_uid;
2132 	if (gid == VNOVAL)
2133 		gid = node->tn_gid;
2134 	MPASS(uid != VNOVAL && gid != VNOVAL);
2135 
2136 	/* Disallow this operation if the file system is mounted read-only. */
2137 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
2138 		return (EROFS);
2139 
2140 	/* Immutable or append-only files cannot be modified, either. */
2141 	if (node->tn_flags & (IMMUTABLE | APPEND))
2142 		return (EPERM);
2143 
2144 	/*
2145 	 * To modify the ownership of a file, must possess VADMIN for that
2146 	 * file.
2147 	 */
2148 	if ((error = VOP_ACCESS(vp, VADMIN, cred, td)))
2149 		return (error);
2150 
2151 	/*
2152 	 * To change the owner of a file, or change the group of a file to a
2153 	 * group of which we are not a member, the caller must have
2154 	 * privilege.
2155 	 */
2156 	if ((uid != node->tn_uid ||
2157 	    (gid != node->tn_gid && !groupmember(gid, cred))) &&
2158 	    (error = priv_check_cred(cred, PRIV_VFS_CHOWN)))
2159 		return (error);
2160 
2161 	ogid = node->tn_gid;
2162 	ouid = node->tn_uid;
2163 
2164 	node->tn_uid = uid;
2165 	node->tn_gid = gid;
2166 
2167 	node->tn_status |= TMPFS_NODE_CHANGED;
2168 
2169 	if ((node->tn_mode & (S_ISUID | S_ISGID)) != 0 &&
2170 	    (ouid != uid || ogid != gid)) {
2171 		if (priv_check_cred(cred, PRIV_VFS_RETAINSUGID)) {
2172 			newmode = node->tn_mode & ~(S_ISUID | S_ISGID);
2173 			atomic_store_short(&node->tn_mode, newmode);
2174 		}
2175 	}
2176 
2177 	ASSERT_VOP_ELOCKED(vp, "chown2");
2178 
2179 	return (0);
2180 }
2181 
2182 /*
2183  * Change size of the given vnode.
2184  * Caller should execute tmpfs_update on vp after a successful execution.
2185  * The vnode must be locked on entry and remain locked on exit.
2186  */
2187 int
tmpfs_chsize(struct vnode * vp,u_quad_t size,struct ucred * cred,struct thread * td)2188 tmpfs_chsize(struct vnode *vp, u_quad_t size, struct ucred *cred,
2189     struct thread *td)
2190 {
2191 	int error;
2192 	struct tmpfs_node *node;
2193 
2194 	ASSERT_VOP_ELOCKED(vp, "chsize");
2195 
2196 	node = VP_TO_TMPFS_NODE(vp);
2197 
2198 	/* Decide whether this is a valid operation based on the file type. */
2199 	error = 0;
2200 	switch (vp->v_type) {
2201 	case VDIR:
2202 		return (EISDIR);
2203 
2204 	case VREG:
2205 		if (vp->v_mount->mnt_flag & MNT_RDONLY)
2206 			return (EROFS);
2207 		break;
2208 
2209 	case VBLK:
2210 		/* FALLTHROUGH */
2211 	case VCHR:
2212 		/* FALLTHROUGH */
2213 	case VFIFO:
2214 		/*
2215 		 * Allow modifications of special files even if in the file
2216 		 * system is mounted read-only (we are not modifying the
2217 		 * files themselves, but the objects they represent).
2218 		 */
2219 		return (0);
2220 
2221 	default:
2222 		/* Anything else is unsupported. */
2223 		return (EOPNOTSUPP);
2224 	}
2225 
2226 	/* Immutable or append-only files cannot be modified, either. */
2227 	if (node->tn_flags & (IMMUTABLE | APPEND))
2228 		return (EPERM);
2229 
2230 	error = vn_rlimit_trunc(size, td);
2231 	if (error != 0)
2232 		return (error);
2233 
2234 	error = tmpfs_truncate(vp, size);
2235 	/*
2236 	 * tmpfs_truncate will raise the NOTE_EXTEND and NOTE_ATTRIB kevents
2237 	 * for us, as will update tn_status; no need to do that here.
2238 	 */
2239 
2240 	ASSERT_VOP_ELOCKED(vp, "chsize2");
2241 
2242 	return (error);
2243 }
2244 
2245 /*
2246  * Change access and modification times of the given vnode.
2247  * Caller should execute tmpfs_update on vp after a successful execution.
2248  * The vnode must be locked on entry and remain locked on exit.
2249  */
2250 int
tmpfs_chtimes(struct vnode * vp,struct vattr * vap,struct ucred * cred,struct thread * td)2251 tmpfs_chtimes(struct vnode *vp, struct vattr *vap,
2252     struct ucred *cred, struct thread *td)
2253 {
2254 	int error;
2255 	struct tmpfs_node *node;
2256 
2257 	ASSERT_VOP_ELOCKED(vp, "chtimes");
2258 
2259 	node = VP_TO_TMPFS_NODE(vp);
2260 
2261 	/* Disallow this operation if the file system is mounted read-only. */
2262 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
2263 		return (EROFS);
2264 
2265 	/* Immutable or append-only files cannot be modified, either. */
2266 	if (node->tn_flags & (IMMUTABLE | APPEND))
2267 		return (EPERM);
2268 
2269 	error = vn_utimes_perm(vp, vap, cred, td);
2270 	if (error != 0)
2271 		return (error);
2272 
2273 	if (vap->va_atime.tv_sec != VNOVAL)
2274 		node->tn_accessed = true;
2275 	if (vap->va_mtime.tv_sec != VNOVAL)
2276 		node->tn_status |= TMPFS_NODE_MODIFIED;
2277 	if (vap->va_birthtime.tv_sec != VNOVAL)
2278 		node->tn_status |= TMPFS_NODE_MODIFIED;
2279 	tmpfs_itimes(vp, &vap->va_atime, &vap->va_mtime);
2280 	if (vap->va_birthtime.tv_sec != VNOVAL)
2281 		node->tn_birthtime = vap->va_birthtime;
2282 	ASSERT_VOP_ELOCKED(vp, "chtimes2");
2283 
2284 	return (0);
2285 }
2286 
2287 void
tmpfs_set_status(struct tmpfs_mount * tm,struct tmpfs_node * node,int status)2288 tmpfs_set_status(struct tmpfs_mount *tm, struct tmpfs_node *node, int status)
2289 {
2290 
2291 	if ((node->tn_status & status) == status || tm->tm_ronly)
2292 		return;
2293 	TMPFS_NODE_LOCK(node);
2294 	node->tn_status |= status;
2295 	TMPFS_NODE_UNLOCK(node);
2296 }
2297 
2298 void
tmpfs_set_accessed(struct tmpfs_mount * tm,struct tmpfs_node * node)2299 tmpfs_set_accessed(struct tmpfs_mount *tm, struct tmpfs_node *node)
2300 {
2301 	if (node->tn_accessed || tm->tm_ronly)
2302 		return;
2303 	atomic_store_8(&node->tn_accessed, true);
2304 }
2305 
2306 /* Sync timestamps */
2307 void
tmpfs_itimes(struct vnode * vp,const struct timespec * acc,const struct timespec * mod)2308 tmpfs_itimes(struct vnode *vp, const struct timespec *acc,
2309     const struct timespec *mod)
2310 {
2311 	struct tmpfs_node *node;
2312 	struct timespec now;
2313 
2314 	ASSERT_VOP_LOCKED(vp, "tmpfs_itimes");
2315 	node = VP_TO_TMPFS_NODE(vp);
2316 
2317 	if (!node->tn_accessed &&
2318 	    (node->tn_status & (TMPFS_NODE_MODIFIED | TMPFS_NODE_CHANGED)) == 0)
2319 		return;
2320 
2321 	vfs_timestamp(&now);
2322 	TMPFS_NODE_LOCK(node);
2323 	if (node->tn_accessed) {
2324 		if (acc == NULL)
2325 			 acc = &now;
2326 		node->tn_atime = *acc;
2327 	}
2328 	if (node->tn_status & TMPFS_NODE_MODIFIED) {
2329 		if (mod == NULL)
2330 			mod = &now;
2331 		node->tn_mtime = *mod;
2332 	}
2333 	if (node->tn_status & TMPFS_NODE_CHANGED)
2334 		node->tn_ctime = now;
2335 	node->tn_status &= ~(TMPFS_NODE_MODIFIED | TMPFS_NODE_CHANGED);
2336 	node->tn_accessed = false;
2337 	TMPFS_NODE_UNLOCK(node);
2338 
2339 	/* XXX: FIX? The entropy here is desirable, but the harvesting may be expensive */
2340 	random_harvest_queue(node, sizeof(*node), RANDOM_FS_ATIME);
2341 }
2342 
2343 int
tmpfs_truncate(struct vnode * vp,off_t length)2344 tmpfs_truncate(struct vnode *vp, off_t length)
2345 {
2346 	struct tmpfs_node *node;
2347 	int error;
2348 
2349 	if (length < 0)
2350 		return (EINVAL);
2351 	if (length > VFS_TO_TMPFS(vp->v_mount)->tm_maxfilesize)
2352 		return (EFBIG);
2353 
2354 	node = VP_TO_TMPFS_NODE(vp);
2355 	error = node->tn_size == length ? 0 : tmpfs_reg_resize(vp, length,
2356 	    FALSE);
2357 	if (error == 0)
2358 		node->tn_status |= TMPFS_NODE_CHANGED | TMPFS_NODE_MODIFIED;
2359 	tmpfs_update(vp);
2360 
2361 	return (error);
2362 }
2363 
2364 static __inline int
tmpfs_dirtree_cmp(struct tmpfs_dirent * a,struct tmpfs_dirent * b)2365 tmpfs_dirtree_cmp(struct tmpfs_dirent *a, struct tmpfs_dirent *b)
2366 {
2367 	if (a->td_hash > b->td_hash)
2368 		return (1);
2369 	else if (a->td_hash < b->td_hash)
2370 		return (-1);
2371 	return (0);
2372 }
2373 
2374 RB_GENERATE_STATIC(tmpfs_dir, tmpfs_dirent, uh.td_entries, tmpfs_dirtree_cmp);
2375