VNode sequencing and locking - part 1/4.
[dragonfly.git] / sys / kern / vfs_lock.c
1 /*
2  * Copyright (c) 2004 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  * $DragonFly: src/sys/kern/vfs_lock.c,v 1.20 2006/08/09 22:47:32 dillon Exp $
35  */
36
37 /*
38  * External virtual filesystem routines
39  */
40 #include "opt_ddb.h"
41
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
45 #include <sys/malloc.h>
46 #include <sys/mount.h>
47 #include <sys/proc.h>
48 #include <sys/vnode.h>
49 #include <sys/buf.h>
50 #include <sys/sysctl.h>
51
52 #include <machine/limits.h>
53
54 #include <vm/vm.h>
55 #include <vm/vm_object.h>
56
57 #include <sys/buf2.h>
58 #include <sys/thread2.h>
59
60
61 static MALLOC_DEFINE(M_VNODE, "vnodes", "vnode structures");
62
63 static TAILQ_HEAD(freelst, vnode) vnode_free_list;      /* vnode free list */
64
65 int  freevnodes = 0;
66 SYSCTL_INT(_debug, OID_AUTO, freevnodes, CTLFLAG_RD,
67                 &freevnodes, 0, "");
68 static int wantfreevnodes = 25;
69 SYSCTL_INT(_debug, OID_AUTO, wantfreevnodes, CTLFLAG_RW,
70                 &wantfreevnodes, 0, "");
71 static int minvnodes;
72 SYSCTL_INT(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
73                 &minvnodes, 0, "Minimum number of vnodes");
74
75 /*
76  * Called from vfsinit()
77  */
78 void
79 vfs_lock_init(void)
80 {
81         minvnodes = desiredvnodes / 4;
82
83         TAILQ_INIT(&vnode_free_list);
84 }
85
86 /*
87  * Inline helper functions.  vbusy() and vfree() must be called while in a
88  * critical section.
89  *
90  * Warning: must be callable if the caller holds a read spinlock to something
91  * else, meaning we can't use read spinlocks here.
92  */
93 static __inline 
94 void
95 __vbusy(struct vnode *vp)
96 {
97         TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
98         freevnodes--;
99         vp->v_flag &= ~(VFREE|VAGE);
100 }
101
102 static __inline
103 void
104 __vfree(struct vnode *vp)
105 {
106         if (vp->v_flag & (VAGE|VRECLAIMED))
107                 TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
108         else
109                 TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
110         freevnodes++;
111         vp->v_flag &= ~VAGE;
112         vp->v_flag |= VFREE;
113 }
114
115 /*
116  * Return 1 if we can immediately place the vnode on the freelist.
117  */
118 static __inline int
119 vshouldfree(struct vnode *vp, int usecount)
120 {
121         if (vp->v_flag & VFREE)
122                 return (0);             /* already free */
123         if (vp->v_holdcnt != 0 || vp->v_usecount != usecount)
124                 return (0);             /* other holderse */
125         if (vp->v_object &&
126             (vp->v_object->ref_count || vp->v_object->resident_page_count)) {
127                 return (0);
128         }
129         return (1);
130 }
131
132 /*
133  * Reference a vnode or release the reference on a vnode.  The vnode will
134  * be taken off the freelist if it is on it and cannot be recycled or 
135  * deactivated while refd.  The last release of a vnode will deactivate the
136  * vnode via VOP_INACTIVE().
137  *
138  * Special cases: refing a vnode does not clear VINACTIVE, you have to vget()
139  * the vnode shared or exclusive to do that.
140  *
141  * Warning: must be callable if the caller holds a read spinlock to something
142  * else, meaning we can't use read spinlocks here.
143  */
144 static __inline
145 void
146 __vref(struct vnode *vp)
147 {
148         ++vp->v_usecount;
149         if (vp->v_flag & VFREE)
150                 __vbusy(vp);
151 }
152
153 /*
154  * Add another ref to a vnode.  The vnode must already have at least one
155  * ref.
156  */
157 void
158 vref(struct vnode *vp)
159 {
160         KKASSERT(vp->v_usecount > 0 && (vp->v_flag & (VFREE|VINACTIVE)) == 0);
161         atomic_add_int(&vp->v_usecount, 1);
162 }
163
164 /*
165  * Add a ref to a vnode which may not have any refs.  This routine is called
166  * from the namecache and vx_get().  The vnode is explicitly removed from
167  * the freelist if necessary.  If requested, the vnode will be reactivated.
168  *
169  * vget(), cache_vget(), and cache_vref() reactives vnodes.  vx_get() does
170  * not.
171  */
172 void
173 vref_initial(struct vnode *vp, int reactivate)
174 {
175         crit_enter();
176         __vref(vp);
177         if (reactivate)
178                 vp->v_flag &= ~VINACTIVE;
179         crit_exit();
180 }
181
182 void
183 vrele(struct vnode *vp)
184 {
185         crit_enter();
186         if (vp->v_usecount == 1) {
187                 KASSERT(lockcountnb(&vp->v_lock) == 0,
188                         ("last vrele vp %p still locked", vp));
189
190                 /*
191                  * Deactivation requires an exclusive v_lock (vx_lock()), and
192                  * only occurs if the usecount is still 1 after locking.
193                  */
194                 if ((vp->v_flag & VINACTIVE) == 0) {
195                         if (vx_lock(vp) == 0) {
196                                 if ((vp->v_flag & VINACTIVE) == 0 &&
197                                     vp->v_usecount == 1) {
198                                         vp->v_flag |= VINACTIVE;
199                                         VOP_INACTIVE(vp);
200                                 }
201                                 vx_unlock(vp);
202                         }
203                 }
204                 if (vshouldfree(vp, 1))
205                         __vfree(vp);
206         } else {
207                 KKASSERT(vp->v_usecount > 0);
208         }
209         --vp->v_usecount;
210         crit_exit();
211 }
212
213 /*
214  * Hold a vnode, preventing it from being recycled (unless it is already
215  * undergoing a recyclement or already has been recycled).
216  *
217  * NOTE: vhold() will defer removal of the vnode from the freelist.
218  */
219 void
220 vhold(struct vnode *vp)
221 {
222         atomic_add_int(&vp->v_holdcnt, 1);
223 }
224
225 void
226 vdrop(struct vnode *vp)
227 {
228         crit_enter();
229         if (vp->v_holdcnt == 1) {
230                 --vp->v_holdcnt;
231                 if (vshouldfree(vp, 0))
232                         __vfree(vp);
233         } else {
234                 --vp->v_holdcnt;
235                 KKASSERT(vp->v_holdcnt > 0);
236         }
237         crit_exit();
238 }
239
240 /****************************************************************
241  *                      VX LOCKING FUNCTIONS                    *
242  ****************************************************************
243  *
244  * These functions lock vnodes for reclamation and deactivation related
245  * activities.  Only vp->v_lock, the top layer of the VFS, is locked.
246  * You must be holding a normal reference in order to be able to safely
247  * call vx_lock() and vx_unlock().
248  *
249  * vx_get() also differs from vget() in that it does not clear the
250  * VINACTIVE bit on a vnode.
251  */
252
253 #define VXLOCKFLAGS     (LK_EXCLUSIVE|LK_RETRY)
254 #define VXLOCKFLAGS_NB  (LK_EXCLUSIVE|LK_NOWAIT)
255
256 static int
257 __vxlock(struct vnode *vp, int flags)
258 {
259         return(lockmgr(&vp->v_lock, flags));
260 }
261
262 static void
263 __vxunlock(struct vnode *vp)
264 {
265         lockmgr(&vp->v_lock, LK_RELEASE);
266 }
267
268 int
269 vx_lock(struct vnode *vp)
270 {
271         return(__vxlock(vp, VXLOCKFLAGS));
272 }
273
274 void
275 vx_unlock(struct vnode *vp)
276 {
277         __vxunlock(vp);
278 }
279
280 int
281 vx_get(struct vnode *vp)
282 {
283         int error;
284
285         vref_initial(vp, 0);
286         if ((error = __vxlock(vp, VXLOCKFLAGS)) != 0)
287                 vrele(vp);
288         return(error);
289 }
290
291 int
292 vx_get_nonblock(struct vnode *vp)
293 {
294         int error;
295
296         vref_initial(vp, 0);
297         if ((error = __vxlock(vp, VXLOCKFLAGS_NB)) != 0)
298                 vrele(vp);
299         return(error);
300 }
301
302 void
303 vx_put(struct vnode *vp)
304 {
305         __vxunlock(vp);
306         vrele(vp);
307 }
308
309 /****************************************************************
310  *                      VNODE ACQUISITION FUNCTIONS             *
311  ****************************************************************
312  *
313  * vget() and vput() access a vnode for the intent of executing an
314  * operation other then a reclamation or deactivation.  vget() will ref
315  * and lock the vnode, vput() will unlock and deref the vnode.  
316  * The VOP_*() locking functions are used.
317  *
318  * CALLING VGET IS MANDATORY PRIOR TO ANY MODIFYING OPERATION ON A VNODE.
319  * This is because vget handles the VINACTIVE interlock and is responsible
320  * for clearing the bit.  If the bit is not cleared inode updates may not
321  * make it to disk.
322  *
323  * Special cases: If vget()'s locking operation fails the vrele() call may
324  * cause the vnode to be deactivated (VOP_INACTIVE called).  However, this
325  * never occurs if the vnode is in a reclaimed state.  Vnodes in reclaimed
326  * states always return an error code of ENOENT.
327  *
328  * Special cases: vput() will unlock and, if it is the last reference, 
329  * deactivate the vnode.  The deactivation uses a separate non-layered
330  * VX lock after the normal unlock.  XXX make it more efficient.
331  */
332 int
333 vget(struct vnode *vp, int flags)
334 {
335         int error;
336
337         crit_enter();
338         __vref(vp);
339         if (flags & LK_TYPE_MASK) {
340                 if ((error = vn_lock(vp, flags)) != 0) {
341                         vrele(vp);
342                 } else if (vp->v_flag & VRECLAIMED) {
343                         VOP_UNLOCK(vp, 0);
344                         vrele(vp);
345                         error = ENOENT;
346                 } else {
347                         vp->v_flag &= ~VINACTIVE;
348                         error = 0;
349                 }
350         } else {
351                 panic("vget() called with no lock specified!");
352                 error = ENOENT; /* not reached, compiler opt */
353         }
354         crit_exit();
355         return(error);
356 }
357
358 void
359 vput(struct vnode *vp)
360 {
361         VOP_UNLOCK(vp, 0);
362         vrele(vp);
363 }
364
365 void
366 vsetflags(struct vnode *vp, int flags)
367 {
368         crit_enter();
369         vp->v_flag |= flags;
370         crit_exit();
371 }
372
373 void
374 vclrflags(struct vnode *vp, int flags)
375 {
376         crit_enter();
377         vp->v_flag &= ~flags;
378         crit_exit();
379 }
380
381 /*
382  * Obtain a new vnode from the freelist, allocating more if necessary.
383  * The returned vnode is VX locked & refd.
384  */
385 struct vnode *
386 allocvnode(int lktimeout, int lkflags)
387 {
388         struct thread *td;
389         struct vnode *vp;
390
391         /*
392          * Try to reuse vnodes if we hit the max.  This situation only
393          * occurs in certain large-memory (2G+) situations.  We cannot
394          * attempt to directly reclaim vnodes due to nasty recursion
395          * problems.
396          */
397         while (numvnodes - freevnodes > desiredvnodes)
398                 vnlru_proc_wait();
399
400         td = curthread;
401         vp = NULL;
402
403         /*
404          * Attempt to reuse a vnode already on the free list, allocating
405          * a new vnode if we can't find one or if we have not reached a
406          * good minimum for good LRU performance.
407          */
408         if (freevnodes >= wantfreevnodes && numvnodes >= minvnodes) {
409                 int count;
410
411                 for (count = 0; count < freevnodes; count++) {
412                         /*
413                          * __VNODESCAN__
414                          *
415                          * Pull the next vnode off the free list and do some
416                          * sanity checks.  Note that regardless of how we
417                          * block, if freevnodes is non-zero there had better
418                          * be something on the list.
419                          */
420                         vp = TAILQ_FIRST(&vnode_free_list);
421                         if (vp == NULL)
422                                 panic("getnewvnode: free vnode isn't");
423
424                         /*
425                          * Note the lack of a critical section.  We vx_get()
426                          * the vnode before we check it for validity, reducing
427                          * the number of checks we have to make.  The vx_get()
428                          * will also pull the vnode off of the freelist.
429                          */
430                         if (vx_get(vp)) {
431                                 vp = NULL;
432                                 continue;
433                         }
434
435                         /*
436                          * Can this vnode be recycled?  It must be in a
437                          * VINACTIVE state with only our reference to it.
438                          * (vx_get(), unlike vget(), does not reactivate
439                          * the vnode).  vx_put() will recycle it onto the
440                          * end of the freelist.
441                          */
442                         if ((vp->v_flag & VINACTIVE) == 0 ||
443                             vp->v_holdcnt || vp->v_usecount != 1) {
444                                 vx_put(vp);
445                                 vp = NULL;
446                                 continue;
447                         }
448
449                         /*
450                          * Ok, we can reclaim the vnode if it isn't already
451                          * in a reclaimed state.  If the reclamation fails,
452                          * or if someone else is referencing the vnode after
453                          * we have vgone()'d it, we stop here.
454                          */
455                         if ((vp->v_flag & VRECLAIMED) == 0) {
456                                 vgone(vp);
457                                 if ((vp->v_flag & VRECLAIMED) == 0 ||
458                                     vp->v_holdcnt || vp->v_usecount != 1) {
459                                         vx_put(vp);
460                                         vp = NULL;
461                                         continue;
462                                 }
463                         }
464                         KKASSERT(vp->v_flag & VINACTIVE);
465
466                         /*
467                          * We have a vnode!
468                          */
469                         break;
470                 }
471         }
472
473         /*
474          * If we have a vp it will be refd and VX locked.
475          */
476         if (vp) {
477 #ifdef INVARIANTS
478                 if (vp->v_data)
479                         panic("cleaned vnode isn't");
480                 if (vp->v_track_read.bk_active + vp->v_track_write.bk_active)
481                         panic("Clean vnode has pending I/O's");
482                 KKASSERT(vp->v_mount == NULL);
483 #endif
484                 vp->v_flag = 0;
485                 vp->v_lastw = 0;
486                 vp->v_lasta = 0;
487                 vp->v_cstart = 0;
488                 vp->v_clen = 0;
489                 vp->v_socket = 0;
490                 vp->v_opencount = 0;
491                 vp->v_writecount = 0;   /* XXX */
492                 lockreinit(&vp->v_lock, "vnode", lktimeout, lkflags);
493                 KKASSERT(TAILQ_FIRST(&vp->v_namecache) == NULL);
494         } else {
495                 /*
496                  * A brand-new vnode (we could use malloc() here I think) XXX
497                  */
498                 vp = malloc(sizeof(struct vnode), M_VNODE, M_WAITOK|M_ZERO);
499                 lwkt_token_init(&vp->v_pollinfo.vpi_token);
500                 lockinit(&vp->v_lock, "vnode", lktimeout, lkflags);
501                 TAILQ_INIT(&vp->v_namecache);
502
503                 /*
504                  * short cut around vfreeing it and looping, just set it up
505                  * as if we had pulled a reclaimed vnode off the freelist
506                  * and reinitialized it.
507                  */
508                 vp->v_usecount = 1;
509                 if (__vxlock(vp, VXLOCKFLAGS))
510                         panic("getnewvnode: __vxlock failed");
511                 numvnodes++;
512         }
513
514         RB_INIT(&vp->v_rbclean_tree);
515         RB_INIT(&vp->v_rbdirty_tree);
516         RB_INIT(&vp->v_rbhash_tree);
517         vp->v_filesize = NOOFFSET;
518         vp->v_type = VNON;
519         vp->v_tag = 0;
520         vp->v_ops = NULL;
521         vp->v_data = NULL;
522         KKASSERT(vp->v_mount == NULL);
523         return (vp);
524 }
525