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