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