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