kernel - Cleanup vfs_lock & ref-count states states
[dragonfly.git] / sys / kern / vfs_lock.c
1 /*
2  * Copyright (c) 2004,2013 The DragonFly Project.  All rights reserved.
3  * 
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  * 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  * 
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 /*
36  * External lock/ref-related vnode functions
37  *
38  * vs_state transition locking requirements:
39  *
40  *      INACTIVE -> CACHED|DYING        vx_lock(excl) + vfs_spin
41  *      DYING    -> CACHED              vx_lock(excl)
42  *      ACTIVE   -> INACTIVE            (none)       + v_spin + vfs_spin
43  *      INACTIVE -> ACTIVE              vn_lock(any) + v_spin + vfs_spin
44  *      CACHED   -> ACTIVE              vn_lock(any) + v_spin + vfs_spin
45  *
46  * NOTE: Switching to/from ACTIVE/INACTIVE requires v_spin and vfs_spin,
47  *
48  *       Switching into ACTIVE also requires a vref and vnode lock, however
49  *       the vnode lock is allowed to be SHARED.
50  *
51  *       Switching into a CACHED or DYING state requires an exclusive vnode
52  *       lock or vx_lock (which is almost the same thing).
53  */
54
55 #include <sys/param.h>
56 #include <sys/systm.h>
57 #include <sys/kernel.h>
58 #include <sys/malloc.h>
59 #include <sys/mount.h>
60 #include <sys/proc.h>
61 #include <sys/vnode.h>
62 #include <sys/buf.h>
63 #include <sys/sysctl.h>
64
65 #include <machine/limits.h>
66
67 #include <vm/vm.h>
68 #include <vm/vm_object.h>
69
70 #include <sys/buf2.h>
71 #include <sys/thread2.h>
72
73 #define VACT_MAX        5
74
75 static void vnode_terminate(struct vnode *vp);
76
77 static MALLOC_DEFINE(M_VNODE, "vnodes", "vnode structures");
78
79 /*
80  * The vnode free list hold inactive vnodes.  Aged inactive vnodes
81  * are inserted prior to the mid point, and otherwise inserted
82  * at the tail.
83  */
84 TAILQ_HEAD(freelst, vnode);
85 static struct freelst   vnode_active_list;
86 static struct freelst   vnode_inactive_list;
87 static struct vnode     vnode_active_rover;
88 static struct spinlock  vfs_spin = SPINLOCK_INITIALIZER(vfs_spin);
89
90 int  activevnodes = 0;
91 SYSCTL_INT(_debug, OID_AUTO, activevnodes, CTLFLAG_RD,
92         &activevnodes, 0, "Number of active nodes");
93 int  cachedvnodes = 0;
94 SYSCTL_INT(_debug, OID_AUTO, cachedvnodes, CTLFLAG_RD,
95         &cachedvnodes, 0, "Number of total cached nodes");
96 int  inactivevnodes = 0;
97 SYSCTL_INT(_debug, OID_AUTO, inactivevnodes, CTLFLAG_RD,
98         &inactivevnodes, 0, "Number of inactive nodes");
99 static int wantfreevnodes = 25;
100 SYSCTL_INT(_debug, OID_AUTO, wantfreevnodes, CTLFLAG_RW,
101         &wantfreevnodes, 0, "Desired number of free vnodes");
102 static int batchfreevnodes = 5;
103 SYSCTL_INT(_debug, OID_AUTO, batchfreevnodes, CTLFLAG_RW,
104         &batchfreevnodes, 0, "Number of vnodes to free at once");
105 #ifdef TRACKVNODE
106 static ulong trackvnode;
107 SYSCTL_ULONG(_debug, OID_AUTO, trackvnode, CTLFLAG_RW,
108                 &trackvnode, 0, "");
109 #endif
110
111 /*
112  * Called from vfsinit()
113  */
114 void
115 vfs_lock_init(void)
116 {
117         TAILQ_INIT(&vnode_inactive_list);
118         TAILQ_INIT(&vnode_active_list);
119         TAILQ_INSERT_TAIL(&vnode_active_list, &vnode_active_rover, v_list);
120         spin_init(&vfs_spin);
121         kmalloc_raise_limit(M_VNODE, 0);        /* unlimited */
122 }
123
124 /*
125  * Misc functions
126  */
127 static __inline
128 void
129 _vsetflags(struct vnode *vp, int flags)
130 {
131         atomic_set_int(&vp->v_flag, flags);
132 }
133
134 static __inline
135 void
136 _vclrflags(struct vnode *vp, int flags)
137 {
138         atomic_clear_int(&vp->v_flag, flags);
139 }
140
141 void
142 vsetflags(struct vnode *vp, int flags)
143 {
144         _vsetflags(vp, flags);
145 }
146
147 void
148 vclrflags(struct vnode *vp, int flags)
149 {
150         _vclrflags(vp, flags);
151 }
152
153 /*
154  * Place the vnode on the active list.
155  *
156  * Caller must hold vp->v_spin
157  */
158 static __inline 
159 void
160 _vactivate(struct vnode *vp)
161 {
162 #ifdef TRACKVNODE
163         if ((ulong)vp == trackvnode)
164                 kprintf("_vactivate %p %08x\n", vp, vp->v_flag);
165 #endif
166         spin_lock(&vfs_spin);
167
168         switch(vp->v_state) {
169         case VS_ACTIVE:
170                 panic("_vactivate: already active");
171                 /* NOT REACHED */
172                 spin_unlock(&vfs_spin);
173                 return;
174         case VS_INACTIVE:
175                 TAILQ_REMOVE(&vnode_inactive_list, vp, v_list);
176                 --inactivevnodes;
177                 break;
178         case VS_CACHED:
179         case VS_DYING:
180                 break;
181         }
182         TAILQ_INSERT_TAIL(&vnode_active_list, vp, v_list);
183         vp->v_state = VS_ACTIVE;
184         ++activevnodes;
185
186         spin_unlock(&vfs_spin);
187 }
188
189 /*
190  * Put a vnode on the inactive list.
191  *
192  * Caller must hold v_spin
193  */
194 static __inline
195 void
196 _vinactive(struct vnode *vp)
197 {
198 #ifdef TRACKVNODE
199         if ((ulong)vp == trackvnode) {
200                 kprintf("_vinactive %p %08x\n", vp, vp->v_flag);
201                 print_backtrace(-1);
202         }
203 #endif
204         spin_lock(&vfs_spin);
205
206         /*
207          * Remove from active list if it is sitting on it
208          */
209         switch(vp->v_state) {
210         case VS_ACTIVE:
211                 TAILQ_REMOVE(&vnode_active_list, vp, v_list);
212                 --activevnodes;
213                 break;
214         case VS_INACTIVE:
215                 panic("_vinactive: already inactive");
216                 /* NOT REACHED */
217                 spin_unlock(&vfs_spin);
218                 return;
219         case VS_CACHED:
220         case VS_DYING:
221                 break;
222         }
223
224         /*
225          * Distinguish between basically dead vnodes, vnodes with cached
226          * data, and vnodes without cached data.  A rover will shift the
227          * vnodes around as their cache status is lost.
228          */
229         if (vp->v_flag & VRECLAIMED) {
230                 TAILQ_INSERT_HEAD(&vnode_inactive_list, vp, v_list);
231         } else {
232                 TAILQ_INSERT_TAIL(&vnode_inactive_list, vp, v_list);
233         }
234         ++inactivevnodes;
235         vp->v_state = VS_INACTIVE;
236
237         spin_unlock(&vfs_spin);
238 }
239
240 static __inline
241 void
242 _vinactive_tail(struct vnode *vp)
243 {
244         spin_lock(&vfs_spin);
245
246         /*
247          * Remove from active list if it is sitting on it
248          */
249         switch(vp->v_state) {
250         case VS_ACTIVE:
251                 TAILQ_REMOVE(&vnode_active_list, vp, v_list);
252                 --activevnodes;
253                 break;
254         case VS_INACTIVE:
255                 panic("_vinactive_tail: already inactive");
256                 /* NOT REACHED */
257                 spin_unlock(&vfs_spin);
258                 return;
259         case VS_CACHED:
260         case VS_DYING:
261                 break;
262         }
263
264         TAILQ_INSERT_TAIL(&vnode_inactive_list, vp, v_list);
265         ++inactivevnodes;
266         vp->v_state = VS_INACTIVE;
267
268         spin_unlock(&vfs_spin);
269 }
270
271 /*
272  * Add a ref to an active vnode.  This function should never be called
273  * with an inactive vnode (use vget() instead), but might be called
274  * with other states.
275  */
276 void
277 vref(struct vnode *vp)
278 {
279         KASSERT((VREFCNT(vp) > 0 && vp->v_state != VS_INACTIVE),
280                 ("vref: bad refcnt %08x %d", vp->v_refcnt, vp->v_state));
281         atomic_add_int(&vp->v_refcnt, 1);
282 }
283
284 /*
285  * Release a ref on an active or inactive vnode.
286  *
287  * Caller has no other requirements.
288  *
289  * If VREF_FINALIZE is set this will deactivate the vnode on the 1->0
290  * transition, otherwise we leave the vnode in the active list and
291  * do a lockless transition to 0, which is very important for the
292  * critical path.
293  *
294  * (vrele() is not called when a vnode is being destroyed w/kfree)
295  */
296 void
297 vrele(struct vnode *vp)
298 {
299         for (;;) {
300                 int count = vp->v_refcnt;
301                 cpu_ccfence();
302                 KKASSERT((count & VREF_MASK) > 0);
303                 KKASSERT(vp->v_state == VS_ACTIVE ||
304                          vp->v_state == VS_INACTIVE);
305
306                 /*
307                  * 2+ case
308                  */
309                 if ((count & VREF_MASK) > 1) {
310                         if (atomic_cmpset_int(&vp->v_refcnt, count, count - 1))
311                                 break;
312                         continue;
313                 }
314
315                 /*
316                  * 1->0 transition case must handle possible finalization.
317                  * When finalizing we transition 1->0x40000000.  Note that
318                  * cachedvnodes is only adjusted on transitions to ->0.
319                  *
320                  * WARNING! VREF_TERMINATE can be cleared at any point
321                  *          when the refcnt is non-zero (by vget()) and
322                  *          the vnode has not been reclaimed.  Thus
323                  *          transitions out of VREF_TERMINATE do not have
324                  *          to mess with cachedvnodes.
325                  */
326                 if (count & VREF_FINALIZE) {
327                         vx_lock(vp);
328                         if (atomic_cmpset_int(&vp->v_refcnt,
329                                               count, VREF_TERMINATE)) {
330                                 vnode_terminate(vp);
331                                 break;
332                         }
333                         vx_unlock(vp);
334                 } else {
335                         if (atomic_cmpset_int(&vp->v_refcnt, count, 0)) {
336                                 atomic_add_int(&cachedvnodes, 1);
337                                 break;
338                         }
339                 }
340                 /* retry */
341         }
342 }
343
344 /*
345  * Add an auxiliary data structure reference to the vnode.  Auxiliary
346  * references do not change the state of the vnode or prevent deactivation
347  * or reclamation of the vnode, but will prevent the vnode from being
348  * destroyed (kfree()'d).
349  *
350  * WARNING!  vhold() must not acquire v_spin.  The spinlock may or may not
351  *           already be held by the caller.  vdrop() will clean up the
352  *           free list state.
353  */
354 void
355 vhold(struct vnode *vp)
356 {
357         atomic_add_int(&vp->v_auxrefs, 1);
358 }
359
360 /*
361  * Remove an auxiliary reference from the vnode.
362  */
363 void
364 vdrop(struct vnode *vp)
365 {
366         atomic_add_int(&vp->v_auxrefs, -1);
367 }
368
369 /*
370  * This function is called on the 1->0 transition (which is actually
371  * 1->VREF_TERMINATE) when VREF_FINALIZE is set, forcing deactivation
372  * of the vnode.
373  *
374  * Additional vrefs are allowed to race but will not result in a reentrant
375  * call to vnode_terminate() due to refcnt being VREF_TERMINATE.  This
376  * prevents additional 1->0 transitions.
377  *
378  * ONLY A VGET() CAN REACTIVATE THE VNODE.
379  *
380  * Caller must hold the VX lock.
381  *
382  * NOTE: v_mount may be NULL due to assigmment to dead_vnode_vops
383  *
384  * NOTE: The vnode may be marked inactive with dirty buffers
385  *       or dirty pages in its cached VM object still present.
386  *
387  * NOTE: VS_FREE should not be set on entry (the vnode was expected to
388  *       previously be active).  We lose control of the vnode the instant
389  *       it is placed on the free list.
390  *
391  *       The VX lock is required when transitioning to VS_CACHED but is
392  *       not sufficient for the vshouldfree() interlocked test or when
393  *       transitioning away from VS_CACHED.  v_spin is also required for
394  *       those cases.
395  */
396 static
397 void
398 vnode_terminate(struct vnode *vp)
399 {
400         KKASSERT(vp->v_state == VS_ACTIVE);
401
402         if ((vp->v_flag & VINACTIVE) == 0) {
403                 _vsetflags(vp, VINACTIVE);
404                 if (vp->v_mount)
405                         VOP_INACTIVE(vp);
406                 /* might deactivate page */
407         }
408         spin_lock(&vp->v_spin);
409         _vinactive(vp);
410         spin_unlock(&vp->v_spin);
411
412         vx_unlock(vp);
413 }
414
415 /****************************************************************
416  *                      VX LOCKING FUNCTIONS                    *
417  ****************************************************************
418  *
419  * These functions lock vnodes for reclamation and deactivation related
420  * activities.  The caller must already be holding some sort of reference
421  * on the vnode.
422  *
423  * MPSAFE
424  */
425 void
426 vx_lock(struct vnode *vp)
427 {
428         lockmgr(&vp->v_lock, LK_EXCLUSIVE);
429 }
430
431 /*
432  * The non-blocking version also uses a slightly different mechanic.
433  * This function will explicitly fail not only if it cannot acquire
434  * the lock normally, but also if the caller already holds a lock.
435  *
436  * The adjusted mechanic is used to close a loophole where complex
437  * VOP_RECLAIM code can circle around recursively and allocate the
438  * same vnode it is trying to destroy from the freelist.
439  *
440  * Any filesystem (aka UFS) which puts LK_CANRECURSE in lk_flags can
441  * cause the incorrect behavior to occur.  If not for that lockmgr()
442  * would do the right thing.
443  */
444 #if 0
445 static int
446 vx_lock_nonblock(struct vnode *vp)
447 {
448         if (lockcountnb(&vp->v_lock))
449                 return(EBUSY);
450         return(lockmgr(&vp->v_lock, LK_EXCLUSIVE | LK_NOWAIT));
451 }
452 #endif
453
454 void
455 vx_unlock(struct vnode *vp)
456 {
457         lockmgr(&vp->v_lock, LK_RELEASE);
458 }
459
460 /****************************************************************
461  *                      VNODE ACQUISITION FUNCTIONS             *
462  ****************************************************************
463  *
464  * These functions must be used when accessing a vnode that has no
465  * chance of being destroyed in a SMP race.  That means the caller will
466  * usually either hold an auxiliary reference (such as the namecache)
467  * or hold some other lock that ensures that the vnode cannot be destroyed.
468  *
469  * These functions are MANDATORY for any code chain accessing a vnode
470  * whos activation state is not known.
471  *
472  * vget() can be called with LK_NOWAIT and will return EBUSY if the
473  * lock cannot be immediately acquired.
474  *
475  * vget()/vput() are used when reactivation is desired.
476  *
477  * vx_get() and vx_put() are used when reactivation is not desired.
478  */
479 int
480 vget(struct vnode *vp, int flags)
481 {
482         int error;
483
484         /*
485          * A lock type must be passed
486          */
487         if ((flags & LK_TYPE_MASK) == 0) {
488                 panic("vget() called with no lock specified!");
489                 /* NOT REACHED */
490         }
491
492         /*
493          * Reference the structure and then acquire the lock.
494          *
495          * NOTE: The requested lock might be a shared lock and does
496          *       not protect our access to the refcnt or other fields.
497          */
498         if ((atomic_fetchadd_int(&vp->v_refcnt, 1) & VREF_MASK) == 0)
499                 atomic_add_int(&cachedvnodes, -1);
500
501         if ((error = vn_lock(vp, flags)) != 0) {
502                 /*
503                  * The lock failed, undo and return an error.  This will not
504                  * normally trigger a termination.
505                  */
506                 vrele(vp);
507         } else if (vp->v_flag & VRECLAIMED) {
508                 /*
509                  * The node is being reclaimed and cannot be reactivated
510                  * any more, undo and return ENOENT.
511                  */
512                 vn_unlock(vp);
513                 vrele(vp);
514                 error = ENOENT;
515         } else if (vp->v_state == VS_ACTIVE) {
516                 /*
517                  * A VS_ACTIVE vnode coupled with the fact that we have
518                  * a vnode lock (even if shared) prevents v_state from
519                  * changing.  Since the vnode is not in a VRECLAIMED state,
520                  * we can safely clear VINACTIVE.
521                  *
522                  * NOTE! Multiple threads may clear VINACTIVE if this is
523                  *       shared lock.  This race is allowed.
524                  */
525                 _vclrflags(vp, VINACTIVE);      /* SMP race ok */
526                 if (++vp->v_act > VACT_MAX)     /* SMP race ok */
527                         vp->v_act = VACT_MAX;
528                 error = 0;
529         } else {
530                 /*
531                  * If the vnode is not VS_ACTIVE it must be reactivated
532                  * in addition to clearing VINACTIVE.  An exclusive spin_lock
533                  * is needed to manipulate the vnode's list.
534                  *
535                  * Because the lockmgr lock might be shared, we might race
536                  * another reactivation, which we handle.  In this situation,
537                  * however, the refcnt prevents other v_state races.
538                  *
539                  * As with above, clearing VINACTIVE is allowed to race other
540                  * clearings of VINACTIVE.
541                  *
542                  * VREF_TERMINATE and VREF_FINALIZE can only be cleared when
543                  * the refcnt is non-zero and the vnode has not been
544                  * reclaimed.  This also means that the transitions do
545                  * not affect cachedvnodes.
546                  */
547                 _vclrflags(vp, VINACTIVE);
548                 if (++vp->v_act > VACT_MAX)     /* SMP race ok */
549                         vp->v_act = VACT_MAX;
550                 spin_lock(&vp->v_spin);
551
552                 switch(vp->v_state) {
553                 case VS_INACTIVE:
554                         _vactivate(vp);
555                         atomic_clear_int(&vp->v_refcnt, VREF_TERMINATE |
556                                                         VREF_FINALIZE);
557                         spin_unlock(&vp->v_spin);
558                         break;
559                 case VS_CACHED:
560                         _vactivate(vp);
561                         atomic_clear_int(&vp->v_refcnt, VREF_TERMINATE |
562                                                         VREF_FINALIZE);
563                         spin_unlock(&vp->v_spin);
564                         break;
565                 case VS_ACTIVE:
566                         atomic_clear_int(&vp->v_refcnt, VREF_FINALIZE);
567                         spin_unlock(&vp->v_spin);
568                         break;
569                 case VS_DYING:
570                         spin_unlock(&vp->v_spin);
571                         panic("Impossible VS_DYING state");
572                         break;
573                 }
574                 error = 0;
575         }
576         return(error);
577 }
578
579 #ifdef DEBUG_VPUT
580
581 void
582 debug_vput(struct vnode *vp, const char *filename, int line)
583 {
584         kprintf("vput(%p) %s:%d\n", vp, filename, line);
585         vn_unlock(vp);
586         vrele(vp);
587 }
588
589 #else
590
591 /*
592  * MPSAFE
593  */
594 void
595 vput(struct vnode *vp)
596 {
597         vn_unlock(vp);
598         vrele(vp);
599 }
600
601 #endif
602
603 /*
604  * Acquire the vnode lock unguarded.
605  *
606  * XXX The vx_*() locks should use auxrefs, not the main reference counter.
607  */
608 void
609 vx_get(struct vnode *vp)
610 {
611         if ((atomic_fetchadd_int(&vp->v_refcnt, 1) & VREF_MASK) == 0)
612                 atomic_add_int(&cachedvnodes, -1);
613         lockmgr(&vp->v_lock, LK_EXCLUSIVE);
614 }
615
616 int
617 vx_get_nonblock(struct vnode *vp)
618 {
619         int error;
620
621         if (lockcountnb(&vp->v_lock))
622                 return(EBUSY);
623         error = lockmgr(&vp->v_lock, LK_EXCLUSIVE | LK_NOWAIT);
624         if (error == 0) {
625                 if ((atomic_fetchadd_int(&vp->v_refcnt, 1) & VREF_MASK) == 0)
626                         atomic_add_int(&cachedvnodes, -1);
627         }
628         return(error);
629 }
630
631 /*
632  * Release a VX lock that also held a ref on the vnode.  vrele() will handle
633  * any needed state transitions.
634  *
635  * However, filesystems use this function to get rid of unwanted new vnodes
636  * so try to get the vnode on the correct queue in that case.
637  */
638 void
639 vx_put(struct vnode *vp)
640 {
641         if (vp->v_type == VNON || vp->v_type == VBAD)
642                 atomic_set_int(&vp->v_refcnt, VREF_FINALIZE);
643         lockmgr(&vp->v_lock, LK_RELEASE);
644         vrele(vp);
645 }
646
647 /*
648  * Try to reuse a vnode from the free list.  This function is somewhat
649  * advisory in that NULL can be returned as a normal case, even if free
650  * vnodes are present.
651  *
652  * The scan is limited because it can result in excessive CPU use during
653  * periods of extreme vnode use.
654  *
655  * NOTE: The returned vnode is not completely initialized.
656  *
657  * MPSAFE
658  */
659 static
660 struct vnode *
661 cleanfreevnode(int maxcount)
662 {
663         struct vnode *vp;
664         int count;
665
666         /*
667          * Try to deactivate some vnodes cached on the active list.
668          */
669         if (cachedvnodes < inactivevnodes)
670                 goto skip;
671
672         for (count = 0; count < maxcount * 2; count++) {
673                 spin_lock(&vfs_spin);
674
675                 vp = TAILQ_NEXT(&vnode_active_rover, v_list);
676                 TAILQ_REMOVE(&vnode_active_list, &vnode_active_rover, v_list);
677                 if (vp == NULL) {
678                         TAILQ_INSERT_HEAD(&vnode_active_list,
679                                           &vnode_active_rover, v_list);
680                 } else {
681                         TAILQ_INSERT_AFTER(&vnode_active_list, vp,
682                                            &vnode_active_rover, v_list);
683                 }
684                 if (vp == NULL || (vp->v_refcnt & VREF_MASK) != 0) {
685                         spin_unlock(&vfs_spin);
686                         continue;
687                 }
688                 if (vp->v_act > 0) {
689                         --vp->v_act;
690                         spin_unlock(&vfs_spin);
691                         continue;
692                 }
693
694                 /*
695                  * Try to deactivate the vnode.
696                  */
697                 if ((atomic_fetchadd_int(&vp->v_refcnt, 1) & VREF_MASK) == 0)
698                         atomic_add_int(&cachedvnodes, -1);
699                 atomic_set_int(&vp->v_refcnt, VREF_FINALIZE);
700
701                 spin_unlock(&vfs_spin);
702                 vrele(vp);
703         }
704
705 skip:
706         /*
707          * Loop trying to lock the first vnode on the free list.
708          * Cycle if we can't.
709          */
710         for (count = 0; count < maxcount; count++) {
711                 spin_lock(&vfs_spin);
712
713                 vp = TAILQ_FIRST(&vnode_inactive_list);
714                 if (vp == NULL) {
715                         spin_unlock(&vfs_spin);
716                         break;
717                 }
718
719                 /*
720                  * non-blocking vx_get will also ref the vnode on success.
721                  */
722                 if (vx_get_nonblock(vp)) {
723                         KKASSERT(vp->v_state == VS_INACTIVE);
724                         TAILQ_REMOVE(&vnode_inactive_list, vp, v_list);
725                         TAILQ_INSERT_TAIL(&vnode_inactive_list, vp, v_list);
726                         spin_unlock(&vfs_spin);
727                         continue;
728                 }
729
730                 /*
731                  * Because we are holding vfs_spin the vnode should currently
732                  * be inactive and VREF_TERMINATE should still be set.
733                  *
734                  * Once vfs_spin is released the vnode's state should remain
735                  * unmodified due to both the lock and ref on it.
736                  */
737                 KKASSERT(vp->v_state == VS_INACTIVE);
738                 spin_unlock(&vfs_spin);
739 #ifdef TRACKVNODE
740                 if ((ulong)vp == trackvnode)
741                         kprintf("cleanfreevnode %p %08x\n", vp, vp->v_flag);
742 #endif
743
744                 /*
745                  * Do not reclaim/reuse a vnode while auxillary refs exists.
746                  * This includes namecache refs due to a related ncp being
747                  * locked or having children, a VM object association, or
748                  * other hold users.
749                  *
750                  * Do not reclaim/reuse a vnode if someone else has a real
751                  * ref on it.  This can occur if a filesystem temporarily
752                  * releases the vnode lock during VOP_RECLAIM.
753                  */
754                 if (vp->v_auxrefs ||
755                     (vp->v_refcnt & ~VREF_FINALIZE) != VREF_TERMINATE + 1) {
756 failed:
757                         if (vp->v_state == VS_INACTIVE) {
758                                 spin_lock(&vfs_spin);
759                                 if (vp->v_state == VS_INACTIVE) {
760                                         TAILQ_REMOVE(&vnode_inactive_list,
761                                                      vp, v_list);
762                                         TAILQ_INSERT_TAIL(&vnode_inactive_list,
763                                                           vp, v_list);
764                                 }
765                                 spin_unlock(&vfs_spin);
766                         }
767                         vx_put(vp);
768                         continue;
769                 }
770
771                 /*
772                  * VINACTIVE and VREF_TERMINATE are expected to both be set
773                  * for vnodes pulled from the inactive list, and cannot be
774                  * changed while we hold the vx lock.
775                  *
776                  * Try to reclaim the vnode.
777                  */
778                 KKASSERT(vp->v_flag & VINACTIVE);
779                 KKASSERT(vp->v_refcnt & VREF_TERMINATE);
780
781                 if ((vp->v_flag & VRECLAIMED) == 0) {
782                         if (cache_inval_vp_nonblock(vp))
783                                 goto failed;
784                         vgone_vxlocked(vp);
785                         /* vnode is still VX locked */
786                 }
787
788                 /*
789                  * At this point if there are no other refs or auxrefs on
790                  * the vnode with the inactive list locked, and we remove
791                  * the vnode from the inactive list, it should not be
792                  * possible for anyone else to access the vnode any more.
793                  *
794                  * Since the vnode is in a VRECLAIMED state, no new
795                  * namecache associations could have been made and the
796                  * vnode should have already been removed from its mountlist.
797                  *
798                  * Since we hold a VX lock on the vnode it cannot have been
799                  * reactivated (moved out of the inactive list).
800                  */
801                 KKASSERT(TAILQ_EMPTY(&vp->v_namecache));
802                 spin_lock(&vfs_spin);
803                 if (vp->v_auxrefs ||
804                     (vp->v_refcnt & ~VREF_FINALIZE) != VREF_TERMINATE + 1) {
805                         spin_unlock(&vfs_spin);
806                         goto failed;
807                 }
808                 KKASSERT(vp->v_state == VS_INACTIVE);
809                 TAILQ_REMOVE(&vnode_inactive_list, vp, v_list);
810                 --inactivevnodes;
811                 vp->v_state = VS_DYING;
812                 spin_unlock(&vfs_spin);
813
814                 /*
815                  * Nothing should have been able to access this vp.  Only
816                  * our ref should remain now.
817                  */
818                 atomic_clear_int(&vp->v_refcnt, VREF_TERMINATE|VREF_FINALIZE);
819                 KASSERT(vp->v_refcnt == 1,
820                         ("vp %p badrefs %08x", vp, vp->v_refcnt));
821
822                 /*
823                  * Return a VX locked vnode suitable for reuse.
824                  */
825                 return(vp);
826         }
827         return(NULL);
828 }
829
830 /*
831  * Obtain a new vnode.  The returned vnode is VX locked & vrefd.
832  *
833  * All new vnodes set the VAGE flags.  An open() of the vnode will
834  * decrement the (2-bit) flags.  Vnodes which are opened several times
835  * are thus retained in the cache over vnodes which are merely stat()d.
836  *
837  * We always allocate the vnode.  Attempting to recycle existing vnodes
838  * here can lead to numerous deadlocks, particularly with softupdates.
839  */
840 struct vnode *
841 allocvnode(int lktimeout, int lkflags)
842 {
843         struct vnode *vp;
844
845         /*
846          * Do not flag for recyclement unless there are enough free vnodes
847          * to recycle and the number of vnodes has exceeded our target.
848          *
849          * The vnlru tries to get to this before we are forced to do it
850          * synchronously in userexit, using 2/10.
851          */
852         if (numvnodes >= desiredvnodes &&
853             cachedvnodes + inactivevnodes > desiredvnodes * 5 / 10 &&
854             cachedvnodes + inactivevnodes > wantfreevnodes) {
855                 struct thread *td = curthread;
856                 if (td->td_lwp)
857                         atomic_set_int(&td->td_lwp->lwp_mpflags, LWP_MP_VNLRU);
858         }
859
860         /*
861          * lktimeout only applies when LK_TIMELOCK is used, and only
862          * the pageout daemon uses it.  The timeout may not be zero
863          * or the pageout daemon can deadlock in low-VM situations.
864          */
865         if (lktimeout == 0)
866                 lktimeout = hz / 10;
867
868         vp = kmalloc(sizeof(*vp), M_VNODE, M_ZERO | M_WAITOK);
869
870         lwkt_token_init(&vp->v_token, "vnode");
871         lockinit(&vp->v_lock, "vnode", lktimeout, lkflags);
872         TAILQ_INIT(&vp->v_namecache);
873         RB_INIT(&vp->v_rbclean_tree);
874         RB_INIT(&vp->v_rbdirty_tree);
875         RB_INIT(&vp->v_rbhash_tree);
876         spin_init(&vp->v_spin);
877
878         lockmgr(&vp->v_lock, LK_EXCLUSIVE);
879         atomic_add_int(&numvnodes, 1);
880         vp->v_refcnt = 1;
881         vp->v_flag = VAGE0 | VAGE1;
882
883         KKASSERT(TAILQ_EMPTY(&vp->v_namecache));
884         /* exclusive lock still held */
885
886         vp->v_filesize = NOOFFSET;
887         vp->v_type = VNON;
888         vp->v_tag = 0;
889         vp->v_state = VS_CACHED;
890         _vactivate(vp);
891
892         return (vp);
893 }
894
895 /*
896  * Called after a process has allocated a vnode via allocvnode()
897  * and we detected that too many vnodes were present.
898  *
899  * Try to reuse vnodes if we hit the max.  This situation only
900  * occurs in certain large-memory (2G+) situations on 32 bit systems,
901  * or if kern.maxvnodes is set to very low values.
902  *
903  * This function is called just prior to a return to userland if the
904  * process at some point had to allocate a new vnode during the last
905  * system call and the vnode count was found to be excessive.
906  *
907  * WARNING: Sometimes numvnodes can blow out due to children being
908  *          present under directory vnodes in the namecache.  For the
909  *          moment use an if() instead of a while() and note that if
910  *          we were to use a while() we would still have to break out
911  *          if freesomevnodes() returned 0.
912  */
913 void
914 allocvnode_gc(void)
915 {
916         if (numvnodes > desiredvnodes &&
917             cachedvnodes + inactivevnodes > wantfreevnodes) {
918                 freesomevnodes(batchfreevnodes);
919         }
920 }
921
922 /*
923  * MPSAFE
924  */
925 int
926 freesomevnodes(int n)
927 {
928         struct vnode *vp;
929         int count = 0;
930
931         while (n) {
932                 if ((vp = cleanfreevnode(n)) == NULL)
933                         break;
934                 vx_unlock(vp);
935                 --n;
936                 ++count;
937                 kfree(vp, M_VNODE);
938                 atomic_add_int(&numvnodes, -1);
939         }
940         return(count);
941 }