Make biowait() MPSAFE.
[dragonfly.git] / sys / kern / vfs_bio.c
1 /*
2  * Copyright (c) 1994,1997 John S. Dyson
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice immediately at the beginning of the file, without modification,
10  *    this list of conditions, and the following disclaimer.
11  * 2. Absolutely no warranty of function or purpose is made by the author
12  *              John S. Dyson.
13  *
14  * $FreeBSD: src/sys/kern/vfs_bio.c,v 1.242.2.20 2003/05/28 18:38:10 alc Exp $
15  * $DragonFly: src/sys/kern/vfs_bio.c,v 1.115 2008/08/13 11:02:31 swildner Exp $
16  */
17
18 /*
19  * this file contains a new buffer I/O scheme implementing a coherent
20  * VM object and buffer cache scheme.  Pains have been taken to make
21  * sure that the performance degradation associated with schemes such
22  * as this is not realized.
23  *
24  * Author:  John S. Dyson
25  * Significant help during the development and debugging phases
26  * had been provided by David Greenman, also of the FreeBSD core team.
27  *
28  * see man buf(9) for more info.
29  */
30
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/buf.h>
34 #include <sys/conf.h>
35 #include <sys/eventhandler.h>
36 #include <sys/lock.h>
37 #include <sys/malloc.h>
38 #include <sys/mount.h>
39 #include <sys/kernel.h>
40 #include <sys/kthread.h>
41 #include <sys/proc.h>
42 #include <sys/reboot.h>
43 #include <sys/resourcevar.h>
44 #include <sys/sysctl.h>
45 #include <sys/vmmeter.h>
46 #include <sys/vnode.h>
47 #include <sys/proc.h>
48 #include <vm/vm.h>
49 #include <vm/vm_param.h>
50 #include <vm/vm_kern.h>
51 #include <vm/vm_pageout.h>
52 #include <vm/vm_page.h>
53 #include <vm/vm_object.h>
54 #include <vm/vm_extern.h>
55 #include <vm/vm_map.h>
56
57 #include <sys/buf2.h>
58 #include <sys/thread2.h>
59 #include <sys/spinlock2.h>
60 #include <vm/vm_page2.h>
61
62 #include "opt_ddb.h"
63 #ifdef DDB
64 #include <ddb/ddb.h>
65 #endif
66
67 /*
68  * Buffer queues.
69  */
70 enum bufq_type {
71         BQUEUE_NONE,            /* not on any queue */
72         BQUEUE_LOCKED,          /* locked buffers */
73         BQUEUE_CLEAN,           /* non-B_DELWRI buffers */
74         BQUEUE_DIRTY,           /* B_DELWRI buffers */
75         BQUEUE_DIRTY_HW,        /* B_DELWRI buffers - heavy weight */
76         BQUEUE_EMPTYKVA,        /* empty buffer headers with KVA assignment */
77         BQUEUE_EMPTY,           /* empty buffer headers */
78
79         BUFFER_QUEUES           /* number of buffer queues */
80 };
81
82 typedef enum bufq_type bufq_type_t;
83
84 #define BD_WAKE_SIZE    128
85 #define BD_WAKE_MASK    (BD_WAKE_SIZE - 1)
86
87 TAILQ_HEAD(bqueues, buf) bufqueues[BUFFER_QUEUES];
88
89 static MALLOC_DEFINE(M_BIOBUF, "BIO buffer", "BIO buffer");
90
91 struct buf *buf;                /* buffer header pool */
92
93 static void vfs_page_set_valid(struct buf *bp, vm_ooffset_t off,
94                                int pageno, vm_page_t m);
95 static void vfs_clean_pages(struct buf *bp);
96 static void vfs_setdirty(struct buf *bp);
97 static void vfs_vmio_release(struct buf *bp);
98 static int flushbufqueues(bufq_type_t q);
99 static vm_page_t bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit);
100
101 static void bd_signal(int totalspace);
102 static void buf_daemon(void);
103 static void buf_daemon_hw(void);
104
105 /*
106  * bogus page -- for I/O to/from partially complete buffers
107  * this is a temporary solution to the problem, but it is not
108  * really that bad.  it would be better to split the buffer
109  * for input in the case of buffers partially already in memory,
110  * but the code is intricate enough already.
111  */
112 vm_page_t bogus_page;
113
114 /*
115  * These are all static, but make the ones we export globals so we do
116  * not need to use compiler magic.
117  */
118 int bufspace, maxbufspace,
119         bufmallocspace, maxbufmallocspace, lobufspace, hibufspace;
120 static int bufreusecnt, bufdefragcnt, buffreekvacnt;
121 static int lorunningspace, hirunningspace, runningbufreq;
122 int dirtybufspace, dirtybufspacehw, lodirtybufspace, hidirtybufspace;
123 int dirtybufcount, dirtybufcounthw;
124 int runningbufspace, runningbufcount;
125 static int getnewbufcalls;
126 static int getnewbufrestarts;
127 static int recoverbufcalls;
128 static int needsbuffer;         /* locked by needsbuffer_spin */
129 static int bd_request;          /* locked by needsbuffer_spin */
130 static int bd_request_hw;       /* locked by needsbuffer_spin */
131 static u_int bd_wake_ary[BD_WAKE_SIZE];
132 static u_int bd_wake_index;
133 static struct spinlock needsbuffer_spin;
134
135 static struct thread *bufdaemon_td;
136 static struct thread *bufdaemonhw_td;
137
138
139 /*
140  * Sysctls for operational control of the buffer cache.
141  */
142 SYSCTL_INT(_vfs, OID_AUTO, lodirtybufspace, CTLFLAG_RW, &lodirtybufspace, 0,
143         "Number of dirty buffers to flush before bufdaemon becomes inactive");
144 SYSCTL_INT(_vfs, OID_AUTO, hidirtybufspace, CTLFLAG_RW, &hidirtybufspace, 0,
145         "High watermark used to trigger explicit flushing of dirty buffers");
146 SYSCTL_INT(_vfs, OID_AUTO, lorunningspace, CTLFLAG_RW, &lorunningspace, 0,
147         "Minimum amount of buffer space required for active I/O");
148 SYSCTL_INT(_vfs, OID_AUTO, hirunningspace, CTLFLAG_RW, &hirunningspace, 0,
149         "Maximum amount of buffer space to usable for active I/O");
150 /*
151  * Sysctls determining current state of the buffer cache.
152  */
153 SYSCTL_INT(_vfs, OID_AUTO, nbuf, CTLFLAG_RD, &nbuf, 0,
154         "Total number of buffers in buffer cache");
155 SYSCTL_INT(_vfs, OID_AUTO, dirtybufspace, CTLFLAG_RD, &dirtybufspace, 0,
156         "Pending bytes of dirty buffers (all)");
157 SYSCTL_INT(_vfs, OID_AUTO, dirtybufspacehw, CTLFLAG_RD, &dirtybufspacehw, 0,
158         "Pending bytes of dirty buffers (heavy weight)");
159 SYSCTL_INT(_vfs, OID_AUTO, dirtybufcount, CTLFLAG_RD, &dirtybufcount, 0,
160         "Pending number of dirty buffers");
161 SYSCTL_INT(_vfs, OID_AUTO, dirtybufcounthw, CTLFLAG_RD, &dirtybufcounthw, 0,
162         "Pending number of dirty buffers (heavy weight)");
163 SYSCTL_INT(_vfs, OID_AUTO, runningbufspace, CTLFLAG_RD, &runningbufspace, 0,
164         "I/O bytes currently in progress due to asynchronous writes");
165 SYSCTL_INT(_vfs, OID_AUTO, runningbufcount, CTLFLAG_RD, &runningbufcount, 0,
166         "I/O buffers currently in progress due to asynchronous writes");
167 SYSCTL_INT(_vfs, OID_AUTO, maxbufspace, CTLFLAG_RD, &maxbufspace, 0,
168         "Hard limit on maximum amount of memory usable for buffer space");
169 SYSCTL_INT(_vfs, OID_AUTO, hibufspace, CTLFLAG_RD, &hibufspace, 0,
170         "Soft limit on maximum amount of memory usable for buffer space");
171 SYSCTL_INT(_vfs, OID_AUTO, lobufspace, CTLFLAG_RD, &lobufspace, 0,
172         "Minimum amount of memory to reserve for system buffer space");
173 SYSCTL_INT(_vfs, OID_AUTO, bufspace, CTLFLAG_RD, &bufspace, 0,
174         "Amount of memory available for buffers");
175 SYSCTL_INT(_vfs, OID_AUTO, maxmallocbufspace, CTLFLAG_RD, &maxbufmallocspace,
176         0, "Maximum amount of memory reserved for buffers using malloc");
177 SYSCTL_INT(_vfs, OID_AUTO, bufmallocspace, CTLFLAG_RD, &bufmallocspace, 0,
178         "Amount of memory left for buffers using malloc-scheme");
179 SYSCTL_INT(_vfs, OID_AUTO, getnewbufcalls, CTLFLAG_RD, &getnewbufcalls, 0,
180         "New buffer header acquisition requests");
181 SYSCTL_INT(_vfs, OID_AUTO, getnewbufrestarts, CTLFLAG_RD, &getnewbufrestarts,
182         0, "New buffer header acquisition restarts");
183 SYSCTL_INT(_vfs, OID_AUTO, recoverbufcalls, CTLFLAG_RD, &recoverbufcalls, 0,
184         "Recover VM space in an emergency");
185 SYSCTL_INT(_vfs, OID_AUTO, bufdefragcnt, CTLFLAG_RD, &bufdefragcnt, 0,
186         "Buffer acquisition restarts due to fragmented buffer map");
187 SYSCTL_INT(_vfs, OID_AUTO, buffreekvacnt, CTLFLAG_RD, &buffreekvacnt, 0,
188         "Amount of time KVA space was deallocated in an arbitrary buffer");
189 SYSCTL_INT(_vfs, OID_AUTO, bufreusecnt, CTLFLAG_RD, &bufreusecnt, 0,
190         "Amount of time buffer re-use operations were successful");
191 SYSCTL_INT(_debug_sizeof, OID_AUTO, buf, CTLFLAG_RD, 0, sizeof(struct buf),
192         "sizeof(struct buf)");
193
194 char *buf_wmesg = BUF_WMESG;
195
196 extern int vm_swap_size;
197
198 #define VFS_BIO_NEED_ANY        0x01    /* any freeable buffer */
199 #define VFS_BIO_NEED_UNUSED02   0x02
200 #define VFS_BIO_NEED_UNUSED04   0x04
201 #define VFS_BIO_NEED_BUFSPACE   0x08    /* wait for buf space, lo hysteresis */
202
203 /*
204  * bufspacewakeup:
205  *
206  *      Called when buffer space is potentially available for recovery.
207  *      getnewbuf() will block on this flag when it is unable to free 
208  *      sufficient buffer space.  Buffer space becomes recoverable when 
209  *      bp's get placed back in the queues.
210  */
211
212 static __inline void
213 bufspacewakeup(void)
214 {
215         /*
216          * If someone is waiting for BUF space, wake them up.  Even
217          * though we haven't freed the kva space yet, the waiting
218          * process will be able to now.
219          */
220         if (needsbuffer & VFS_BIO_NEED_BUFSPACE) {
221                 spin_lock_wr(&needsbuffer_spin);
222                 needsbuffer &= ~VFS_BIO_NEED_BUFSPACE;
223                 spin_unlock_wr(&needsbuffer_spin);
224                 wakeup(&needsbuffer);
225         }
226 }
227
228 /*
229  * runningbufwakeup:
230  *
231  *      Accounting for I/O in progress.
232  *
233  */
234 static __inline void
235 runningbufwakeup(struct buf *bp)
236 {
237         int totalspace;
238
239         if ((totalspace = bp->b_runningbufspace) != 0) {
240                 runningbufspace -= totalspace;
241                 --runningbufcount;
242                 bp->b_runningbufspace = 0;
243                 if (runningbufreq && runningbufspace <= lorunningspace) {
244                         runningbufreq = 0;
245                         wakeup(&runningbufreq);
246                 }
247                 bd_signal(totalspace);
248         }
249 }
250
251 /*
252  * bufcountwakeup:
253  *
254  *      Called when a buffer has been added to one of the free queues to
255  *      account for the buffer and to wakeup anyone waiting for free buffers.
256  *      This typically occurs when large amounts of metadata are being handled
257  *      by the buffer cache ( else buffer space runs out first, usually ).
258  */
259
260 static __inline void
261 bufcountwakeup(void) 
262 {
263         if (needsbuffer) {
264                 spin_lock_wr(&needsbuffer_spin);
265                 needsbuffer &= ~VFS_BIO_NEED_ANY;
266                 spin_unlock_wr(&needsbuffer_spin);
267                 wakeup(&needsbuffer);
268         }
269 }
270
271 /*
272  * waitrunningbufspace()
273  *
274  * Wait for the amount of running I/O to drop to a reasonable level.
275  *
276  * The caller may be using this function to block in a tight loop, we
277  * must block of runningbufspace is greater then the passed limit.
278  * And even with that it may not be enough, due to the presence of
279  * B_LOCKED dirty buffers, so also wait for at least one running buffer
280  * to complete.
281  */
282 static __inline void
283 waitrunningbufspace(int limit)
284 {
285         int lorun;
286
287         if (lorunningspace < limit)
288                 lorun = lorunningspace;
289         else
290                 lorun = limit;
291
292         crit_enter();
293         if (runningbufspace > lorun) {
294                 while (runningbufspace > lorun) {
295                         ++runningbufreq;
296                         tsleep(&runningbufreq, 0, "wdrain", 0);
297                 }
298         } else if (runningbufspace) {
299                 ++runningbufreq;
300                 tsleep(&runningbufreq, 0, "wdrain2", 1);
301         }
302         crit_exit();
303 }
304
305 /*
306  * vfs_buf_test_cache:
307  *
308  *      Called when a buffer is extended.  This function clears the B_CACHE
309  *      bit if the newly extended portion of the buffer does not contain
310  *      valid data.
311  */
312 static __inline__
313 void
314 vfs_buf_test_cache(struct buf *bp,
315                   vm_ooffset_t foff, vm_offset_t off, vm_offset_t size,
316                   vm_page_t m)
317 {
318         if (bp->b_flags & B_CACHE) {
319                 int base = (foff + off) & PAGE_MASK;
320                 if (vm_page_is_valid(m, base, size) == 0)
321                         bp->b_flags &= ~B_CACHE;
322         }
323 }
324
325 /*
326  * bd_speedup()
327  *
328  * Spank the buf_daemon[_hw] if the total dirty buffer space exceeds the
329  * low water mark.
330  */
331 static __inline__
332 void
333 bd_speedup(void)
334 {
335         if (dirtybufspace < lodirtybufspace && dirtybufcount < nbuf / 2)
336                 return;
337
338         if (bd_request == 0 &&
339             (dirtybufspace - dirtybufspacehw > lodirtybufspace / 2 ||
340              dirtybufcount - dirtybufcounthw >= nbuf / 2)) {
341                 spin_lock_wr(&needsbuffer_spin);
342                 bd_request = 1;
343                 spin_unlock_wr(&needsbuffer_spin);
344                 wakeup(&bd_request);
345         }
346         if (bd_request_hw == 0 &&
347             (dirtybufspacehw > lodirtybufspace / 2 ||
348              dirtybufcounthw >= nbuf / 2)) {
349                 spin_lock_wr(&needsbuffer_spin);
350                 bd_request_hw = 1;
351                 spin_unlock_wr(&needsbuffer_spin);
352                 wakeup(&bd_request_hw);
353         }
354 }
355
356 /*
357  * bd_heatup()
358  *
359  *      Get the buf_daemon heated up when the number of running and dirty
360  *      buffers exceeds the mid-point.
361  */
362 int
363 bd_heatup(void)
364 {
365         int mid1;
366         int mid2;
367         int totalspace;
368
369         mid1 = lodirtybufspace + (hidirtybufspace - lodirtybufspace) / 2;
370
371         totalspace = runningbufspace + dirtybufspace;
372         if (totalspace >= mid1 || dirtybufcount >= nbuf / 2) {
373                 bd_speedup();
374                 mid2 = mid1 + (hidirtybufspace - mid1) / 2;
375                 if (totalspace >= mid2)
376                         return(totalspace - mid2);
377         }
378         return(0);
379 }
380
381 /*
382  * bd_wait()
383  *
384  *      Wait for the buffer cache to flush (totalspace) bytes worth of
385  *      buffers, then return.
386  *
387  *      Regardless this function blocks while the number of dirty buffers
388  *      exceeds hidirtybufspace.
389  */
390 void
391 bd_wait(int totalspace)
392 {
393         u_int i;
394         int count;
395
396         if (curthread == bufdaemonhw_td || curthread == bufdaemon_td)
397                 return;
398
399         while (totalspace > 0) {
400                 bd_heatup();
401                 crit_enter();
402                 if (totalspace > runningbufspace + dirtybufspace)
403                         totalspace = runningbufspace + dirtybufspace;
404                 count = totalspace / BKVASIZE;
405                 if (count >= BD_WAKE_SIZE)
406                         count = BD_WAKE_SIZE - 1;
407                 i = (bd_wake_index + count) & BD_WAKE_MASK;
408                 ++bd_wake_ary[i];
409                 tsleep(&bd_wake_ary[i], 0, "flstik", hz);
410                 crit_exit();
411
412                 totalspace = runningbufspace + dirtybufspace - hidirtybufspace;
413         }
414 }
415
416 /*
417  * bd_signal()
418  * 
419  *      This function is called whenever runningbufspace or dirtybufspace
420  *      is reduced.  Track threads waiting for run+dirty buffer I/O
421  *      complete.
422  */
423 static void
424 bd_signal(int totalspace)
425 {
426         u_int i;
427
428         while (totalspace > 0) {
429                 i = atomic_fetchadd_int(&bd_wake_index, 1);
430                 i &= BD_WAKE_MASK;
431                 if (bd_wake_ary[i]) {
432                         bd_wake_ary[i] = 0;
433                         wakeup(&bd_wake_ary[i]);
434                 }
435                 totalspace -= BKVASIZE;
436         }
437 }
438
439 /*
440  * BIO tracking support routines.
441  *
442  * Release a ref on a bio_track.  Wakeup requests are atomically released
443  * along with the last reference so bk_active will never wind up set to
444  * only 0x80000000.
445  *
446  * MPSAFE
447  */
448 static
449 void
450 bio_track_rel(struct bio_track *track)
451 {
452         int     active;
453         int     desired;
454
455         /*
456          * Shortcut
457          */
458         active = track->bk_active;
459         if (active == 1 && atomic_cmpset_int(&track->bk_active, 1, 0))
460                 return;
461
462         /*
463          * Full-on.  Note that the wait flag is only atomically released on
464          * the 1->0 count transition.
465          *
466          * We check for a negative count transition using bit 30 since bit 31
467          * has a different meaning.
468          */
469         for (;;) {
470                 desired = (active & 0x7FFFFFFF) - 1;
471                 if (desired)
472                         desired |= active & 0x80000000;
473                 if (atomic_cmpset_int(&track->bk_active, active, desired)) {
474                         if (desired & 0x40000000)
475                                 panic("bio_track_rel: bad count: %p\n", track);
476                         if (active & 0x80000000)
477                                 wakeup(track);
478                         break;
479                 }
480                 active = track->bk_active;
481         }
482 }
483
484 /*
485  * Wait for the tracking count to reach 0.
486  *
487  * Use atomic ops such that the wait flag is only set atomically when
488  * bk_active is non-zero.
489  *
490  * MPSAFE
491  */
492 int
493 bio_track_wait(struct bio_track *track, int slp_flags, int slp_timo)
494 {
495         int     active;
496         int     desired;
497         int     error;
498
499         /*
500          * Shortcut
501          */
502         if (track->bk_active == 0)
503                 return(0);
504
505         /*
506          * Full-on.  Note that the wait flag may only be atomically set if
507          * the active count is non-zero.
508          */
509         crit_enter();   /* for tsleep_interlock */
510         error = 0;
511         while ((active = track->bk_active) != 0) {
512                 desired = active | 0x80000000;
513                 tsleep_interlock(track);
514                 if (active == desired ||
515                     atomic_cmpset_int(&track->bk_active, active, desired)) {
516                         error = tsleep(track, slp_flags, "iowait", slp_timo);
517                         if (error)
518                                 break;
519                 }
520         }
521         crit_exit();
522         return (error);
523 }
524
525 /*
526  * bufinit:
527  *
528  *      Load time initialisation of the buffer cache, called from machine
529  *      dependant initialization code. 
530  */
531 void
532 bufinit(void)
533 {
534         struct buf *bp;
535         vm_offset_t bogus_offset;
536         int i;
537
538         spin_init(&needsbuffer_spin);
539
540         /* next, make a null set of free lists */
541         for (i = 0; i < BUFFER_QUEUES; i++)
542                 TAILQ_INIT(&bufqueues[i]);
543
544         /* finally, initialize each buffer header and stick on empty q */
545         for (i = 0; i < nbuf; i++) {
546                 bp = &buf[i];
547                 bzero(bp, sizeof *bp);
548                 bp->b_flags = B_INVAL;  /* we're just an empty header */
549                 bp->b_cmd = BUF_CMD_DONE;
550                 bp->b_qindex = BQUEUE_EMPTY;
551                 initbufbio(bp);
552                 xio_init(&bp->b_xio);
553                 buf_dep_init(bp);
554                 BUF_LOCKINIT(bp);
555                 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_EMPTY], bp, b_freelist);
556         }
557
558         /*
559          * maxbufspace is the absolute maximum amount of buffer space we are 
560          * allowed to reserve in KVM and in real terms.  The absolute maximum
561          * is nominally used by buf_daemon.  hibufspace is the nominal maximum
562          * used by most other processes.  The differential is required to 
563          * ensure that buf_daemon is able to run when other processes might 
564          * be blocked waiting for buffer space.
565          *
566          * maxbufspace is based on BKVASIZE.  Allocating buffers larger then
567          * this may result in KVM fragmentation which is not handled optimally
568          * by the system.
569          */
570         maxbufspace = nbuf * BKVASIZE;
571         hibufspace = imax(3 * maxbufspace / 4, maxbufspace - MAXBSIZE * 10);
572         lobufspace = hibufspace - MAXBSIZE;
573
574         lorunningspace = 512 * 1024;
575         hirunningspace = 1024 * 1024;
576
577         /*
578          * Limit the amount of malloc memory since it is wired permanently
579          * into the kernel space.  Even though this is accounted for in
580          * the buffer allocation, we don't want the malloced region to grow
581          * uncontrolled.  The malloc scheme improves memory utilization
582          * significantly on average (small) directories.
583          */
584         maxbufmallocspace = hibufspace / 20;
585
586         /*
587          * Reduce the chance of a deadlock occuring by limiting the number
588          * of delayed-write dirty buffers we allow to stack up.
589          */
590         hidirtybufspace = hibufspace / 2;
591         dirtybufspace = 0;
592         dirtybufspacehw = 0;
593
594         lodirtybufspace = hidirtybufspace / 2;
595
596         /*
597          * Maximum number of async ops initiated per buf_daemon loop.  This is
598          * somewhat of a hack at the moment, we really need to limit ourselves
599          * based on the number of bytes of I/O in-transit that were initiated
600          * from buf_daemon.
601          */
602
603         bogus_offset = kmem_alloc_pageable(&kernel_map, PAGE_SIZE);
604         bogus_page = vm_page_alloc(&kernel_object,
605                                    (bogus_offset >> PAGE_SHIFT),
606                                    VM_ALLOC_NORMAL);
607         vmstats.v_wire_count++;
608
609 }
610
611 /*
612  * Initialize the embedded bio structures
613  */
614 void
615 initbufbio(struct buf *bp)
616 {
617         bp->b_bio1.bio_buf = bp;
618         bp->b_bio1.bio_prev = NULL;
619         bp->b_bio1.bio_offset = NOOFFSET;
620         bp->b_bio1.bio_next = &bp->b_bio2;
621         bp->b_bio1.bio_done = NULL;
622
623         bp->b_bio2.bio_buf = bp;
624         bp->b_bio2.bio_prev = &bp->b_bio1;
625         bp->b_bio2.bio_offset = NOOFFSET;
626         bp->b_bio2.bio_next = NULL;
627         bp->b_bio2.bio_done = NULL;
628 }
629
630 /*
631  * Reinitialize the embedded bio structures as well as any additional
632  * translation cache layers.
633  */
634 void
635 reinitbufbio(struct buf *bp)
636 {
637         struct bio *bio;
638
639         for (bio = &bp->b_bio1; bio; bio = bio->bio_next) {
640                 bio->bio_done = NULL;
641                 bio->bio_offset = NOOFFSET;
642         }
643 }
644
645 /*
646  * Push another BIO layer onto an existing BIO and return it.  The new
647  * BIO layer may already exist, holding cached translation data.
648  */
649 struct bio *
650 push_bio(struct bio *bio)
651 {
652         struct bio *nbio;
653
654         if ((nbio = bio->bio_next) == NULL) {
655                 int index = bio - &bio->bio_buf->b_bio_array[0];
656                 if (index >= NBUF_BIO - 1) {
657                         panic("push_bio: too many layers bp %p\n",
658                                 bio->bio_buf);
659                 }
660                 nbio = &bio->bio_buf->b_bio_array[index + 1];
661                 bio->bio_next = nbio;
662                 nbio->bio_prev = bio;
663                 nbio->bio_buf = bio->bio_buf;
664                 nbio->bio_offset = NOOFFSET;
665                 nbio->bio_done = NULL;
666                 nbio->bio_next = NULL;
667         }
668         KKASSERT(nbio->bio_done == NULL);
669         return(nbio);
670 }
671
672 /*
673  * Pop a BIO translation layer, returning the previous layer.  The
674  * must have been previously pushed.
675  */
676 struct bio *
677 pop_bio(struct bio *bio)
678 {
679         return(bio->bio_prev);
680 }
681
682 void
683 clearbiocache(struct bio *bio)
684 {
685         while (bio) {
686                 bio->bio_offset = NOOFFSET;
687                 bio = bio->bio_next;
688         }
689 }
690
691 /*
692  * bfreekva:
693  *
694  *      Free the KVA allocation for buffer 'bp'.
695  *
696  *      Must be called from a critical section as this is the only locking for
697  *      buffer_map.
698  *
699  *      Since this call frees up buffer space, we call bufspacewakeup().
700  */
701 static void
702 bfreekva(struct buf *bp)
703 {
704         int count;
705
706         if (bp->b_kvasize) {
707                 ++buffreekvacnt;
708                 count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
709                 vm_map_lock(&buffer_map);
710                 bufspace -= bp->b_kvasize;
711                 vm_map_delete(&buffer_map,
712                     (vm_offset_t) bp->b_kvabase,
713                     (vm_offset_t) bp->b_kvabase + bp->b_kvasize,
714                     &count
715                 );
716                 vm_map_unlock(&buffer_map);
717                 vm_map_entry_release(count);
718                 bp->b_kvasize = 0;
719                 bufspacewakeup();
720         }
721 }
722
723 /*
724  * bremfree:
725  *
726  *      Remove the buffer from the appropriate free list.
727  */
728 void
729 bremfree(struct buf *bp)
730 {
731         crit_enter();
732
733         if (bp->b_qindex != BQUEUE_NONE) {
734                 KASSERT(BUF_REFCNTNB(bp) == 1, 
735                                 ("bremfree: bp %p not locked",bp));
736                 TAILQ_REMOVE(&bufqueues[bp->b_qindex], bp, b_freelist);
737                 bp->b_qindex = BQUEUE_NONE;
738         } else {
739                 if (BUF_REFCNTNB(bp) <= 1)
740                         panic("bremfree: removing a buffer not on a queue");
741         }
742
743         crit_exit();
744 }
745
746
747 /*
748  * bread:
749  *
750  *      Get a buffer with the specified data.  Look in the cache first.  We
751  *      must clear B_ERROR and B_INVAL prior to initiating I/O.  If B_CACHE
752  *      is set, the buffer is valid and we do not have to do anything ( see
753  *      getblk() ).
754  */
755 int
756 bread(struct vnode *vp, off_t loffset, int size, struct buf **bpp)
757 {
758         struct buf *bp;
759
760         bp = getblk(vp, loffset, size, 0, 0);
761         *bpp = bp;
762
763         /* if not found in cache, do some I/O */
764         if ((bp->b_flags & B_CACHE) == 0) {
765                 KASSERT(!(bp->b_flags & B_ASYNC),
766                         ("bread: illegal async bp %p", bp));
767                 bp->b_flags &= ~(B_ERROR | B_INVAL);
768                 bp->b_cmd = BUF_CMD_READ;
769                 vfs_busy_pages(vp, bp);
770                 vn_strategy(vp, &bp->b_bio1);
771                 return (biowait(bp));
772         }
773         return (0);
774 }
775
776 /*
777  * breadn:
778  *
779  *      Operates like bread, but also starts asynchronous I/O on
780  *      read-ahead blocks.  We must clear B_ERROR and B_INVAL prior
781  *      to initiating I/O . If B_CACHE is set, the buffer is valid 
782  *      and we do not have to do anything.
783  */
784 int
785 breadn(struct vnode *vp, off_t loffset, int size, off_t *raoffset,
786         int *rabsize, int cnt, struct buf **bpp)
787 {
788         struct buf *bp, *rabp;
789         int i;
790         int rv = 0, readwait = 0;
791
792         *bpp = bp = getblk(vp, loffset, size, 0, 0);
793
794         /* if not found in cache, do some I/O */
795         if ((bp->b_flags & B_CACHE) == 0) {
796                 bp->b_flags &= ~(B_ERROR | B_INVAL);
797                 bp->b_cmd = BUF_CMD_READ;
798                 vfs_busy_pages(vp, bp);
799                 vn_strategy(vp, &bp->b_bio1);
800                 ++readwait;
801         }
802
803         for (i = 0; i < cnt; i++, raoffset++, rabsize++) {
804                 if (inmem(vp, *raoffset))
805                         continue;
806                 rabp = getblk(vp, *raoffset, *rabsize, 0, 0);
807
808                 if ((rabp->b_flags & B_CACHE) == 0) {
809                         rabp->b_flags |= B_ASYNC;
810                         rabp->b_flags &= ~(B_ERROR | B_INVAL);
811                         rabp->b_cmd = BUF_CMD_READ;
812                         vfs_busy_pages(vp, rabp);
813                         BUF_KERNPROC(rabp);
814                         vn_strategy(vp, &rabp->b_bio1);
815                 } else {
816                         brelse(rabp);
817                 }
818         }
819
820         if (readwait) {
821                 rv = biowait(bp);
822         }
823         return (rv);
824 }
825
826 /*
827  * bwrite:
828  *
829  *      Write, release buffer on completion.  (Done by iodone
830  *      if async).  Do not bother writing anything if the buffer
831  *      is invalid.
832  *
833  *      Note that we set B_CACHE here, indicating that buffer is
834  *      fully valid and thus cacheable.  This is true even of NFS
835  *      now so we set it generally.  This could be set either here 
836  *      or in biodone() since the I/O is synchronous.  We put it
837  *      here.
838  */
839 int
840 bwrite(struct buf *bp)
841 {
842         int oldflags;
843
844         if (bp->b_flags & B_INVAL) {
845                 brelse(bp);
846                 return (0);
847         }
848
849         oldflags = bp->b_flags;
850
851         if (BUF_REFCNTNB(bp) == 0)
852                 panic("bwrite: buffer is not busy???");
853         crit_enter();
854
855         /* Mark the buffer clean */
856         bundirty(bp);
857
858         bp->b_flags &= ~B_ERROR;
859         bp->b_flags |= B_CACHE;
860         bp->b_cmd = BUF_CMD_WRITE;
861         vfs_busy_pages(bp->b_vp, bp);
862
863         /*
864          * Normal bwrites pipeline writes.  NOTE: b_bufsize is only
865          * valid for vnode-backed buffers.
866          */
867         bp->b_runningbufspace = bp->b_bufsize;
868         if (bp->b_runningbufspace) {
869                 runningbufspace += bp->b_runningbufspace;
870                 ++runningbufcount;
871         }
872
873         crit_exit();
874         if (oldflags & B_ASYNC)
875                 BUF_KERNPROC(bp);
876         vn_strategy(bp->b_vp, &bp->b_bio1);
877
878         if ((oldflags & B_ASYNC) == 0) {
879                 int rtval = biowait(bp);
880                 brelse(bp);
881                 return (rtval);
882         }
883         return (0);
884 }
885
886 /*
887  * bdwrite:
888  *
889  *      Delayed write. (Buffer is marked dirty).  Do not bother writing
890  *      anything if the buffer is marked invalid.
891  *
892  *      Note that since the buffer must be completely valid, we can safely
893  *      set B_CACHE.  In fact, we have to set B_CACHE here rather then in
894  *      biodone() in order to prevent getblk from writing the buffer
895  *      out synchronously.
896  */
897 void
898 bdwrite(struct buf *bp)
899 {
900         if (BUF_REFCNTNB(bp) == 0)
901                 panic("bdwrite: buffer is not busy");
902
903         if (bp->b_flags & B_INVAL) {
904                 brelse(bp);
905                 return;
906         }
907         bdirty(bp);
908
909         /*
910          * Set B_CACHE, indicating that the buffer is fully valid.  This is
911          * true even of NFS now.
912          */
913         bp->b_flags |= B_CACHE;
914
915         /*
916          * This bmap keeps the system from needing to do the bmap later,
917          * perhaps when the system is attempting to do a sync.  Since it
918          * is likely that the indirect block -- or whatever other datastructure
919          * that the filesystem needs is still in memory now, it is a good
920          * thing to do this.  Note also, that if the pageout daemon is
921          * requesting a sync -- there might not be enough memory to do
922          * the bmap then...  So, this is important to do.
923          */
924         if (bp->b_bio2.bio_offset == NOOFFSET) {
925                 VOP_BMAP(bp->b_vp, bp->b_loffset, &bp->b_bio2.bio_offset,
926                          NULL, NULL, BUF_CMD_WRITE);
927         }
928
929         /*
930          * Set the *dirty* buffer range based upon the VM system dirty pages.
931          */
932         vfs_setdirty(bp);
933
934         /*
935          * We need to do this here to satisfy the vnode_pager and the
936          * pageout daemon, so that it thinks that the pages have been
937          * "cleaned".  Note that since the pages are in a delayed write
938          * buffer -- the VFS layer "will" see that the pages get written
939          * out on the next sync, or perhaps the cluster will be completed.
940          */
941         vfs_clean_pages(bp);
942         bqrelse(bp);
943
944         /*
945          * note: we cannot initiate I/O from a bdwrite even if we wanted to,
946          * due to the softdep code.
947          */
948 }
949
950 /*
951  * bdirty:
952  *
953  *      Turn buffer into delayed write request by marking it B_DELWRI.
954  *      B_RELBUF and B_NOCACHE must be cleared.
955  *
956  *      We reassign the buffer to itself to properly update it in the
957  *      dirty/clean lists. 
958  *
959  *      Must be called from a critical section.
960  *      The buffer must be on BQUEUE_NONE.
961  */
962 void
963 bdirty(struct buf *bp)
964 {
965         KASSERT(bp->b_qindex == BQUEUE_NONE, ("bdirty: buffer %p still on queue %d", bp, bp->b_qindex));
966         if (bp->b_flags & B_NOCACHE) {
967                 kprintf("bdirty: clearing B_NOCACHE on buf %p\n", bp);
968                 bp->b_flags &= ~B_NOCACHE;
969         }
970         if (bp->b_flags & B_INVAL) {
971                 kprintf("bdirty: warning, dirtying invalid buffer %p\n", bp);
972         }
973         bp->b_flags &= ~B_RELBUF;
974
975         if ((bp->b_flags & B_DELWRI) == 0) {
976                 bp->b_flags |= B_DELWRI;
977                 reassignbuf(bp);
978                 ++dirtybufcount;
979                 dirtybufspace += bp->b_bufsize;
980                 if (bp->b_flags & B_HEAVY) {
981                         ++dirtybufcounthw;
982                         dirtybufspacehw += bp->b_bufsize;
983                 }
984                 bd_heatup();
985         }
986 }
987
988 /*
989  * Set B_HEAVY, indicating that this is a heavy-weight buffer that
990  * needs to be flushed with a different buf_daemon thread to avoid
991  * deadlocks.  B_HEAVY also imposes restrictions in getnewbuf().
992  */
993 void
994 bheavy(struct buf *bp)
995 {
996         if ((bp->b_flags & B_HEAVY) == 0) {
997                 bp->b_flags |= B_HEAVY;
998                 if (bp->b_flags & B_DELWRI) {
999                         ++dirtybufcounthw;
1000                         dirtybufspacehw += bp->b_bufsize;
1001                 }
1002         }
1003 }
1004
1005 /*
1006  * bundirty:
1007  *
1008  *      Clear B_DELWRI for buffer.
1009  *
1010  *      Must be called from a critical section.
1011  *
1012  *      The buffer is typically on BQUEUE_NONE but there is one case in 
1013  *      brelse() that calls this function after placing the buffer on
1014  *      a different queue.
1015  */
1016
1017 void
1018 bundirty(struct buf *bp)
1019 {
1020         if (bp->b_flags & B_DELWRI) {
1021                 bp->b_flags &= ~B_DELWRI;
1022                 reassignbuf(bp);
1023                 --dirtybufcount;
1024                 dirtybufspace -= bp->b_bufsize;
1025                 if (bp->b_flags & B_HEAVY) {
1026                         --dirtybufcounthw;
1027                         dirtybufspacehw -= bp->b_bufsize;
1028                 }
1029                 bd_signal(bp->b_bufsize);
1030         }
1031         /*
1032          * Since it is now being written, we can clear its deferred write flag.
1033          */
1034         bp->b_flags &= ~B_DEFERRED;
1035 }
1036
1037 /*
1038  * bawrite:
1039  *
1040  *      Asynchronous write.  Start output on a buffer, but do not wait for
1041  *      it to complete.  The buffer is released when the output completes.
1042  *
1043  *      bwrite() ( or the VOP routine anyway ) is responsible for handling 
1044  *      B_INVAL buffers.  Not us.
1045  */
1046 void
1047 bawrite(struct buf *bp)
1048 {
1049         bp->b_flags |= B_ASYNC;
1050         bwrite(bp);
1051 }
1052
1053 /*
1054  * bowrite:
1055  *
1056  *      Ordered write.  Start output on a buffer, and flag it so that the 
1057  *      device will write it in the order it was queued.  The buffer is 
1058  *      released when the output completes.  bwrite() ( or the VOP routine
1059  *      anyway ) is responsible for handling B_INVAL buffers.
1060  */
1061 int
1062 bowrite(struct buf *bp)
1063 {
1064         bp->b_flags |= B_ORDERED | B_ASYNC;
1065         return (bwrite(bp));
1066 }
1067
1068 /*
1069  * buf_dirty_count_severe:
1070  *
1071  *      Return true if we have too many dirty buffers.
1072  */
1073 int
1074 buf_dirty_count_severe(void)
1075 {
1076         return (runningbufspace + dirtybufspace >= hidirtybufspace ||
1077                 dirtybufcount >= nbuf / 2);
1078 }
1079
1080 /*
1081  * brelse:
1082  *
1083  *      Release a busy buffer and, if requested, free its resources.  The
1084  *      buffer will be stashed in the appropriate bufqueue[] allowing it
1085  *      to be accessed later as a cache entity or reused for other purposes.
1086  */
1087 void
1088 brelse(struct buf *bp)
1089 {
1090 #ifdef INVARIANTS
1091         int saved_flags = bp->b_flags;
1092 #endif
1093
1094         KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("brelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1095
1096         crit_enter();
1097
1098         /*
1099          * If B_NOCACHE is set we are being asked to destroy the buffer and
1100          * its backing store.  Clear B_DELWRI.
1101          *
1102          * B_NOCACHE is set in two cases: (1) when the caller really wants
1103          * to destroy the buffer and backing store and (2) when the caller
1104          * wants to destroy the buffer and backing store after a write 
1105          * completes.
1106          */
1107         if ((bp->b_flags & (B_NOCACHE|B_DELWRI)) == (B_NOCACHE|B_DELWRI)) {
1108                 bundirty(bp);
1109         }
1110
1111         if ((bp->b_flags & (B_INVAL | B_DELWRI)) == B_DELWRI) {
1112                 /*
1113                  * A re-dirtied buffer is only subject to destruction
1114                  * by B_INVAL.  B_ERROR and B_NOCACHE are ignored.
1115                  */
1116                 /* leave buffer intact */
1117         } else if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR)) ||
1118                    (bp->b_bufsize <= 0)) {
1119                 /*
1120                  * Either a failed read or we were asked to free or not
1121                  * cache the buffer.  This path is reached with B_DELWRI
1122                  * set only if B_INVAL is already set.  B_NOCACHE governs
1123                  * backing store destruction.
1124                  *
1125                  * NOTE: HAMMER will set B_LOCKED in buf_deallocate if the
1126                  * buffer cannot be immediately freed.
1127                  */
1128                 bp->b_flags |= B_INVAL;
1129                 if (LIST_FIRST(&bp->b_dep) != NULL)
1130                         buf_deallocate(bp);
1131                 if (bp->b_flags & B_DELWRI) {
1132                         --dirtybufcount;
1133                         dirtybufspace -= bp->b_bufsize;
1134                         if (bp->b_flags & B_HEAVY) {
1135                                 --dirtybufcounthw;
1136                                 dirtybufspacehw -= bp->b_bufsize;
1137                         }
1138                         bd_signal(bp->b_bufsize);
1139                 }
1140                 bp->b_flags &= ~(B_DELWRI | B_CACHE);
1141         }
1142
1143         /*
1144          * We must clear B_RELBUF if B_DELWRI or B_LOCKED is set.
1145          * If vfs_vmio_release() is called with either bit set, the
1146          * underlying pages may wind up getting freed causing a previous
1147          * write (bdwrite()) to get 'lost' because pages associated with
1148          * a B_DELWRI bp are marked clean.  Pages associated with a
1149          * B_LOCKED buffer may be mapped by the filesystem.
1150          *
1151          * If we want to release the buffer ourselves (rather then the
1152          * originator asking us to release it), give the originator a
1153          * chance to countermand the release by setting B_LOCKED.
1154          * 
1155          * We still allow the B_INVAL case to call vfs_vmio_release(), even
1156          * if B_DELWRI is set.
1157          *
1158          * If B_DELWRI is not set we may have to set B_RELBUF if we are low
1159          * on pages to return pages to the VM page queues.
1160          */
1161         if (bp->b_flags & (B_DELWRI | B_LOCKED)) {
1162                 bp->b_flags &= ~B_RELBUF;
1163         } else if (vm_page_count_severe()) {
1164                 if (LIST_FIRST(&bp->b_dep) != NULL)
1165                         buf_deallocate(bp);             /* can set B_LOCKED */
1166                 if (bp->b_flags & (B_DELWRI | B_LOCKED))
1167                         bp->b_flags &= ~B_RELBUF;
1168                 else
1169                         bp->b_flags |= B_RELBUF;
1170         }
1171
1172         /*
1173          * Make sure b_cmd is clear.  It may have already been cleared by
1174          * biodone().
1175          *
1176          * At this point destroying the buffer is governed by the B_INVAL 
1177          * or B_RELBUF flags.
1178          */
1179         bp->b_cmd = BUF_CMD_DONE;
1180
1181         /*
1182          * VMIO buffer rundown.  Make sure the VM page array is restored
1183          * after an I/O may have replaces some of the pages with bogus pages
1184          * in order to not destroy dirty pages in a fill-in read.
1185          *
1186          * Note that due to the code above, if a buffer is marked B_DELWRI
1187          * then the B_RELBUF and B_NOCACHE bits will always be clear.
1188          * B_INVAL may still be set, however.
1189          *
1190          * For clean buffers, B_INVAL or B_RELBUF will destroy the buffer
1191          * but not the backing store.   B_NOCACHE will destroy the backing
1192          * store.
1193          *
1194          * Note that dirty NFS buffers contain byte-granular write ranges
1195          * and should not be destroyed w/ B_INVAL even if the backing store
1196          * is left intact.
1197          */
1198         if (bp->b_flags & B_VMIO) {
1199                 /*
1200                  * Rundown for VMIO buffers which are not dirty NFS buffers.
1201                  */
1202                 int i, j, resid;
1203                 vm_page_t m;
1204                 off_t foff;
1205                 vm_pindex_t poff;
1206                 vm_object_t obj;
1207                 struct vnode *vp;
1208
1209                 vp = bp->b_vp;
1210
1211                 /*
1212                  * Get the base offset and length of the buffer.  Note that 
1213                  * in the VMIO case if the buffer block size is not
1214                  * page-aligned then b_data pointer may not be page-aligned.
1215                  * But our b_xio.xio_pages array *IS* page aligned.
1216                  *
1217                  * block sizes less then DEV_BSIZE (usually 512) are not 
1218                  * supported due to the page granularity bits (m->valid,
1219                  * m->dirty, etc...). 
1220                  *
1221                  * See man buf(9) for more information
1222                  */
1223
1224                 resid = bp->b_bufsize;
1225                 foff = bp->b_loffset;
1226
1227                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
1228                         m = bp->b_xio.xio_pages[i];
1229                         vm_page_flag_clear(m, PG_ZERO);
1230                         /*
1231                          * If we hit a bogus page, fixup *all* of them
1232                          * now.  Note that we left these pages wired
1233                          * when we removed them so they had better exist,
1234                          * and they cannot be ripped out from under us so
1235                          * no critical section protection is necessary.
1236                          */
1237                         if (m == bogus_page) {
1238                                 obj = vp->v_object;
1239                                 poff = OFF_TO_IDX(bp->b_loffset);
1240
1241                                 for (j = i; j < bp->b_xio.xio_npages; j++) {
1242                                         vm_page_t mtmp;
1243
1244                                         mtmp = bp->b_xio.xio_pages[j];
1245                                         if (mtmp == bogus_page) {
1246                                                 mtmp = vm_page_lookup(obj, poff + j);
1247                                                 if (!mtmp) {
1248                                                         panic("brelse: page missing");
1249                                                 }
1250                                                 bp->b_xio.xio_pages[j] = mtmp;
1251                                         }
1252                                 }
1253
1254                                 if ((bp->b_flags & B_INVAL) == 0) {
1255                                         pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
1256                                                 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
1257                                 }
1258                                 m = bp->b_xio.xio_pages[i];
1259                         }
1260
1261                         /*
1262                          * Invalidate the backing store if B_NOCACHE is set
1263                          * (e.g. used with vinvalbuf()).  If this is NFS
1264                          * we impose a requirement that the block size be
1265                          * a multiple of PAGE_SIZE and create a temporary
1266                          * hack to basically invalidate the whole page.  The
1267                          * problem is that NFS uses really odd buffer sizes
1268                          * especially when tracking piecemeal writes and
1269                          * it also vinvalbuf()'s a lot, which would result
1270                          * in only partial page validation and invalidation
1271                          * here.  If the file page is mmap()'d, however,
1272                          * all the valid bits get set so after we invalidate
1273                          * here we would end up with weird m->valid values
1274                          * like 0xfc.  nfs_getpages() can't handle this so
1275                          * we clear all the valid bits for the NFS case
1276                          * instead of just some of them.
1277                          *
1278                          * The real bug is the VM system having to set m->valid
1279                          * to VM_PAGE_BITS_ALL for faulted-in pages, which
1280                          * itself is an artifact of the whole 512-byte
1281                          * granular mess that exists to support odd block 
1282                          * sizes and UFS meta-data block sizes (e.g. 6144).
1283                          * A complete rewrite is required.
1284                          */
1285                         if (bp->b_flags & (B_NOCACHE|B_ERROR)) {
1286                                 int poffset = foff & PAGE_MASK;
1287                                 int presid;
1288
1289                                 presid = PAGE_SIZE - poffset;
1290                                 if (bp->b_vp->v_tag == VT_NFS &&
1291                                     bp->b_vp->v_type == VREG) {
1292                                         ; /* entire page */
1293                                 } else if (presid > resid) {
1294                                         presid = resid;
1295                                 }
1296                                 KASSERT(presid >= 0, ("brelse: extra page"));
1297                                 vm_page_set_invalid(m, poffset, presid);
1298                         }
1299                         resid -= PAGE_SIZE - (foff & PAGE_MASK);
1300                         foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
1301                 }
1302                 if (bp->b_flags & (B_INVAL | B_RELBUF))
1303                         vfs_vmio_release(bp);
1304         } else {
1305                 /*
1306                  * Rundown for non-VMIO buffers.
1307                  */
1308                 if (bp->b_flags & (B_INVAL | B_RELBUF)) {
1309 #if 0
1310                         if (bp->b_vp)
1311                                 kprintf("brelse bp %p %08x/%08x: Warning, caught and fixed brelvp bug\n", bp, saved_flags, bp->b_flags);
1312 #endif
1313                         if (bp->b_bufsize)
1314                                 allocbuf(bp, 0);
1315                         KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1316                         if (bp->b_vp)
1317                                 brelvp(bp);
1318                 }
1319         }
1320                         
1321         if (bp->b_qindex != BQUEUE_NONE)
1322                 panic("brelse: free buffer onto another queue???");
1323         if (BUF_REFCNTNB(bp) > 1) {
1324                 /* Temporary panic to verify exclusive locking */
1325                 /* This panic goes away when we allow shared refs */
1326                 panic("brelse: multiple refs");
1327                 /* do not release to free list */
1328                 BUF_UNLOCK(bp);
1329                 crit_exit();
1330                 return;
1331         }
1332
1333         /*
1334          * Figure out the correct queue to place the cleaned up buffer on.
1335          * Buffers placed in the EMPTY or EMPTYKVA had better already be
1336          * disassociated from their vnode.
1337          */
1338         if (bp->b_flags & B_LOCKED) {
1339                 /*
1340                  * Buffers that are locked are placed in the locked queue
1341                  * immediately, regardless of their state.
1342                  */
1343                 bp->b_qindex = BQUEUE_LOCKED;
1344                 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1345         } else if (bp->b_bufsize == 0) {
1346                 /*
1347                  * Buffers with no memory.  Due to conditionals near the top
1348                  * of brelse() such buffers should probably already be
1349                  * marked B_INVAL and disassociated from their vnode.
1350                  */
1351                 bp->b_flags |= B_INVAL;
1352                 KASSERT(bp->b_vp == NULL, ("bp1 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1353                 KKASSERT((bp->b_flags & B_HASHED) == 0);
1354                 if (bp->b_kvasize) {
1355                         bp->b_qindex = BQUEUE_EMPTYKVA;
1356                 } else {
1357                         bp->b_qindex = BQUEUE_EMPTY;
1358                 }
1359                 TAILQ_INSERT_HEAD(&bufqueues[bp->b_qindex], bp, b_freelist);
1360         } else if (bp->b_flags & (B_INVAL | B_NOCACHE | B_RELBUF)) {
1361                 /*
1362                  * Buffers with junk contents.   Again these buffers had better
1363                  * already be disassociated from their vnode.
1364                  */
1365                 KASSERT(bp->b_vp == NULL, ("bp2 %p flags %08x/%08x vnode %p unexpectededly still associated!", bp, saved_flags, bp->b_flags, bp->b_vp));
1366                 KKASSERT((bp->b_flags & B_HASHED) == 0);
1367                 bp->b_flags |= B_INVAL;
1368                 bp->b_qindex = BQUEUE_CLEAN;
1369                 TAILQ_INSERT_HEAD(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1370         } else {
1371                 /*
1372                  * Remaining buffers.  These buffers are still associated with
1373                  * their vnode.
1374                  */
1375                 switch(bp->b_flags & (B_DELWRI|B_HEAVY)) {
1376                 case B_DELWRI:
1377                     bp->b_qindex = BQUEUE_DIRTY;
1378                     TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY], bp, b_freelist);
1379                     break;
1380                 case B_DELWRI | B_HEAVY:
1381                     bp->b_qindex = BQUEUE_DIRTY_HW;
1382                     TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_DIRTY_HW], bp,
1383                                       b_freelist);
1384                     break;
1385                 default:
1386                     /*
1387                      * NOTE: Buffers are always placed at the end of the
1388                      * queue.  If B_AGE is not set the buffer will cycle
1389                      * through the queue twice.
1390                      */
1391                     bp->b_qindex = BQUEUE_CLEAN;
1392                     TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1393                     break;
1394                 }
1395         }
1396
1397         /*
1398          * If B_INVAL, clear B_DELWRI.  We've already placed the buffer
1399          * on the correct queue.
1400          */
1401         if ((bp->b_flags & (B_INVAL|B_DELWRI)) == (B_INVAL|B_DELWRI))
1402                 bundirty(bp);
1403
1404         /*
1405          * The bp is on an appropriate queue unless locked.  If it is not
1406          * locked or dirty we can wakeup threads waiting for buffer space.
1407          *
1408          * We've already handled the B_INVAL case ( B_DELWRI will be clear
1409          * if B_INVAL is set ).
1410          */
1411         if ((bp->b_flags & (B_LOCKED|B_DELWRI)) == 0)
1412                 bufcountwakeup();
1413
1414         /*
1415          * Something we can maybe free or reuse
1416          */
1417         if (bp->b_bufsize || bp->b_kvasize)
1418                 bufspacewakeup();
1419
1420         /*
1421          * Clean up temporary flags and unlock the buffer.
1422          */
1423         bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_RELBUF | B_DIRECT);
1424         BUF_UNLOCK(bp);
1425         crit_exit();
1426 }
1427
1428 /*
1429  * bqrelse:
1430  *
1431  *      Release a buffer back to the appropriate queue but do not try to free
1432  *      it.  The buffer is expected to be used again soon.
1433  *
1434  *      bqrelse() is used by bdwrite() to requeue a delayed write, and used by
1435  *      biodone() to requeue an async I/O on completion.  It is also used when
1436  *      known good buffers need to be requeued but we think we may need the data
1437  *      again soon.
1438  *
1439  *      XXX we should be able to leave the B_RELBUF hint set on completion.
1440  */
1441 void
1442 bqrelse(struct buf *bp)
1443 {
1444         crit_enter();
1445
1446         KASSERT(!(bp->b_flags & (B_CLUSTER|B_PAGING)), ("bqrelse: inappropriate B_PAGING or B_CLUSTER bp %p", bp));
1447
1448         if (bp->b_qindex != BQUEUE_NONE)
1449                 panic("bqrelse: free buffer onto another queue???");
1450         if (BUF_REFCNTNB(bp) > 1) {
1451                 /* do not release to free list */
1452                 panic("bqrelse: multiple refs");
1453                 BUF_UNLOCK(bp);
1454                 crit_exit();
1455                 return;
1456         }
1457         if (bp->b_flags & B_LOCKED) {
1458                 /*
1459                  * Locked buffers are released to the locked queue.  However,
1460                  * if the buffer is dirty it will first go into the dirty
1461                  * queue and later on after the I/O completes successfully it
1462                  * will be released to the locked queue.
1463                  */
1464                 bp->b_qindex = BQUEUE_LOCKED;
1465                 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_LOCKED], bp, b_freelist);
1466         } else if (bp->b_flags & B_DELWRI) {
1467                 bp->b_qindex = (bp->b_flags & B_HEAVY) ?
1468                                BQUEUE_DIRTY_HW : BQUEUE_DIRTY;
1469                 TAILQ_INSERT_TAIL(&bufqueues[bp->b_qindex], bp, b_freelist);
1470         } else if (vm_page_count_severe()) {
1471                 /*
1472                  * We are too low on memory, we have to try to free the
1473                  * buffer (most importantly: the wired pages making up its
1474                  * backing store) *now*.
1475                  */
1476                 crit_exit();
1477                 brelse(bp);
1478                 return;
1479         } else {
1480                 bp->b_qindex = BQUEUE_CLEAN;
1481                 TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
1482         }
1483
1484         if ((bp->b_flags & B_LOCKED) == 0 &&
1485             ((bp->b_flags & B_INVAL) || (bp->b_flags & B_DELWRI) == 0)) {
1486                 bufcountwakeup();
1487         }
1488
1489         /*
1490          * Something we can maybe free or reuse.
1491          */
1492         if (bp->b_bufsize && !(bp->b_flags & B_DELWRI))
1493                 bufspacewakeup();
1494
1495         /*
1496          * Final cleanup and unlock.  Clear bits that are only used while a
1497          * buffer is actively locked.
1498          */
1499         bp->b_flags &= ~(B_ORDERED | B_ASYNC | B_NOCACHE | B_RELBUF);
1500         BUF_UNLOCK(bp);
1501         crit_exit();
1502 }
1503
1504 /*
1505  * vfs_vmio_release:
1506  *
1507  *      Return backing pages held by the buffer 'bp' back to the VM system
1508  *      if possible.  The pages are freed if they are no longer valid or
1509  *      attempt to free if it was used for direct I/O otherwise they are
1510  *      sent to the page cache.
1511  *
1512  *      Pages that were marked busy are left alone and skipped.
1513  *
1514  *      The KVA mapping (b_data) for the underlying pages is removed by
1515  *      this function.
1516  */
1517 static void
1518 vfs_vmio_release(struct buf *bp)
1519 {
1520         int i;
1521         vm_page_t m;
1522
1523         crit_enter();
1524         for (i = 0; i < bp->b_xio.xio_npages; i++) {
1525                 m = bp->b_xio.xio_pages[i];
1526                 bp->b_xio.xio_pages[i] = NULL;
1527                 /*
1528                  * In order to keep page LRU ordering consistent, put
1529                  * everything on the inactive queue.
1530                  */
1531                 vm_page_unwire(m, 0);
1532                 /*
1533                  * We don't mess with busy pages, it is
1534                  * the responsibility of the process that
1535                  * busied the pages to deal with them.
1536                  */
1537                 if ((m->flags & PG_BUSY) || (m->busy != 0))
1538                         continue;
1539                         
1540                 if (m->wire_count == 0) {
1541                         vm_page_flag_clear(m, PG_ZERO);
1542                         /*
1543                          * Might as well free the page if we can and it has
1544                          * no valid data.  We also free the page if the
1545                          * buffer was used for direct I/O.
1546                          */
1547                         if ((bp->b_flags & B_ASYNC) == 0 && !m->valid &&
1548                                         m->hold_count == 0) {
1549                                 vm_page_busy(m);
1550                                 vm_page_protect(m, VM_PROT_NONE);
1551                                 vm_page_free(m);
1552                         } else if (bp->b_flags & B_DIRECT) {
1553                                 vm_page_try_to_free(m);
1554                         } else if (vm_page_count_severe()) {
1555                                 vm_page_try_to_cache(m);
1556                         }
1557                 }
1558         }
1559         crit_exit();
1560         pmap_qremove(trunc_page((vm_offset_t) bp->b_data), bp->b_xio.xio_npages);
1561         if (bp->b_bufsize) {
1562                 bufspacewakeup();
1563                 bp->b_bufsize = 0;
1564         }
1565         bp->b_xio.xio_npages = 0;
1566         bp->b_flags &= ~B_VMIO;
1567         KKASSERT (LIST_FIRST(&bp->b_dep) == NULL);
1568         if (bp->b_vp)
1569                 brelvp(bp);
1570 }
1571
1572 /*
1573  * vfs_bio_awrite:
1574  *
1575  *      Implement clustered async writes for clearing out B_DELWRI buffers.
1576  *      This is much better then the old way of writing only one buffer at
1577  *      a time.  Note that we may not be presented with the buffers in the 
1578  *      correct order, so we search for the cluster in both directions.
1579  *
1580  *      The buffer is locked on call.
1581  */
1582 int
1583 vfs_bio_awrite(struct buf *bp)
1584 {
1585         int i;
1586         int j;
1587         off_t loffset = bp->b_loffset;
1588         struct vnode *vp = bp->b_vp;
1589         int nbytes;
1590         struct buf *bpa;
1591         int nwritten;
1592         int size;
1593
1594         crit_enter();
1595         /*
1596          * right now we support clustered writing only to regular files.  If
1597          * we find a clusterable block we could be in the middle of a cluster
1598          * rather then at the beginning.
1599          *
1600          * NOTE: b_bio1 contains the logical loffset and is aliased
1601          * to b_loffset.  b_bio2 contains the translated block number.
1602          */
1603         if ((vp->v_type == VREG) && 
1604             (vp->v_mount != 0) && /* Only on nodes that have the size info */
1605             (bp->b_flags & (B_CLUSTEROK | B_INVAL)) == B_CLUSTEROK) {
1606
1607                 size = vp->v_mount->mnt_stat.f_iosize;
1608
1609                 for (i = size; i < MAXPHYS; i += size) {
1610                         if ((bpa = findblk(vp, loffset + i)) &&
1611                             BUF_REFCNT(bpa) == 0 &&
1612                             ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1613                             (B_DELWRI | B_CLUSTEROK)) &&
1614                             (bpa->b_bufsize == size)) {
1615                                 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1616                                     (bpa->b_bio2.bio_offset !=
1617                                      bp->b_bio2.bio_offset + i))
1618                                         break;
1619                         } else {
1620                                 break;
1621                         }
1622                 }
1623                 for (j = size; i + j <= MAXPHYS && j <= loffset; j += size) {
1624                         if ((bpa = findblk(vp, loffset - j)) &&
1625                             BUF_REFCNT(bpa) == 0 &&
1626                             ((bpa->b_flags & (B_DELWRI | B_CLUSTEROK | B_INVAL)) ==
1627                             (B_DELWRI | B_CLUSTEROK)) &&
1628                             (bpa->b_bufsize == size)) {
1629                                 if ((bpa->b_bio2.bio_offset == NOOFFSET) ||
1630                                     (bpa->b_bio2.bio_offset !=
1631                                      bp->b_bio2.bio_offset - j))
1632                                         break;
1633                         } else {
1634                                 break;
1635                         }
1636                 }
1637                 j -= size;
1638                 nbytes = (i + j);
1639                 /*
1640                  * this is a possible cluster write
1641                  */
1642                 if (nbytes != size) {
1643                         BUF_UNLOCK(bp);
1644                         nwritten = cluster_wbuild(vp, size,
1645                                                   loffset - j, nbytes);
1646                         crit_exit();
1647                         return nwritten;
1648                 }
1649         }
1650
1651         bremfree(bp);
1652         bp->b_flags |= B_ASYNC;
1653
1654         crit_exit();
1655         /*
1656          * default (old) behavior, writing out only one block
1657          *
1658          * XXX returns b_bufsize instead of b_bcount for nwritten?
1659          */
1660         nwritten = bp->b_bufsize;
1661         bwrite(bp);
1662
1663         return nwritten;
1664 }
1665
1666 /*
1667  * getnewbuf:
1668  *
1669  *      Find and initialize a new buffer header, freeing up existing buffers 
1670  *      in the bufqueues as necessary.  The new buffer is returned locked.
1671  *
1672  *      Important:  B_INVAL is not set.  If the caller wishes to throw the
1673  *      buffer away, the caller must set B_INVAL prior to calling brelse().
1674  *
1675  *      We block if:
1676  *              We have insufficient buffer headers
1677  *              We have insufficient buffer space
1678  *              buffer_map is too fragmented ( space reservation fails )
1679  *              If we have to flush dirty buffers ( but we try to avoid this )
1680  *
1681  *      To avoid VFS layer recursion we do not flush dirty buffers ourselves.
1682  *      Instead we ask the buf daemon to do it for us.  We attempt to
1683  *      avoid piecemeal wakeups of the pageout daemon.
1684  */
1685
1686 static struct buf *
1687 getnewbuf(int blkflags, int slptimeo, int size, int maxsize)
1688 {
1689         struct buf *bp;
1690         struct buf *nbp;
1691         int defrag = 0;
1692         int nqindex;
1693         int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
1694         static int flushingbufs;
1695
1696         /*
1697          * We can't afford to block since we might be holding a vnode lock,
1698          * which may prevent system daemons from running.  We deal with
1699          * low-memory situations by proactively returning memory and running
1700          * async I/O rather then sync I/O.
1701          */
1702         
1703         ++getnewbufcalls;
1704         --getnewbufrestarts;
1705 restart:
1706         ++getnewbufrestarts;
1707
1708         /*
1709          * Setup for scan.  If we do not have enough free buffers,
1710          * we setup a degenerate case that immediately fails.  Note
1711          * that if we are specially marked process, we are allowed to
1712          * dip into our reserves.
1713          *
1714          * The scanning sequence is nominally:  EMPTY->EMPTYKVA->CLEAN
1715          *
1716          * We start with EMPTYKVA.  If the list is empty we backup to EMPTY.
1717          * However, there are a number of cases (defragging, reusing, ...)
1718          * where we cannot backup.
1719          */
1720         nqindex = BQUEUE_EMPTYKVA;
1721         nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA]);
1722
1723         if (nbp == NULL) {
1724                 /*
1725                  * If no EMPTYKVA buffers and we are either
1726                  * defragging or reusing, locate a CLEAN buffer
1727                  * to free or reuse.  If bufspace useage is low
1728                  * skip this step so we can allocate a new buffer.
1729                  */
1730                 if (defrag || bufspace >= lobufspace) {
1731                         nqindex = BQUEUE_CLEAN;
1732                         nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
1733                 }
1734
1735                 /*
1736                  * If we could not find or were not allowed to reuse a
1737                  * CLEAN buffer, check to see if it is ok to use an EMPTY
1738                  * buffer.  We can only use an EMPTY buffer if allocating
1739                  * its KVA would not otherwise run us out of buffer space.
1740                  */
1741                 if (nbp == NULL && defrag == 0 &&
1742                     bufspace + maxsize < hibufspace) {
1743                         nqindex = BQUEUE_EMPTY;
1744                         nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTY]);
1745                 }
1746         }
1747
1748         /*
1749          * Run scan, possibly freeing data and/or kva mappings on the fly
1750          * depending.
1751          */
1752
1753         while ((bp = nbp) != NULL) {
1754                 int qindex = nqindex;
1755
1756                 nbp = TAILQ_NEXT(bp, b_freelist);
1757
1758                 /*
1759                  * BQUEUE_CLEAN - B_AGE special case.  If not set the bp
1760                  * cycles through the queue twice before being selected.
1761                  */
1762                 if (qindex == BQUEUE_CLEAN && 
1763                     (bp->b_flags & B_AGE) == 0 && nbp) {
1764                         bp->b_flags |= B_AGE;
1765                         TAILQ_REMOVE(&bufqueues[qindex], bp, b_freelist);
1766                         TAILQ_INSERT_TAIL(&bufqueues[qindex], bp, b_freelist);
1767                         continue;
1768                 }
1769
1770                 /*
1771                  * Calculate next bp ( we can only use it if we do not block
1772                  * or do other fancy things ).
1773                  */
1774                 if (nbp == NULL) {
1775                         switch(qindex) {
1776                         case BQUEUE_EMPTY:
1777                                 nqindex = BQUEUE_EMPTYKVA;
1778                                 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_EMPTYKVA])))
1779                                         break;
1780                                 /* fall through */
1781                         case BQUEUE_EMPTYKVA:
1782                                 nqindex = BQUEUE_CLEAN;
1783                                 if ((nbp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN])))
1784                                         break;
1785                                 /* fall through */
1786                         case BQUEUE_CLEAN:
1787                                 /*
1788                                  * nbp is NULL. 
1789                                  */
1790                                 break;
1791                         }
1792                 }
1793
1794                 /*
1795                  * Sanity Checks
1796                  */
1797                 KASSERT(bp->b_qindex == qindex, ("getnewbuf: inconsistent queue %d bp %p", qindex, bp));
1798
1799                 /*
1800                  * Note: we no longer distinguish between VMIO and non-VMIO
1801                  * buffers.
1802                  */
1803
1804                 KASSERT((bp->b_flags & B_DELWRI) == 0, ("delwri buffer %p found in queue %d", bp, qindex));
1805
1806                 /*
1807                  * If we are defragging then we need a buffer with 
1808                  * b_kvasize != 0.  XXX this situation should no longer
1809                  * occur, if defrag is non-zero the buffer's b_kvasize
1810                  * should also be non-zero at this point.  XXX
1811                  */
1812                 if (defrag && bp->b_kvasize == 0) {
1813                         kprintf("Warning: defrag empty buffer %p\n", bp);
1814                         continue;
1815                 }
1816
1817                 /*
1818                  * Start freeing the bp.  This is somewhat involved.  nbp
1819                  * remains valid only for BQUEUE_EMPTY[KVA] bp's.  Buffers
1820                  * on the clean list must be disassociated from their 
1821                  * current vnode.  Buffers on the empty[kva] lists have
1822                  * already been disassociated.
1823                  */
1824
1825                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
1826                         kprintf("getnewbuf: warning, locked buf %p, race corrected\n", bp);
1827                         tsleep(&bd_request, 0, "gnbxxx", hz / 100);
1828                         goto restart;
1829                 }
1830                 if (bp->b_qindex != qindex) {
1831                         kprintf("getnewbuf: warning, BUF_LOCK blocked unexpectedly on buf %p index %d->%d, race corrected\n", bp, qindex, bp->b_qindex);
1832                         BUF_UNLOCK(bp);
1833                         goto restart;
1834                 }
1835                 bremfree(bp);
1836
1837                 /*
1838                  * Dependancies must be handled before we disassociate the
1839                  * vnode.
1840                  *
1841                  * NOTE: HAMMER will set B_LOCKED if the buffer cannot
1842                  * be immediately disassociated.  HAMMER then becomes
1843                  * responsible for releasing the buffer.
1844                  */
1845                 if (LIST_FIRST(&bp->b_dep) != NULL) {
1846                         buf_deallocate(bp);
1847                         if (bp->b_flags & B_LOCKED) {
1848                                 bqrelse(bp);
1849                                 goto restart;
1850                         }
1851                         KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
1852                 }
1853
1854                 if (qindex == BQUEUE_CLEAN) {
1855                         if (bp->b_flags & B_VMIO) {
1856                                 bp->b_flags &= ~B_ASYNC;
1857                                 vfs_vmio_release(bp);
1858                         }
1859                         if (bp->b_vp)
1860                                 brelvp(bp);
1861                 }
1862
1863                 /*
1864                  * NOTE:  nbp is now entirely invalid.  We can only restart
1865                  * the scan from this point on.
1866                  *
1867                  * Get the rest of the buffer freed up.  b_kva* is still
1868                  * valid after this operation.
1869                  */
1870
1871                 KASSERT(bp->b_vp == NULL, ("bp3 %p flags %08x vnode %p qindex %d unexpectededly still associated!", bp, bp->b_flags, bp->b_vp, qindex));
1872                 KKASSERT((bp->b_flags & B_HASHED) == 0);
1873
1874                 /*
1875                  * critical section protection is not required when
1876                  * scrapping a buffer's contents because it is already 
1877                  * wired.
1878                  */
1879                 if (bp->b_bufsize)
1880                         allocbuf(bp, 0);
1881
1882                 bp->b_flags = B_BNOCLIP;
1883                 bp->b_cmd = BUF_CMD_DONE;
1884                 bp->b_vp = NULL;
1885                 bp->b_error = 0;
1886                 bp->b_resid = 0;
1887                 bp->b_bcount = 0;
1888                 bp->b_xio.xio_npages = 0;
1889                 bp->b_dirtyoff = bp->b_dirtyend = 0;
1890                 reinitbufbio(bp);
1891                 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
1892                 buf_dep_init(bp);
1893                 if (blkflags & GETBLK_BHEAVY)
1894                         bp->b_flags |= B_HEAVY;
1895
1896                 /*
1897                  * If we are defragging then free the buffer.
1898                  */
1899                 if (defrag) {
1900                         bp->b_flags |= B_INVAL;
1901                         bfreekva(bp);
1902                         brelse(bp);
1903                         defrag = 0;
1904                         goto restart;
1905                 }
1906
1907                 /*
1908                  * If we are overcomitted then recover the buffer and its
1909                  * KVM space.  This occurs in rare situations when multiple
1910                  * processes are blocked in getnewbuf() or allocbuf().
1911                  */
1912                 if (bufspace >= hibufspace)
1913                         flushingbufs = 1;
1914                 if (flushingbufs && bp->b_kvasize != 0) {
1915                         bp->b_flags |= B_INVAL;
1916                         bfreekva(bp);
1917                         brelse(bp);
1918                         goto restart;
1919                 }
1920                 if (bufspace < lobufspace)
1921                         flushingbufs = 0;
1922                 break;
1923         }
1924
1925         /*
1926          * If we exhausted our list, sleep as appropriate.  We may have to
1927          * wakeup various daemons and write out some dirty buffers.
1928          *
1929          * Generally we are sleeping due to insufficient buffer space.
1930          */
1931
1932         if (bp == NULL) {
1933                 int flags;
1934                 char *waitmsg;
1935
1936                 if (defrag) {
1937                         flags = VFS_BIO_NEED_BUFSPACE;
1938                         waitmsg = "nbufkv";
1939                 } else if (bufspace >= hibufspace) {
1940                         waitmsg = "nbufbs";
1941                         flags = VFS_BIO_NEED_BUFSPACE;
1942                 } else {
1943                         waitmsg = "newbuf";
1944                         flags = VFS_BIO_NEED_ANY;
1945                 }
1946
1947                 needsbuffer |= flags;
1948                 bd_speedup();   /* heeeelp */
1949                 while (needsbuffer & flags) {
1950                         if (tsleep(&needsbuffer, slpflags, waitmsg, slptimeo))
1951                                 return (NULL);
1952                 }
1953         } else {
1954                 /*
1955                  * We finally have a valid bp.  We aren't quite out of the
1956                  * woods, we still have to reserve kva space.  In order
1957                  * to keep fragmentation sane we only allocate kva in
1958                  * BKVASIZE chunks.
1959                  */
1960                 maxsize = (maxsize + BKVAMASK) & ~BKVAMASK;
1961
1962                 if (maxsize != bp->b_kvasize) {
1963                         vm_offset_t addr = 0;
1964                         int count;
1965
1966                         bfreekva(bp);
1967
1968                         count = vm_map_entry_reserve(MAP_RESERVE_COUNT);
1969                         vm_map_lock(&buffer_map);
1970
1971                         if (vm_map_findspace(&buffer_map,
1972                                     vm_map_min(&buffer_map), maxsize,
1973                                     maxsize, 0, &addr)) {
1974                                 /*
1975                                  * Uh oh.  Buffer map is too fragmented.  We
1976                                  * must defragment the map.
1977                                  */
1978                                 vm_map_unlock(&buffer_map);
1979                                 vm_map_entry_release(count);
1980                                 ++bufdefragcnt;
1981                                 defrag = 1;
1982                                 bp->b_flags |= B_INVAL;
1983                                 brelse(bp);
1984                                 goto restart;
1985                         }
1986                         if (addr) {
1987                                 vm_map_insert(&buffer_map, &count,
1988                                         NULL, 0,
1989                                         addr, addr + maxsize,
1990                                         VM_MAPTYPE_NORMAL,
1991                                         VM_PROT_ALL, VM_PROT_ALL,
1992                                         MAP_NOFAULT);
1993
1994                                 bp->b_kvabase = (caddr_t) addr;
1995                                 bp->b_kvasize = maxsize;
1996                                 bufspace += bp->b_kvasize;
1997                                 ++bufreusecnt;
1998                         }
1999                         vm_map_unlock(&buffer_map);
2000                         vm_map_entry_release(count);
2001                 }
2002                 bp->b_data = bp->b_kvabase;
2003         }
2004         return(bp);
2005 }
2006
2007 /*
2008  * This routine is called in an emergency to recover VM pages from the
2009  * buffer cache by cashing in clean buffers.  The idea is to recover
2010  * enough pages to be able to satisfy a stuck bio_page_alloc().
2011  */
2012 static int
2013 recoverbufpages(void)
2014 {
2015         struct buf *bp;
2016         int bytes = 0;
2017
2018         ++recoverbufcalls;
2019
2020         while (bytes < MAXBSIZE) {
2021                 bp = TAILQ_FIRST(&bufqueues[BQUEUE_CLEAN]);
2022                 if (bp == NULL)
2023                         break;
2024
2025                 /*
2026                  * BQUEUE_CLEAN - B_AGE special case.  If not set the bp
2027                  * cycles through the queue twice before being selected.
2028                  */
2029                 if ((bp->b_flags & B_AGE) == 0 && TAILQ_NEXT(bp, b_freelist)) {
2030                         bp->b_flags |= B_AGE;
2031                         TAILQ_REMOVE(&bufqueues[BQUEUE_CLEAN], bp, b_freelist);
2032                         TAILQ_INSERT_TAIL(&bufqueues[BQUEUE_CLEAN],
2033                                           bp, b_freelist);
2034                         continue;
2035                 }
2036
2037                 /*
2038                  * Sanity Checks
2039                  */
2040                 KKASSERT(bp->b_qindex == BQUEUE_CLEAN);
2041                 KKASSERT((bp->b_flags & B_DELWRI) == 0);
2042
2043                 /*
2044                  * Start freeing the bp.  This is somewhat involved.
2045                  *
2046                  * Buffers on the clean list must be disassociated from
2047                  * their current vnode
2048                  */
2049
2050                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
2051                         kprintf("recoverbufpages: warning, locked buf %p, race corrected\n", bp);
2052                         tsleep(&bd_request, 0, "gnbxxx", hz / 100);
2053                         continue;
2054                 }
2055                 if (bp->b_qindex != BQUEUE_CLEAN) {
2056                         kprintf("recoverbufpages: warning, BUF_LOCK blocked unexpectedly on buf %p index %d, race corrected\n", bp, bp->b_qindex);
2057                         BUF_UNLOCK(bp);
2058                         continue;
2059                 }
2060                 bremfree(bp);
2061
2062                 /*
2063                  * Dependancies must be handled before we disassociate the
2064                  * vnode.
2065                  *
2066                  * NOTE: HAMMER will set B_LOCKED if the buffer cannot
2067                  * be immediately disassociated.  HAMMER then becomes
2068                  * responsible for releasing the buffer.
2069                  */
2070                 if (LIST_FIRST(&bp->b_dep) != NULL) {
2071                         buf_deallocate(bp);
2072                         if (bp->b_flags & B_LOCKED) {
2073                                 bqrelse(bp);
2074                                 continue;
2075                         }
2076                         KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2077                 }
2078
2079                 bytes += bp->b_bufsize;
2080
2081                 if (bp->b_flags & B_VMIO) {
2082                         bp->b_flags &= ~B_ASYNC;
2083                         bp->b_flags |= B_DIRECT;    /* try to free pages */
2084                         vfs_vmio_release(bp);
2085                 }
2086                 if (bp->b_vp)
2087                         brelvp(bp);
2088
2089                 KKASSERT(bp->b_vp == NULL);
2090                 KKASSERT((bp->b_flags & B_HASHED) == 0);
2091
2092                 /*
2093                  * critical section protection is not required when
2094                  * scrapping a buffer's contents because it is already 
2095                  * wired.
2096                  */
2097                 if (bp->b_bufsize)
2098                         allocbuf(bp, 0);
2099
2100                 bp->b_flags = B_BNOCLIP;
2101                 bp->b_cmd = BUF_CMD_DONE;
2102                 bp->b_vp = NULL;
2103                 bp->b_error = 0;
2104                 bp->b_resid = 0;
2105                 bp->b_bcount = 0;
2106                 bp->b_xio.xio_npages = 0;
2107                 bp->b_dirtyoff = bp->b_dirtyend = 0;
2108                 reinitbufbio(bp);
2109                 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
2110                 buf_dep_init(bp);
2111                 bp->b_flags |= B_INVAL;
2112                 /* bfreekva(bp); */
2113                 brelse(bp);
2114         }
2115         return(bytes);
2116 }
2117
2118 /*
2119  * buf_daemon:
2120  *
2121  *      Buffer flushing daemon.  Buffers are normally flushed by the
2122  *      update daemon but if it cannot keep up this process starts to
2123  *      take the load in an attempt to prevent getnewbuf() from blocking.
2124  *
2125  *      Once a flush is initiated it does not stop until the number
2126  *      of buffers falls below lodirtybuffers, but we will wake up anyone
2127  *      waiting at the mid-point.
2128  */
2129
2130 static struct kproc_desc buf_kp = {
2131         "bufdaemon",
2132         buf_daemon,
2133         &bufdaemon_td
2134 };
2135 SYSINIT(bufdaemon, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2136         kproc_start, &buf_kp)
2137
2138 static struct kproc_desc bufhw_kp = {
2139         "bufdaemon_hw",
2140         buf_daemon_hw,
2141         &bufdaemonhw_td
2142 };
2143 SYSINIT(bufdaemon_hw, SI_SUB_KTHREAD_BUF, SI_ORDER_FIRST,
2144         kproc_start, &bufhw_kp)
2145
2146 static void
2147 buf_daemon(void)
2148 {
2149         int limit;
2150
2151         /*
2152          * This process needs to be suspended prior to shutdown sync.
2153          */
2154         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2155                               bufdaemon_td, SHUTDOWN_PRI_LAST);
2156         curthread->td_flags |= TDF_SYSTHREAD;
2157
2158         /*
2159          * This process is allowed to take the buffer cache to the limit
2160          */
2161         crit_enter();
2162
2163         for (;;) {
2164                 kproc_suspend_loop();
2165
2166                 /*
2167                  * Do the flush.  Limit the amount of in-transit I/O we
2168                  * allow to build up, otherwise we would completely saturate
2169                  * the I/O system.  Wakeup any waiting processes before we
2170                  * normally would so they can run in parallel with our drain.
2171                  *
2172                  * Our aggregate normal+HW lo water mark is lodirtybufspace,
2173                  * but because we split the operation into two threads we
2174                  * have to cut it in half for each thread.
2175                  */
2176                 limit = lodirtybufspace / 2;
2177                 waitrunningbufspace(limit);
2178                 while (runningbufspace + dirtybufspace > limit ||
2179                        dirtybufcount - dirtybufcounthw >= nbuf / 2) {
2180                         if (flushbufqueues(BQUEUE_DIRTY) == 0)
2181                                 break;
2182                         waitrunningbufspace(limit);
2183                 }
2184
2185                 /*
2186                  * We reached our low water mark, reset the
2187                  * request and sleep until we are needed again.
2188                  * The sleep is just so the suspend code works.
2189                  */
2190                 spin_lock_wr(&needsbuffer_spin);
2191                 if (bd_request == 0) {
2192                         msleep(&bd_request, &needsbuffer_spin, 0,
2193                                "psleep", hz);
2194                 }
2195                 bd_request = 0;
2196                 spin_unlock_wr(&needsbuffer_spin);
2197         }
2198 }
2199
2200 static void
2201 buf_daemon_hw(void)
2202 {
2203         int limit;
2204
2205         /*
2206          * This process needs to be suspended prior to shutdown sync.
2207          */
2208         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc,
2209                               bufdaemonhw_td, SHUTDOWN_PRI_LAST);
2210         curthread->td_flags |= TDF_SYSTHREAD;
2211
2212         /*
2213          * This process is allowed to take the buffer cache to the limit
2214          */
2215         crit_enter();
2216
2217         for (;;) {
2218                 kproc_suspend_loop();
2219
2220                 /*
2221                  * Do the flush.  Limit the amount of in-transit I/O we
2222                  * allow to build up, otherwise we would completely saturate
2223                  * the I/O system.  Wakeup any waiting processes before we
2224                  * normally would so they can run in parallel with our drain.
2225                  *
2226                  * Our aggregate normal+HW lo water mark is lodirtybufspace,
2227                  * but because we split the operation into two threads we
2228                  * have to cut it in half for each thread.
2229                  */
2230                 limit = lodirtybufspace / 2;
2231                 waitrunningbufspace(limit);
2232                 while (runningbufspace + dirtybufspacehw > limit ||
2233                        dirtybufcounthw >= nbuf / 2) {
2234                         if (flushbufqueues(BQUEUE_DIRTY_HW) == 0)
2235                                 break;
2236                         waitrunningbufspace(limit);
2237                 }
2238
2239                 /*
2240                  * We reached our low water mark, reset the
2241                  * request and sleep until we are needed again.
2242                  * The sleep is just so the suspend code works.
2243                  */
2244                 spin_lock_wr(&needsbuffer_spin);
2245                 if (bd_request_hw == 0) {
2246                         msleep(&bd_request_hw, &needsbuffer_spin, 0,
2247                                "psleep", hz);
2248                 }
2249                 bd_request_hw = 0;
2250                 spin_unlock_wr(&needsbuffer_spin);
2251         }
2252 }
2253
2254 /*
2255  * flushbufqueues:
2256  *
2257  *      Try to flush a buffer in the dirty queue.  We must be careful to
2258  *      free up B_INVAL buffers instead of write them, which NFS is 
2259  *      particularly sensitive to.
2260  *
2261  *      B_RELBUF may only be set by VFSs.  We do set B_AGE to indicate
2262  *      that we really want to try to get the buffer out and reuse it
2263  *      due to the write load on the machine.
2264  */
2265
2266 static int
2267 flushbufqueues(bufq_type_t q)
2268 {
2269         struct buf *bp;
2270         int r = 0;
2271
2272         bp = TAILQ_FIRST(&bufqueues[q]);
2273         while (bp) {
2274                 KASSERT((bp->b_flags & B_DELWRI),
2275                         ("unexpected clean buffer %p", bp));
2276
2277                 if (bp->b_flags & B_DELWRI) {
2278                         if (bp->b_flags & B_INVAL) {
2279                                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
2280                                         panic("flushbufqueues: locked buf");
2281                                 bremfree(bp);
2282                                 brelse(bp);
2283                                 ++r;
2284                                 break;
2285                         }
2286                         if (LIST_FIRST(&bp->b_dep) != NULL &&
2287                             (bp->b_flags & B_DEFERRED) == 0 &&
2288                             buf_countdeps(bp, 0)) {
2289                                 TAILQ_REMOVE(&bufqueues[q], bp, b_freelist);
2290                                 TAILQ_INSERT_TAIL(&bufqueues[q], bp,
2291                                                   b_freelist);
2292                                 bp->b_flags |= B_DEFERRED;
2293                                 bp = TAILQ_FIRST(&bufqueues[q]);
2294                                 continue;
2295                         }
2296
2297                         /*
2298                          * Only write it out if we can successfully lock
2299                          * it.  If the buffer has a dependancy,
2300                          * buf_checkwrite must also return 0 for us to
2301                          * be able to initate the write.
2302                          *
2303                          * If the buffer is flagged B_ERROR it may be
2304                          * requeued over and over again, we try to
2305                          * avoid a live lock.
2306                          */
2307                         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
2308                                 if (LIST_FIRST(&bp->b_dep) != NULL &&
2309                                     buf_checkwrite(bp)) {
2310                                         bremfree(bp);
2311                                         brelse(bp);
2312                                 } else if (bp->b_flags & B_ERROR) {
2313                                         tsleep(bp, 0, "bioer", 1);
2314                                         bp->b_flags &= ~B_AGE;
2315                                         vfs_bio_awrite(bp);
2316                                 } else {
2317                                         bp->b_flags |= B_AGE;
2318                                         vfs_bio_awrite(bp);
2319                                 }
2320                                 ++r;
2321                                 break;
2322                         }
2323                 }
2324                 bp = TAILQ_NEXT(bp, b_freelist);
2325         }
2326         return (r);
2327 }
2328
2329 /*
2330  * inmem:
2331  *
2332  *      Returns true if no I/O is needed to access the associated VM object.
2333  *      This is like findblk except it also hunts around in the VM system for
2334  *      the data.
2335  *
2336  *      Note that we ignore vm_page_free() races from interrupts against our
2337  *      lookup, since if the caller is not protected our return value will not
2338  *      be any more valid then otherwise once we exit the critical section.
2339  */
2340 int
2341 inmem(struct vnode *vp, off_t loffset)
2342 {
2343         vm_object_t obj;
2344         vm_offset_t toff, tinc, size;
2345         vm_page_t m;
2346
2347         if (findblk(vp, loffset))
2348                 return 1;
2349         if (vp->v_mount == NULL)
2350                 return 0;
2351         if ((obj = vp->v_object) == NULL)
2352                 return 0;
2353
2354         size = PAGE_SIZE;
2355         if (size > vp->v_mount->mnt_stat.f_iosize)
2356                 size = vp->v_mount->mnt_stat.f_iosize;
2357
2358         for (toff = 0; toff < vp->v_mount->mnt_stat.f_iosize; toff += tinc) {
2359                 m = vm_page_lookup(obj, OFF_TO_IDX(loffset + toff));
2360                 if (m == NULL)
2361                         return 0;
2362                 tinc = size;
2363                 if (tinc > PAGE_SIZE - ((toff + loffset) & PAGE_MASK))
2364                         tinc = PAGE_SIZE - ((toff + loffset) & PAGE_MASK);
2365                 if (vm_page_is_valid(m,
2366                     (vm_offset_t) ((toff + loffset) & PAGE_MASK), tinc) == 0)
2367                         return 0;
2368         }
2369         return 1;
2370 }
2371
2372 /*
2373  * vfs_setdirty:
2374  *
2375  *      Sets the dirty range for a buffer based on the status of the dirty
2376  *      bits in the pages comprising the buffer.
2377  *
2378  *      The range is limited to the size of the buffer.
2379  *
2380  *      This routine is primarily used by NFS, but is generalized for the
2381  *      B_VMIO case.
2382  */
2383 static void
2384 vfs_setdirty(struct buf *bp) 
2385 {
2386         int i;
2387         vm_object_t object;
2388
2389         /*
2390          * Degenerate case - empty buffer
2391          */
2392
2393         if (bp->b_bufsize == 0)
2394                 return;
2395
2396         /*
2397          * We qualify the scan for modified pages on whether the
2398          * object has been flushed yet.  The OBJ_WRITEABLE flag
2399          * is not cleared simply by protecting pages off.
2400          */
2401
2402         if ((bp->b_flags & B_VMIO) == 0)
2403                 return;
2404
2405         object = bp->b_xio.xio_pages[0]->object;
2406
2407         if ((object->flags & OBJ_WRITEABLE) && !(object->flags & OBJ_MIGHTBEDIRTY))
2408                 kprintf("Warning: object %p writeable but not mightbedirty\n", object);
2409         if (!(object->flags & OBJ_WRITEABLE) && (object->flags & OBJ_MIGHTBEDIRTY))
2410                 kprintf("Warning: object %p mightbedirty but not writeable\n", object);
2411
2412         if (object->flags & (OBJ_MIGHTBEDIRTY|OBJ_CLEANING)) {
2413                 vm_offset_t boffset;
2414                 vm_offset_t eoffset;
2415
2416                 /*
2417                  * test the pages to see if they have been modified directly
2418                  * by users through the VM system.
2419                  */
2420                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2421                         vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
2422                         vm_page_test_dirty(bp->b_xio.xio_pages[i]);
2423                 }
2424
2425                 /*
2426                  * Calculate the encompassing dirty range, boffset and eoffset,
2427                  * (eoffset - boffset) bytes.
2428                  */
2429
2430                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
2431                         if (bp->b_xio.xio_pages[i]->dirty)
2432                                 break;
2433                 }
2434                 boffset = (i << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2435
2436                 for (i = bp->b_xio.xio_npages - 1; i >= 0; --i) {
2437                         if (bp->b_xio.xio_pages[i]->dirty) {
2438                                 break;
2439                         }
2440                 }
2441                 eoffset = ((i + 1) << PAGE_SHIFT) - (bp->b_loffset & PAGE_MASK);
2442
2443                 /*
2444                  * Fit it to the buffer.
2445                  */
2446
2447                 if (eoffset > bp->b_bcount)
2448                         eoffset = bp->b_bcount;
2449
2450                 /*
2451                  * If we have a good dirty range, merge with the existing
2452                  * dirty range.
2453                  */
2454
2455                 if (boffset < eoffset) {
2456                         if (bp->b_dirtyoff > boffset)
2457                                 bp->b_dirtyoff = boffset;
2458                         if (bp->b_dirtyend < eoffset)
2459                                 bp->b_dirtyend = eoffset;
2460                 }
2461         }
2462 }
2463
2464 /*
2465  * findblk:
2466  *
2467  *      Locate and return the specified buffer, or NULL if the buffer does
2468  *      not exist.  Do not attempt to lock the buffer or manipulate it in
2469  *      any way.  The caller must validate that the correct buffer has been
2470  *      obtain after locking it.
2471  *
2472  *
2473  */
2474 struct buf *
2475 findblk(struct vnode *vp, off_t loffset)
2476 {
2477         lwkt_tokref vlock;
2478         struct buf *bp;
2479
2480         lwkt_gettoken(&vlock, &vp->v_token);
2481 /*      ASSERT_LWKT_TOKEN_HELD(&vp->v_token);*/
2482         bp = buf_rb_hash_RB_LOOKUP(&vp->v_rbhash_tree, loffset);
2483         lwkt_reltoken(&vlock);
2484         return(bp);
2485 }
2486
2487 /*
2488  * getblk:
2489  *
2490  *      Get a block given a specified block and offset into a file/device.
2491  *      B_INVAL may or may not be set on return.  The caller should clear
2492  *      B_INVAL prior to initiating a READ.
2493  *
2494  *      IT IS IMPORTANT TO UNDERSTAND THAT IF YOU CALL GETBLK() AND B_CACHE
2495  *      IS NOT SET, YOU MUST INITIALIZE THE RETURNED BUFFER, ISSUE A READ,
2496  *      OR SET B_INVAL BEFORE RETIRING IT.  If you retire a getblk'd buffer
2497  *      without doing any of those things the system will likely believe
2498  *      the buffer to be valid (especially if it is not B_VMIO), and the
2499  *      next getblk() will return the buffer with B_CACHE set.
2500  *
2501  *      For a non-VMIO buffer, B_CACHE is set to the opposite of B_INVAL for
2502  *      an existing buffer.
2503  *
2504  *      For a VMIO buffer, B_CACHE is modified according to the backing VM.
2505  *      If getblk()ing a previously 0-sized invalid buffer, B_CACHE is set
2506  *      and then cleared based on the backing VM.  If the previous buffer is
2507  *      non-0-sized but invalid, B_CACHE will be cleared.
2508  *
2509  *      If getblk() must create a new buffer, the new buffer is returned with
2510  *      both B_INVAL and B_CACHE clear unless it is a VMIO buffer, in which
2511  *      case it is returned with B_INVAL clear and B_CACHE set based on the
2512  *      backing VM.
2513  *
2514  *      getblk() also forces a bwrite() for any B_DELWRI buffer whos
2515  *      B_CACHE bit is clear.
2516  *      
2517  *      What this means, basically, is that the caller should use B_CACHE to
2518  *      determine whether the buffer is fully valid or not and should clear
2519  *      B_INVAL prior to issuing a read.  If the caller intends to validate
2520  *      the buffer by loading its data area with something, the caller needs
2521  *      to clear B_INVAL.  If the caller does this without issuing an I/O, 
2522  *      the caller should set B_CACHE ( as an optimization ), else the caller
2523  *      should issue the I/O and biodone() will set B_CACHE if the I/O was
2524  *      a write attempt or if it was a successfull read.  If the caller 
2525  *      intends to issue a READ, the caller must clear B_INVAL and B_ERROR
2526  *      prior to issuing the READ.  biodone() will *not* clear B_INVAL.
2527  *
2528  *      getblk flags:
2529  *
2530  *      GETBLK_PCATCH - catch signal if blocked, can cause NULL return
2531  *      GETBLK_BHEAVY - heavy-weight buffer cache buffer
2532  */
2533 struct buf *
2534 getblk(struct vnode *vp, off_t loffset, int size, int blkflags, int slptimeo)
2535 {
2536         struct buf *bp;
2537         int slpflags = (blkflags & GETBLK_PCATCH) ? PCATCH : 0;
2538         int error;
2539
2540         if (size > MAXBSIZE)
2541                 panic("getblk: size(%d) > MAXBSIZE(%d)", size, MAXBSIZE);
2542         if (vp->v_object == NULL)
2543                 panic("getblk: vnode %p has no object!", vp);
2544
2545         crit_enter();
2546 loop:
2547         if ((bp = findblk(vp, loffset))) {
2548                 /*
2549                  * The buffer was found in the cache, but we need to lock it.
2550                  * Even with LK_NOWAIT the lockmgr may break our critical
2551                  * section, so double-check the validity of the buffer
2552                  * once the lock has been obtained.
2553                  */
2554                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
2555                         if (blkflags & GETBLK_NOWAIT) {
2556                                 crit_exit();
2557                                 return(NULL);
2558                         }
2559                         int lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
2560                         if (blkflags & GETBLK_PCATCH)
2561                                 lkflags |= LK_PCATCH;
2562                         error = BUF_TIMELOCK(bp, lkflags, "getblk", slptimeo);
2563                         if (error) {
2564                                 if (error == ENOLCK)
2565                                         goto loop;
2566                                 crit_exit();
2567                                 return (NULL);
2568                         }
2569                 }
2570
2571                 /*
2572                  * Once the buffer has been locked, make sure we didn't race
2573                  * a buffer recyclement.  Buffers that are no longer hashed
2574                  * will have b_vp == NULL, so this takes care of that check
2575                  * as well.
2576                  */
2577                 if (bp->b_vp != vp || bp->b_loffset != loffset) {
2578                         kprintf("Warning buffer %p (vp %p loffset %lld) "
2579                                 "was recycled\n",
2580                                 bp, vp, (long long)loffset);
2581                         BUF_UNLOCK(bp);
2582                         goto loop;
2583                 }
2584
2585                 /*
2586                  * If SZMATCH any pre-existing buffer must be of the requested
2587                  * size or NULL is returned.  The caller absolutely does not
2588                  * want getblk() to bwrite() the buffer on a size mismatch.
2589                  */
2590                 if ((blkflags & GETBLK_SZMATCH) && size != bp->b_bcount) {
2591                         BUF_UNLOCK(bp);
2592                         crit_exit();
2593                         return(NULL);
2594                 }
2595
2596                 /*
2597                  * All vnode-based buffers must be backed by a VM object.
2598                  */
2599                 KKASSERT(bp->b_flags & B_VMIO);
2600                 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2601                 bp->b_flags &= ~B_AGE;
2602
2603                 /*
2604                  * Make sure that B_INVAL buffers do not have a cached
2605                  * block number translation.
2606                  */
2607                 if ((bp->b_flags & B_INVAL) && (bp->b_bio2.bio_offset != NOOFFSET)) {
2608                         kprintf("Warning invalid buffer %p (vp %p loffset %lld)"
2609                                 " did not have cleared bio_offset cache\n",
2610                                 bp, vp, (long long)loffset);
2611                         clearbiocache(&bp->b_bio2);
2612                 }
2613
2614                 /*
2615                  * The buffer is locked.  B_CACHE is cleared if the buffer is 
2616                  * invalid.
2617                  */
2618                 if (bp->b_flags & B_INVAL)
2619                         bp->b_flags &= ~B_CACHE;
2620                 bremfree(bp);
2621
2622                 /*
2623                  * Any size inconsistancy with a dirty buffer or a buffer
2624                  * with a softupdates dependancy must be resolved.  Resizing
2625                  * the buffer in such circumstances can lead to problems.
2626                  */
2627                 if (size != bp->b_bcount) {
2628                         if (bp->b_flags & B_DELWRI) {
2629                                 bp->b_flags |= B_NOCACHE;
2630                                 bwrite(bp);
2631                         } else if (LIST_FIRST(&bp->b_dep)) {
2632                                 bp->b_flags |= B_NOCACHE;
2633                                 bwrite(bp);
2634                         } else {
2635                                 bp->b_flags |= B_RELBUF;
2636                                 brelse(bp);
2637                         }
2638                         goto loop;
2639                 }
2640                 KKASSERT(size <= bp->b_kvasize);
2641                 KASSERT(bp->b_loffset != NOOFFSET, 
2642                         ("getblk: no buffer offset"));
2643
2644                 /*
2645                  * A buffer with B_DELWRI set and B_CACHE clear must
2646                  * be committed before we can return the buffer in
2647                  * order to prevent the caller from issuing a read
2648                  * ( due to B_CACHE not being set ) and overwriting
2649                  * it.
2650                  *
2651                  * Most callers, including NFS and FFS, need this to
2652                  * operate properly either because they assume they
2653                  * can issue a read if B_CACHE is not set, or because
2654                  * ( for example ) an uncached B_DELWRI might loop due 
2655                  * to softupdates re-dirtying the buffer.  In the latter
2656                  * case, B_CACHE is set after the first write completes,
2657                  * preventing further loops.
2658                  *
2659                  * NOTE!  b*write() sets B_CACHE.  If we cleared B_CACHE
2660                  * above while extending the buffer, we cannot allow the
2661                  * buffer to remain with B_CACHE set after the write
2662                  * completes or it will represent a corrupt state.  To
2663                  * deal with this we set B_NOCACHE to scrap the buffer
2664                  * after the write.
2665                  *
2666                  * We might be able to do something fancy, like setting
2667                  * B_CACHE in bwrite() except if B_DELWRI is already set,
2668                  * so the below call doesn't set B_CACHE, but that gets real
2669                  * confusing.  This is much easier.
2670                  */
2671
2672                 if ((bp->b_flags & (B_CACHE|B_DELWRI)) == B_DELWRI) {
2673                         bp->b_flags |= B_NOCACHE;
2674                         bwrite(bp);
2675                         goto loop;
2676                 }
2677                 crit_exit();
2678         } else {
2679                 /*
2680                  * Buffer is not in-core, create new buffer.  The buffer
2681                  * returned by getnewbuf() is locked.  Note that the returned
2682                  * buffer is also considered valid (not marked B_INVAL).
2683                  *
2684                  * Calculating the offset for the I/O requires figuring out
2685                  * the block size.  We use DEV_BSIZE for VBLK or VCHR and
2686                  * the mount's f_iosize otherwise.  If the vnode does not
2687                  * have an associated mount we assume that the passed size is 
2688                  * the block size.  
2689                  *
2690                  * Note that vn_isdisk() cannot be used here since it may
2691                  * return a failure for numerous reasons.   Note that the
2692                  * buffer size may be larger then the block size (the caller
2693                  * will use block numbers with the proper multiple).  Beware
2694                  * of using any v_* fields which are part of unions.  In
2695                  * particular, in DragonFly the mount point overloading 
2696                  * mechanism uses the namecache only and the underlying
2697                  * directory vnode is not a special case.
2698                  */
2699                 int bsize, maxsize;
2700
2701                 if (vp->v_type == VBLK || vp->v_type == VCHR)
2702                         bsize = DEV_BSIZE;
2703                 else if (vp->v_mount)
2704                         bsize = vp->v_mount->mnt_stat.f_iosize;
2705                 else
2706                         bsize = size;
2707
2708                 maxsize = size + (loffset & PAGE_MASK);
2709                 maxsize = imax(maxsize, bsize);
2710
2711                 if ((bp = getnewbuf(blkflags, slptimeo, size, maxsize)) == NULL) {
2712                         if (slpflags || slptimeo) {
2713                                 crit_exit();
2714                                 return NULL;
2715                         }
2716                         goto loop;
2717                 }
2718
2719                 /*
2720                  * This code is used to make sure that a buffer is not
2721                  * created while the getnewbuf routine is blocked.
2722                  * This can be a problem whether the vnode is locked or not.
2723                  * If the buffer is created out from under us, we have to
2724                  * throw away the one we just created.  There is no window
2725                  * race because we are safely running in a critical section
2726                  * from the point of the duplicate buffer creation through
2727                  * to here, and we've locked the buffer.
2728                  */
2729                 if (findblk(vp, loffset)) {
2730                         bp->b_flags |= B_INVAL;
2731                         brelse(bp);
2732                         goto loop;
2733                 }
2734
2735                 /*
2736                  * Insert the buffer into the hash, so that it can
2737                  * be found by findblk(). 
2738                  *
2739                  * Make sure the translation layer has been cleared.
2740                  */
2741                 bp->b_loffset = loffset;
2742                 bp->b_bio2.bio_offset = NOOFFSET;
2743                 /* bp->b_bio2.bio_next = NULL; */
2744
2745                 bgetvp(vp, bp);
2746
2747                 /*
2748                  * All vnode-based buffers must be backed by a VM object.
2749                  */
2750                 KKASSERT(vp->v_object != NULL);
2751                 bp->b_flags |= B_VMIO;
2752                 KKASSERT(bp->b_cmd == BUF_CMD_DONE);
2753
2754                 allocbuf(bp, size);
2755
2756                 crit_exit();
2757         }
2758         return (bp);
2759 }
2760
2761 /*
2762  * regetblk(bp)
2763  *
2764  * Reacquire a buffer that was previously released to the locked queue,
2765  * or reacquire a buffer which is interlocked by having bioops->io_deallocate
2766  * set B_LOCKED (which handles the acquisition race).
2767  *
2768  * To this end, either B_LOCKED must be set or the dependancy list must be
2769  * non-empty.
2770  */
2771 void
2772 regetblk(struct buf *bp)
2773 {
2774         KKASSERT((bp->b_flags & B_LOCKED) || LIST_FIRST(&bp->b_dep) != NULL);
2775         BUF_LOCK(bp, LK_EXCLUSIVE | LK_RETRY);
2776         crit_enter();
2777         bremfree(bp);
2778         crit_exit();
2779 }
2780
2781 /*
2782  * geteblk:
2783  *
2784  *      Get an empty, disassociated buffer of given size.  The buffer is
2785  *      initially set to B_INVAL.
2786  *
2787  *      critical section protection is not required for the allocbuf()
2788  *      call because races are impossible here.
2789  */
2790 struct buf *
2791 geteblk(int size)
2792 {
2793         struct buf *bp;
2794         int maxsize;
2795
2796         maxsize = (size + BKVAMASK) & ~BKVAMASK;
2797
2798         crit_enter();
2799         while ((bp = getnewbuf(0, 0, size, maxsize)) == 0)
2800                 ;
2801         crit_exit();
2802         allocbuf(bp, size);
2803         bp->b_flags |= B_INVAL; /* b_dep cleared by getnewbuf() */
2804         return (bp);
2805 }
2806
2807
2808 /*
2809  * allocbuf:
2810  *
2811  *      This code constitutes the buffer memory from either anonymous system
2812  *      memory (in the case of non-VMIO operations) or from an associated
2813  *      VM object (in the case of VMIO operations).  This code is able to
2814  *      resize a buffer up or down.
2815  *
2816  *      Note that this code is tricky, and has many complications to resolve
2817  *      deadlock or inconsistant data situations.  Tread lightly!!! 
2818  *      There are B_CACHE and B_DELWRI interactions that must be dealt with by 
2819  *      the caller.  Calling this code willy nilly can result in the loss of data.
2820  *
2821  *      allocbuf() only adjusts B_CACHE for VMIO buffers.  getblk() deals with
2822  *      B_CACHE for the non-VMIO case.
2823  *
2824  *      This routine does not need to be called from a critical section but you
2825  *      must own the buffer.
2826  */
2827 int
2828 allocbuf(struct buf *bp, int size)
2829 {
2830         int newbsize, mbsize;
2831         int i;
2832
2833         if (BUF_REFCNT(bp) == 0)
2834                 panic("allocbuf: buffer not busy");
2835
2836         if (bp->b_kvasize < size)
2837                 panic("allocbuf: buffer too small");
2838
2839         if ((bp->b_flags & B_VMIO) == 0) {
2840                 caddr_t origbuf;
2841                 int origbufsize;
2842                 /*
2843                  * Just get anonymous memory from the kernel.  Don't
2844                  * mess with B_CACHE.
2845                  */
2846                 mbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2847                 if (bp->b_flags & B_MALLOC)
2848                         newbsize = mbsize;
2849                 else
2850                         newbsize = round_page(size);
2851
2852                 if (newbsize < bp->b_bufsize) {
2853                         /*
2854                          * Malloced buffers are not shrunk
2855                          */
2856                         if (bp->b_flags & B_MALLOC) {
2857                                 if (newbsize) {
2858                                         bp->b_bcount = size;
2859                                 } else {
2860                                         kfree(bp->b_data, M_BIOBUF);
2861                                         if (bp->b_bufsize) {
2862                                                 bufmallocspace -= bp->b_bufsize;
2863                                                 bufspacewakeup();
2864                                                 bp->b_bufsize = 0;
2865                                         }
2866                                         bp->b_data = bp->b_kvabase;
2867                                         bp->b_bcount = 0;
2868                                         bp->b_flags &= ~B_MALLOC;
2869                                 }
2870                                 return 1;
2871                         }               
2872                         vm_hold_free_pages(
2873                             bp,
2874                             (vm_offset_t) bp->b_data + newbsize,
2875                             (vm_offset_t) bp->b_data + bp->b_bufsize);
2876                 } else if (newbsize > bp->b_bufsize) {
2877                         /*
2878                          * We only use malloced memory on the first allocation.
2879                          * and revert to page-allocated memory when the buffer
2880                          * grows.
2881                          */
2882                         if ((bufmallocspace < maxbufmallocspace) &&
2883                                 (bp->b_bufsize == 0) &&
2884                                 (mbsize <= PAGE_SIZE/2)) {
2885
2886                                 bp->b_data = kmalloc(mbsize, M_BIOBUF, M_WAITOK);
2887                                 bp->b_bufsize = mbsize;
2888                                 bp->b_bcount = size;
2889                                 bp->b_flags |= B_MALLOC;
2890                                 bufmallocspace += mbsize;
2891                                 return 1;
2892                         }
2893                         origbuf = NULL;
2894                         origbufsize = 0;
2895                         /*
2896                          * If the buffer is growing on its other-than-first
2897                          * allocation, then we revert to the page-allocation
2898                          * scheme.
2899                          */
2900                         if (bp->b_flags & B_MALLOC) {
2901                                 origbuf = bp->b_data;
2902                                 origbufsize = bp->b_bufsize;
2903                                 bp->b_data = bp->b_kvabase;
2904                                 if (bp->b_bufsize) {
2905                                         bufmallocspace -= bp->b_bufsize;
2906                                         bufspacewakeup();
2907                                         bp->b_bufsize = 0;
2908                                 }
2909                                 bp->b_flags &= ~B_MALLOC;
2910                                 newbsize = round_page(newbsize);
2911                         }
2912                         vm_hold_load_pages(
2913                             bp,
2914                             (vm_offset_t) bp->b_data + bp->b_bufsize,
2915                             (vm_offset_t) bp->b_data + newbsize);
2916                         if (origbuf) {
2917                                 bcopy(origbuf, bp->b_data, origbufsize);
2918                                 kfree(origbuf, M_BIOBUF);
2919                         }
2920                 }
2921         } else {
2922                 vm_page_t m;
2923                 int desiredpages;
2924
2925                 newbsize = (size + DEV_BSIZE - 1) & ~(DEV_BSIZE - 1);
2926                 desiredpages = ((int)(bp->b_loffset & PAGE_MASK) +
2927                                 newbsize + PAGE_MASK) >> PAGE_SHIFT;
2928                 KKASSERT(desiredpages <= XIO_INTERNAL_PAGES);
2929
2930                 if (bp->b_flags & B_MALLOC)
2931                         panic("allocbuf: VMIO buffer can't be malloced");
2932                 /*
2933                  * Set B_CACHE initially if buffer is 0 length or will become
2934                  * 0-length.
2935                  */
2936                 if (size == 0 || bp->b_bufsize == 0)
2937                         bp->b_flags |= B_CACHE;
2938
2939                 if (newbsize < bp->b_bufsize) {
2940                         /*
2941                          * DEV_BSIZE aligned new buffer size is less then the
2942                          * DEV_BSIZE aligned existing buffer size.  Figure out
2943                          * if we have to remove any pages.
2944                          */
2945                         if (desiredpages < bp->b_xio.xio_npages) {
2946                                 for (i = desiredpages; i < bp->b_xio.xio_npages; i++) {
2947                                         /*
2948                                          * the page is not freed here -- it
2949                                          * is the responsibility of 
2950                                          * vnode_pager_setsize
2951                                          */
2952                                         m = bp->b_xio.xio_pages[i];
2953                                         KASSERT(m != bogus_page,
2954                                             ("allocbuf: bogus page found"));
2955                                         while (vm_page_sleep_busy(m, TRUE, "biodep"))
2956                                                 ;
2957
2958                                         bp->b_xio.xio_pages[i] = NULL;
2959                                         vm_page_unwire(m, 0);
2960                                 }
2961                                 pmap_qremove((vm_offset_t) trunc_page((vm_offset_t)bp->b_data) +
2962                                     (desiredpages << PAGE_SHIFT), (bp->b_xio.xio_npages - desiredpages));
2963                                 bp->b_xio.xio_npages = desiredpages;
2964                         }
2965                 } else if (size > bp->b_bcount) {
2966                         /*
2967                          * We are growing the buffer, possibly in a 
2968                          * byte-granular fashion.
2969                          */
2970                         struct vnode *vp;
2971                         vm_object_t obj;
2972                         vm_offset_t toff;
2973                         vm_offset_t tinc;
2974
2975                         /*
2976                          * Step 1, bring in the VM pages from the object, 
2977                          * allocating them if necessary.  We must clear
2978                          * B_CACHE if these pages are not valid for the 
2979                          * range covered by the buffer.
2980                          *
2981                          * critical section protection is required to protect
2982                          * against interrupts unbusying and freeing pages
2983                          * between our vm_page_lookup() and our
2984                          * busycheck/wiring call.
2985                          */
2986                         vp = bp->b_vp;
2987                         obj = vp->v_object;
2988
2989                         crit_enter();
2990                         while (bp->b_xio.xio_npages < desiredpages) {
2991                                 vm_page_t m;
2992                                 vm_pindex_t pi;
2993
2994                                 pi = OFF_TO_IDX(bp->b_loffset) + bp->b_xio.xio_npages;
2995                                 if ((m = vm_page_lookup(obj, pi)) == NULL) {
2996                                         /*
2997                                          * note: must allocate system pages
2998                                          * since blocking here could intefere
2999                                          * with paging I/O, no matter which
3000                                          * process we are.
3001                                          */
3002                                         m = bio_page_alloc(obj, pi, desiredpages - bp->b_xio.xio_npages);
3003                                         if (m) {
3004                                                 vm_page_wire(m);
3005                                                 vm_page_wakeup(m);
3006                                                 bp->b_flags &= ~B_CACHE;
3007                                                 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3008                                                 ++bp->b_xio.xio_npages;
3009                                         }
3010                                         continue;
3011                                 }
3012
3013                                 /*
3014                                  * We found a page.  If we have to sleep on it,
3015                                  * retry because it might have gotten freed out
3016                                  * from under us.
3017                                  *
3018                                  * We can only test PG_BUSY here.  Blocking on
3019                                  * m->busy might lead to a deadlock:
3020                                  *
3021                                  *  vm_fault->getpages->cluster_read->allocbuf
3022                                  *
3023                                  */
3024
3025                                 if (vm_page_sleep_busy(m, FALSE, "pgtblk"))
3026                                         continue;
3027                                 vm_page_flag_clear(m, PG_ZERO);
3028                                 vm_page_wire(m);
3029                                 bp->b_xio.xio_pages[bp->b_xio.xio_npages] = m;
3030                                 ++bp->b_xio.xio_npages;
3031                         }
3032                         crit_exit();
3033
3034                         /*
3035                          * Step 2.  We've loaded the pages into the buffer,
3036                          * we have to figure out if we can still have B_CACHE
3037                          * set.  Note that B_CACHE is set according to the
3038                          * byte-granular range ( bcount and size ), not the
3039                          * aligned range ( newbsize ).
3040                          *
3041                          * The VM test is against m->valid, which is DEV_BSIZE
3042                          * aligned.  Needless to say, the validity of the data
3043                          * needs to also be DEV_BSIZE aligned.  Note that this
3044                          * fails with NFS if the server or some other client
3045                          * extends the file's EOF.  If our buffer is resized, 
3046                          * B_CACHE may remain set! XXX
3047                          */
3048
3049                         toff = bp->b_bcount;
3050                         tinc = PAGE_SIZE - ((bp->b_loffset + toff) & PAGE_MASK);
3051
3052                         while ((bp->b_flags & B_CACHE) && toff < size) {
3053                                 vm_pindex_t pi;
3054
3055                                 if (tinc > (size - toff))
3056                                         tinc = size - toff;
3057
3058                                 pi = ((bp->b_loffset & PAGE_MASK) + toff) >> 
3059                                     PAGE_SHIFT;
3060
3061                                 vfs_buf_test_cache(
3062                                     bp, 
3063                                     bp->b_loffset,
3064                                     toff, 
3065                                     tinc, 
3066                                     bp->b_xio.xio_pages[pi]
3067                                 );
3068                                 toff += tinc;
3069                                 tinc = PAGE_SIZE;
3070                         }
3071
3072                         /*
3073                          * Step 3, fixup the KVM pmap.  Remember that
3074                          * bp->b_data is relative to bp->b_loffset, but 
3075                          * bp->b_loffset may be offset into the first page.
3076                          */
3077
3078                         bp->b_data = (caddr_t)
3079                             trunc_page((vm_offset_t)bp->b_data);
3080                         pmap_qenter(
3081                             (vm_offset_t)bp->b_data,
3082                             bp->b_xio.xio_pages, 
3083                             bp->b_xio.xio_npages
3084                         );
3085                         bp->b_data = (caddr_t)((vm_offset_t)bp->b_data | 
3086                             (vm_offset_t)(bp->b_loffset & PAGE_MASK));
3087                 }
3088         }
3089
3090         /* adjust space use on already-dirty buffer */
3091         if (bp->b_flags & B_DELWRI) {
3092                 dirtybufspace += newbsize - bp->b_bufsize;
3093                 if (bp->b_flags & B_HEAVY)
3094                         dirtybufspacehw += newbsize - bp->b_bufsize;
3095         }
3096         if (newbsize < bp->b_bufsize)
3097                 bufspacewakeup();
3098         bp->b_bufsize = newbsize;       /* actual buffer allocation     */
3099         bp->b_bcount = size;            /* requested buffer size        */
3100         return 1;
3101 }
3102
3103 /*
3104  * biowait:
3105  *
3106  *      Wait for buffer I/O completion, returning error status.  The buffer
3107  *      is left locked on return.  B_EINTR is converted into an EINTR error
3108  *      and cleared.
3109  *
3110  *      NOTE!  The original b_cmd is lost on return, since b_cmd will be
3111  *      set to BUF_CMD_DONE.
3112  *
3113  * MPSAFE
3114  */
3115 int
3116 biowait(struct buf *bp)
3117 {
3118         if (bp->b_cmd != BUF_CMD_DONE) {
3119                 crit_enter();
3120                 for (;;) {
3121                         tsleep_interlock(bp);
3122                         if (bp->b_cmd == BUF_CMD_DONE)
3123                                 break;
3124                         if (bp->b_cmd == BUF_CMD_READ)
3125                                 tsleep(bp, 0, "biord", 0);
3126                         else
3127                                 tsleep(bp, 0, "biowr", 0);
3128                 }
3129                 crit_exit();
3130         }
3131         if (bp->b_flags & B_EINTR) {
3132                 bp->b_flags &= ~B_EINTR;
3133                 return (EINTR);
3134         }
3135         if (bp->b_flags & B_ERROR) {
3136                 return (bp->b_error ? bp->b_error : EIO);
3137         } else {
3138                 return (0);
3139         }
3140 }
3141
3142 /*
3143  * This associates a tracking count with an I/O.  vn_strategy() and
3144  * dev_dstrategy() do this automatically but there are a few cases
3145  * where a vnode or device layer is bypassed when a block translation
3146  * is cached.  In such cases bio_start_transaction() may be called on
3147  * the bypassed layers so the system gets an I/O in progress indication 
3148  * for those higher layers.
3149  */
3150 void
3151 bio_start_transaction(struct bio *bio, struct bio_track *track)
3152 {
3153         bio->bio_track = track;
3154         bio_track_ref(track);
3155 }
3156
3157 /*
3158  * Initiate I/O on a vnode.
3159  */
3160 void
3161 vn_strategy(struct vnode *vp, struct bio *bio)
3162 {
3163         struct bio_track *track;
3164
3165         KKASSERT(bio->bio_buf->b_cmd != BUF_CMD_DONE);
3166         if (bio->bio_buf->b_cmd == BUF_CMD_READ)
3167                 track = &vp->v_track_read;
3168         else
3169                 track = &vp->v_track_write;
3170         bio->bio_track = track;
3171         bio_track_ref(track);
3172         vop_strategy(*vp->v_ops, vp, bio);
3173 }
3174
3175
3176 /*
3177  * biodone:
3178  *
3179  *      Finish I/O on a buffer, optionally calling a completion function.
3180  *      This is usually called from an interrupt so process blocking is
3181  *      not allowed.
3182  *
3183  *      biodone is also responsible for setting B_CACHE in a B_VMIO bp.
3184  *      In a non-VMIO bp, B_CACHE will be set on the next getblk() 
3185  *      assuming B_INVAL is clear.
3186  *
3187  *      For the VMIO case, we set B_CACHE if the op was a read and no
3188  *      read error occured, or if the op was a write.  B_CACHE is never
3189  *      set if the buffer is invalid or otherwise uncacheable.
3190  *
3191  *      biodone does not mess with B_INVAL, allowing the I/O routine or the
3192  *      initiator to leave B_INVAL set to brelse the buffer out of existance
3193  *      in the biodone routine.
3194  */
3195 void
3196 biodone(struct bio *bio)
3197 {
3198         struct buf *bp = bio->bio_buf;
3199         buf_cmd_t cmd;
3200
3201         crit_enter();
3202
3203         KASSERT(BUF_REFCNTNB(bp) > 0, 
3204                 ("biodone: bp %p not busy %d", bp, BUF_REFCNTNB(bp)));
3205         KASSERT(bp->b_cmd != BUF_CMD_DONE, 
3206                 ("biodone: bp %p already done!", bp));
3207
3208         runningbufwakeup(bp);
3209
3210         /*
3211          * Run up the chain of BIO's.   Leave b_cmd intact for the duration.
3212          */
3213         while (bio) {
3214                 biodone_t *done_func; 
3215                 struct bio_track *track;
3216
3217                 /*
3218                  * BIO tracking.  Most but not all BIOs are tracked.
3219                  */
3220                 if ((track = bio->bio_track) != NULL) {
3221                         bio_track_rel(track);
3222                         bio->bio_track = NULL;
3223                 }
3224
3225                 /*
3226                  * A bio_done function terminates the loop.  The function
3227                  * will be responsible for any further chaining and/or 
3228                  * buffer management.
3229                  *
3230                  * WARNING!  The done function can deallocate the buffer!
3231                  */
3232                 if ((done_func = bio->bio_done) != NULL) {
3233                         bio->bio_done = NULL;
3234                         done_func(bio);
3235                         crit_exit();
3236                         return;
3237                 }
3238                 bio = bio->bio_prev;
3239         }
3240
3241         cmd = bp->b_cmd;
3242         bp->b_cmd = BUF_CMD_DONE;
3243
3244         /*
3245          * Only reads and writes are processed past this point.
3246          */
3247         if (cmd != BUF_CMD_READ && cmd != BUF_CMD_WRITE) {
3248                 if (cmd == BUF_CMD_FREEBLKS)
3249                         bp->b_flags |= B_NOCACHE;
3250                 brelse(bp);
3251                 crit_exit();
3252                 return;
3253         }
3254
3255         /*
3256          * Warning: softupdates may re-dirty the buffer, and HAMMER can do
3257          * a lot worse.  XXX - move this above the clearing of b_cmd
3258          */
3259         if (LIST_FIRST(&bp->b_dep) != NULL)
3260                 buf_complete(bp);
3261
3262         /*
3263          * A failed write must re-dirty the buffer unless B_INVAL
3264          * was set.
3265          */
3266         if (cmd == BUF_CMD_WRITE &&
3267             (bp->b_flags & (B_ERROR | B_INVAL)) == B_ERROR) {
3268                 bp->b_flags &= ~B_NOCACHE;
3269                 bdirty(bp);
3270         }
3271
3272
3273         if (bp->b_flags & B_VMIO) {
3274                 int i;
3275                 vm_ooffset_t foff;
3276                 vm_page_t m;
3277                 vm_object_t obj;
3278                 int iosize;
3279                 struct vnode *vp = bp->b_vp;
3280
3281                 obj = vp->v_object;
3282
3283 #if defined(VFS_BIO_DEBUG)
3284                 if (vp->v_auxrefs == 0)
3285                         panic("biodone: zero vnode hold count");
3286                 if ((vp->v_flag & VOBJBUF) == 0)
3287                         panic("biodone: vnode is not setup for merged cache");
3288 #endif
3289
3290                 foff = bp->b_loffset;
3291                 KASSERT(foff != NOOFFSET, ("biodone: no buffer offset"));
3292                 KASSERT(obj != NULL, ("biodone: missing VM object"));
3293
3294 #if defined(VFS_BIO_DEBUG)
3295                 if (obj->paging_in_progress < bp->b_xio.xio_npages) {
3296                         kprintf("biodone: paging in progress(%d) < bp->b_xio.xio_npages(%d)\n",
3297                             obj->paging_in_progress, bp->b_xio.xio_npages);
3298                 }
3299 #endif
3300
3301                 /*
3302                  * Set B_CACHE if the op was a normal read and no error
3303                  * occured.  B_CACHE is set for writes in the b*write()
3304                  * routines.
3305                  */
3306                 iosize = bp->b_bcount - bp->b_resid;
3307                 if (cmd == BUF_CMD_READ && (bp->b_flags & (B_INVAL|B_NOCACHE|B_ERROR)) == 0) {
3308                         bp->b_flags |= B_CACHE;
3309                 }
3310
3311                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3312                         int bogusflag = 0;
3313                         int resid;
3314
3315                         resid = ((foff + PAGE_SIZE) & ~(off_t)PAGE_MASK) - foff;
3316                         if (resid > iosize)
3317                                 resid = iosize;
3318
3319                         /*
3320                          * cleanup bogus pages, restoring the originals.  Since
3321                          * the originals should still be wired, we don't have
3322                          * to worry about interrupt/freeing races destroying
3323                          * the VM object association.
3324                          */
3325                         m = bp->b_xio.xio_pages[i];
3326                         if (m == bogus_page) {
3327                                 bogusflag = 1;
3328                                 m = vm_page_lookup(obj, OFF_TO_IDX(foff));
3329                                 if (m == NULL)
3330                                         panic("biodone: page disappeared");
3331                                 bp->b_xio.xio_pages[i] = m;
3332                                 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3333                                         bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3334                         }
3335 #if defined(VFS_BIO_DEBUG)
3336                         if (OFF_TO_IDX(foff) != m->pindex) {
3337                                 kprintf(
3338 "biodone: foff(%lu)/m->pindex(%d) mismatch\n",
3339                                     (unsigned long)foff, m->pindex);
3340                         }
3341 #endif
3342
3343                         /*
3344                          * In the write case, the valid and clean bits are
3345                          * already changed correctly ( see bdwrite() ), so we 
3346                          * only need to do this here in the read case.
3347                          */
3348                         if (cmd == BUF_CMD_READ && !bogusflag && resid > 0) {
3349                                 vfs_page_set_valid(bp, foff, i, m);
3350                         }
3351                         vm_page_flag_clear(m, PG_ZERO);
3352
3353                         /*
3354                          * when debugging new filesystems or buffer I/O methods, this
3355                          * is the most common error that pops up.  if you see this, you
3356                          * have not set the page busy flag correctly!!!
3357                          */
3358                         if (m->busy == 0) {
3359                                 kprintf("biodone: page busy < 0, "
3360                                     "pindex: %d, foff: 0x(%x,%x), "
3361                                     "resid: %d, index: %d\n",
3362                                     (int) m->pindex, (int)(foff >> 32),
3363                                                 (int) foff & 0xffffffff, resid, i);
3364                                 if (!vn_isdisk(vp, NULL))
3365                                         kprintf(" iosize: %ld, loffset: %lld, "
3366                                                 "flags: 0x%08x, npages: %d\n",
3367                                             bp->b_vp->v_mount->mnt_stat.f_iosize,
3368                                             (long long)bp->b_loffset,
3369                                             bp->b_flags, bp->b_xio.xio_npages);
3370                                 else
3371                                         kprintf(" VDEV, loffset: %lld, flags: 0x%08x, npages: %d\n",
3372                                             (long long)bp->b_loffset,
3373                                             bp->b_flags, bp->b_xio.xio_npages);
3374                                 kprintf(" valid: 0x%x, dirty: 0x%x, wired: %d\n",
3375                                     m->valid, m->dirty, m->wire_count);
3376                                 panic("biodone: page busy < 0");
3377                         }
3378                         vm_page_io_finish(m);
3379                         vm_object_pip_subtract(obj, 1);
3380                         foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3381                         iosize -= resid;
3382                 }
3383                 if (obj)
3384                         vm_object_pip_wakeupn(obj, 0);
3385         }
3386
3387         /*
3388          * For asynchronous completions, release the buffer now. The brelse
3389          * will do a wakeup there if necessary - so no need to do a wakeup
3390          * here in the async case. The sync case always needs to do a wakeup.
3391          */
3392
3393         if (bp->b_flags & B_ASYNC) {
3394                 if ((bp->b_flags & (B_NOCACHE | B_INVAL | B_ERROR | B_RELBUF)) != 0)
3395                         brelse(bp);
3396                 else
3397                         bqrelse(bp);
3398         } else {
3399                 wakeup(bp);
3400         }
3401         crit_exit();
3402 }
3403
3404 /*
3405  * vfs_unbusy_pages:
3406  *
3407  *      This routine is called in lieu of iodone in the case of
3408  *      incomplete I/O.  This keeps the busy status for pages
3409  *      consistant.
3410  */
3411 void
3412 vfs_unbusy_pages(struct buf *bp)
3413 {
3414         int i;
3415
3416         runningbufwakeup(bp);
3417         if (bp->b_flags & B_VMIO) {
3418                 struct vnode *vp = bp->b_vp;
3419                 vm_object_t obj;
3420
3421                 obj = vp->v_object;
3422
3423                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3424                         vm_page_t m = bp->b_xio.xio_pages[i];
3425
3426                         /*
3427                          * When restoring bogus changes the original pages
3428                          * should still be wired, so we are in no danger of
3429                          * losing the object association and do not need
3430                          * critical section protection particularly.
3431                          */
3432                         if (m == bogus_page) {
3433                                 m = vm_page_lookup(obj, OFF_TO_IDX(bp->b_loffset) + i);
3434                                 if (!m) {
3435                                         panic("vfs_unbusy_pages: page missing");
3436                                 }
3437                                 bp->b_xio.xio_pages[i] = m;
3438                                 pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3439                                         bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3440                         }
3441                         vm_object_pip_subtract(obj, 1);
3442                         vm_page_flag_clear(m, PG_ZERO);
3443                         vm_page_io_finish(m);
3444                 }
3445                 vm_object_pip_wakeupn(obj, 0);
3446         }
3447 }
3448
3449 /*
3450  * vfs_page_set_valid:
3451  *
3452  *      Set the valid bits in a page based on the supplied offset.   The
3453  *      range is restricted to the buffer's size.
3454  *
3455  *      This routine is typically called after a read completes.
3456  */
3457 static void
3458 vfs_page_set_valid(struct buf *bp, vm_ooffset_t off, int pageno, vm_page_t m)
3459 {
3460         vm_ooffset_t soff, eoff;
3461
3462         /*
3463          * Start and end offsets in buffer.  eoff - soff may not cross a
3464          * page boundry or cross the end of the buffer.  The end of the
3465          * buffer, in this case, is our file EOF, not the allocation size
3466          * of the buffer.
3467          */
3468         soff = off;
3469         eoff = (off + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3470         if (eoff > bp->b_loffset + bp->b_bcount)
3471                 eoff = bp->b_loffset + bp->b_bcount;
3472
3473         /*
3474          * Set valid range.  This is typically the entire buffer and thus the
3475          * entire page.
3476          */
3477         if (eoff > soff) {
3478                 vm_page_set_validclean(
3479                     m,
3480                    (vm_offset_t) (soff & PAGE_MASK),
3481                    (vm_offset_t) (eoff - soff)
3482                 );
3483         }
3484 }
3485
3486 /*
3487  * vfs_busy_pages:
3488  *
3489  *      This routine is called before a device strategy routine.
3490  *      It is used to tell the VM system that paging I/O is in
3491  *      progress, and treat the pages associated with the buffer
3492  *      almost as being PG_BUSY.  Also the object 'paging_in_progress'
3493  *      flag is handled to make sure that the object doesn't become
3494  *      inconsistant.
3495  *
3496  *      Since I/O has not been initiated yet, certain buffer flags
3497  *      such as B_ERROR or B_INVAL may be in an inconsistant state
3498  *      and should be ignored.
3499  */
3500 void
3501 vfs_busy_pages(struct vnode *vp, struct buf *bp)
3502 {
3503         int i, bogus;
3504         struct lwp *lp = curthread->td_lwp;
3505
3506         /*
3507          * The buffer's I/O command must already be set.  If reading,
3508          * B_CACHE must be 0 (double check against callers only doing
3509          * I/O when B_CACHE is 0).
3510          */
3511         KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3512         KKASSERT(bp->b_cmd == BUF_CMD_WRITE || (bp->b_flags & B_CACHE) == 0);
3513
3514         if (bp->b_flags & B_VMIO) {
3515                 vm_object_t obj;
3516                 vm_ooffset_t foff;
3517
3518                 obj = vp->v_object;
3519                 foff = bp->b_loffset;
3520                 KASSERT(bp->b_loffset != NOOFFSET,
3521                         ("vfs_busy_pages: no buffer offset"));
3522                 vfs_setdirty(bp);
3523
3524                 /*
3525                  * Loop until none of the pages are busy.
3526                  */
3527 retry:
3528                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3529                         vm_page_t m = bp->b_xio.xio_pages[i];
3530
3531                         if (vm_page_sleep_busy(m, FALSE, "vbpage"))
3532                                 goto retry;
3533                 }
3534
3535                 /*
3536                  * Setup for I/O, soft-busy the page right now because
3537                  * the next loop may block.
3538                  */
3539                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3540                         vm_page_t m = bp->b_xio.xio_pages[i];
3541
3542                         vm_page_flag_clear(m, PG_ZERO);
3543                         if ((bp->b_flags & B_CLUSTER) == 0) {
3544                                 vm_object_pip_add(obj, 1);
3545                                 vm_page_io_start(m);
3546                         }
3547                 }
3548
3549                 /*
3550                  * Adjust protections for I/O and do bogus-page mapping.
3551                  * Assume that vm_page_protect() can block (it can block
3552                  * if VM_PROT_NONE, don't take any chances regardless).
3553                  */
3554                 bogus = 0;
3555                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3556                         vm_page_t m = bp->b_xio.xio_pages[i];
3557
3558                         /*
3559                          * When readying a vnode-backed buffer for a write
3560                          * we must zero-fill any invalid portions of the
3561                          * backing VM pages.
3562                          *
3563                          * When readying a vnode-backed buffer for a read
3564                          * we must replace any dirty pages with a bogus
3565                          * page so we do not destroy dirty data when
3566                          * filling in gaps.  Dirty pages might not
3567                          * necessarily be marked dirty yet, so use m->valid
3568                          * as a reasonable test.
3569                          *
3570                          * Bogus page replacement is, uh, bogus.  We need
3571                          * to find a better way.
3572                          */
3573                         if (bp->b_cmd == BUF_CMD_WRITE) {
3574                                 vm_page_protect(m, VM_PROT_READ);
3575                                 vfs_page_set_valid(bp, foff, i, m);
3576                         } else if (m->valid == VM_PAGE_BITS_ALL) {
3577                                 bp->b_xio.xio_pages[i] = bogus_page;
3578                                 bogus++;
3579                         } else {
3580                                 vm_page_protect(m, VM_PROT_NONE);
3581                         }
3582                         foff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3583                 }
3584                 if (bogus)
3585                         pmap_qenter(trunc_page((vm_offset_t)bp->b_data),
3586                                 bp->b_xio.xio_pages, bp->b_xio.xio_npages);
3587         }
3588
3589         /*
3590          * This is the easiest place to put the process accounting for the I/O
3591          * for now.
3592          */
3593         if (lp != NULL) {
3594                 if (bp->b_cmd == BUF_CMD_READ)
3595                         lp->lwp_ru.ru_inblock++;
3596                 else
3597                         lp->lwp_ru.ru_oublock++;
3598         }
3599 }
3600
3601 /*
3602  * vfs_clean_pages:
3603  *      
3604  *      Tell the VM system that the pages associated with this buffer
3605  *      are clean.  This is used for delayed writes where the data is
3606  *      going to go to disk eventually without additional VM intevention.
3607  *
3608  *      Note that while we only really need to clean through to b_bcount, we
3609  *      just go ahead and clean through to b_bufsize.
3610  */
3611 static void
3612 vfs_clean_pages(struct buf *bp)
3613 {
3614         int i;
3615
3616         if (bp->b_flags & B_VMIO) {
3617                 vm_ooffset_t foff;
3618
3619                 foff = bp->b_loffset;
3620                 KASSERT(foff != NOOFFSET, ("vfs_clean_pages: no buffer offset"));
3621                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
3622                         vm_page_t m = bp->b_xio.xio_pages[i];
3623                         vm_ooffset_t noff = (foff + PAGE_SIZE) & ~(off_t)PAGE_MASK;
3624
3625                         vfs_page_set_valid(bp, foff, i, m);
3626                         foff = noff;
3627                 }
3628         }
3629 }
3630
3631 /*
3632  * vfs_bio_set_validclean:
3633  *
3634  *      Set the range within the buffer to valid and clean.  The range is 
3635  *      relative to the beginning of the buffer, b_loffset.  Note that
3636  *      b_loffset itself may be offset from the beginning of the first page.
3637  */
3638
3639 void   
3640 vfs_bio_set_validclean(struct buf *bp, int base, int size)
3641 {
3642         if (bp->b_flags & B_VMIO) {
3643                 int i;
3644                 int n;
3645
3646                 /*
3647                  * Fixup base to be relative to beginning of first page.
3648                  * Set initial n to be the maximum number of bytes in the
3649                  * first page that can be validated.
3650                  */
3651
3652                 base += (bp->b_loffset & PAGE_MASK);
3653                 n = PAGE_SIZE - (base & PAGE_MASK);
3654
3655                 for (i = base / PAGE_SIZE; size > 0 && i < bp->b_xio.xio_npages; ++i) {
3656                         vm_page_t m = bp->b_xio.xio_pages[i];
3657
3658                         if (n > size)
3659                                 n = size;
3660
3661                         vm_page_set_validclean(m, base & PAGE_MASK, n);
3662                         base += n;
3663                         size -= n;
3664                         n = PAGE_SIZE;
3665                 }
3666         }
3667 }
3668
3669 /*
3670  * vfs_bio_clrbuf:
3671  *
3672  *      Clear a buffer.  This routine essentially fakes an I/O, so we need
3673  *      to clear B_ERROR and B_INVAL.
3674  *
3675  *      Note that while we only theoretically need to clear through b_bcount,
3676  *      we go ahead and clear through b_bufsize.
3677  */
3678
3679 void
3680 vfs_bio_clrbuf(struct buf *bp)
3681 {
3682         int i, mask = 0;
3683         caddr_t sa, ea;
3684         if ((bp->b_flags & (B_VMIO | B_MALLOC)) == B_VMIO) {
3685                 bp->b_flags &= ~(B_INVAL|B_ERROR);
3686                 if ((bp->b_xio.xio_npages == 1) && (bp->b_bufsize < PAGE_SIZE) &&
3687                     (bp->b_loffset & PAGE_MASK) == 0) {
3688                         mask = (1 << (bp->b_bufsize / DEV_BSIZE)) - 1;
3689                         if ((bp->b_xio.xio_pages[0]->valid & mask) == mask) {
3690                                 bp->b_resid = 0;
3691                                 return;
3692                         }
3693                         if (((bp->b_xio.xio_pages[0]->flags & PG_ZERO) == 0) &&
3694                             ((bp->b_xio.xio_pages[0]->valid & mask) == 0)) {
3695                                 bzero(bp->b_data, bp->b_bufsize);
3696                                 bp->b_xio.xio_pages[0]->valid |= mask;
3697                                 bp->b_resid = 0;
3698                                 return;
3699                         }
3700                 }
3701                 sa = bp->b_data;
3702                 for(i=0;i<bp->b_xio.xio_npages;i++,sa=ea) {
3703                         int j = ((vm_offset_t)sa & PAGE_MASK) / DEV_BSIZE;
3704                         ea = (caddr_t)trunc_page((vm_offset_t)sa + PAGE_SIZE);
3705                         ea = (caddr_t)(vm_offset_t)ulmin(
3706                             (u_long)(vm_offset_t)ea,
3707                             (u_long)(vm_offset_t)bp->b_data + bp->b_bufsize);
3708                         mask = ((1 << ((ea - sa) / DEV_BSIZE)) - 1) << j;
3709                         if ((bp->b_xio.xio_pages[i]->valid & mask) == mask)
3710                                 continue;
3711                         if ((bp->b_xio.xio_pages[i]->valid & mask) == 0) {
3712                                 if ((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) {
3713                                         bzero(sa, ea - sa);
3714                                 }
3715                         } else {
3716                                 for (; sa < ea; sa += DEV_BSIZE, j++) {
3717                                         if (((bp->b_xio.xio_pages[i]->flags & PG_ZERO) == 0) &&
3718                                                 (bp->b_xio.xio_pages[i]->valid & (1<<j)) == 0)
3719                                                 bzero(sa, DEV_BSIZE);
3720                                 }
3721                         }
3722                         bp->b_xio.xio_pages[i]->valid |= mask;
3723                         vm_page_flag_clear(bp->b_xio.xio_pages[i], PG_ZERO);
3724                 }
3725                 bp->b_resid = 0;
3726         } else {
3727                 clrbuf(bp);
3728         }
3729 }
3730
3731 /*
3732  * vm_hold_load_pages:
3733  *
3734  *      Load pages into the buffer's address space.  The pages are
3735  *      allocated from the kernel object in order to reduce interference
3736  *      with the any VM paging I/O activity.  The range of loaded
3737  *      pages will be wired.
3738  *
3739  *      If a page cannot be allocated, the 'pagedaemon' is woken up to
3740  *      retrieve the full range (to - from) of pages.
3741  *
3742  */
3743 void
3744 vm_hold_load_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3745 {
3746         vm_offset_t pg;
3747         vm_page_t p;
3748         int index;
3749
3750         to = round_page(to);
3751         from = round_page(from);
3752         index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3753
3754         pg = from;
3755         while (pg < to) {
3756                 /*
3757                  * Note: must allocate system pages since blocking here
3758                  * could intefere with paging I/O, no matter which
3759                  * process we are.
3760                  */
3761                 p = bio_page_alloc(&kernel_object, pg >> PAGE_SHIFT,
3762                                    (vm_pindex_t)((to - pg) >> PAGE_SHIFT));
3763                 if (p) {
3764                         vm_page_wire(p);
3765                         p->valid = VM_PAGE_BITS_ALL;
3766                         vm_page_flag_clear(p, PG_ZERO);
3767                         pmap_kenter(pg, VM_PAGE_TO_PHYS(p));
3768                         bp->b_xio.xio_pages[index] = p;
3769                         vm_page_wakeup(p);
3770
3771                         pg += PAGE_SIZE;
3772                         ++index;
3773                 }
3774         }
3775         bp->b_xio.xio_npages = index;
3776 }
3777
3778 /*
3779  * Allocate pages for a buffer cache buffer.
3780  *
3781  * Under extremely severe memory conditions even allocating out of the
3782  * system reserve can fail.  If this occurs we must allocate out of the
3783  * interrupt reserve to avoid a deadlock with the pageout daemon.
3784  *
3785  * The pageout daemon can run (putpages -> VOP_WRITE -> getblk -> allocbuf).
3786  * If the buffer cache's vm_page_alloc() fails a vm_wait() can deadlock
3787  * against the pageout daemon if pages are not freed from other sources.
3788  */
3789 static
3790 vm_page_t
3791 bio_page_alloc(vm_object_t obj, vm_pindex_t pg, int deficit)
3792 {
3793         vm_page_t p;
3794
3795         /*
3796          * Try a normal allocation, allow use of system reserve.
3797          */
3798         p = vm_page_alloc(obj, pg, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM);
3799         if (p)
3800                 return(p);
3801
3802         /*
3803          * The normal allocation failed and we clearly have a page
3804          * deficit.  Try to reclaim some clean VM pages directly
3805          * from the buffer cache.
3806          */
3807         vm_pageout_deficit += deficit;
3808         recoverbufpages();
3809
3810         /*
3811          * We may have blocked, the caller will know what to do if the
3812          * page now exists.
3813          */
3814         if (vm_page_lookup(obj, pg))
3815                 return(NULL);
3816
3817         /*
3818          * Allocate and allow use of the interrupt reserve.
3819          *
3820          * If after all that we still can't allocate a VM page we are
3821          * in real trouble, but we slog on anyway hoping that the system
3822          * won't deadlock.
3823          */
3824         p = vm_page_alloc(obj, pg, VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
3825                                    VM_ALLOC_INTERRUPT);
3826         if (p) {
3827                 if (vm_page_count_severe()) {
3828                         kprintf("bio_page_alloc: WARNING emergency page "
3829                                 "allocation\n");
3830                         vm_wait(hz / 20);
3831                 }
3832         } else {
3833                 kprintf("bio_page_alloc: WARNING emergency page "
3834                         "allocation failed\n");
3835                 vm_wait(hz * 5);
3836         }
3837         return(p);
3838 }
3839
3840 /*
3841  * vm_hold_free_pages:
3842  *
3843  *      Return pages associated with the buffer back to the VM system.
3844  *
3845  *      The range of pages underlying the buffer's address space will
3846  *      be unmapped and un-wired.
3847  */
3848 void
3849 vm_hold_free_pages(struct buf *bp, vm_offset_t from, vm_offset_t to)
3850 {
3851         vm_offset_t pg;
3852         vm_page_t p;
3853         int index, newnpages;
3854
3855         from = round_page(from);
3856         to = round_page(to);
3857         newnpages = index = (from - trunc_page((vm_offset_t)bp->b_data)) >> PAGE_SHIFT;
3858
3859         for (pg = from; pg < to; pg += PAGE_SIZE, index++) {
3860                 p = bp->b_xio.xio_pages[index];
3861                 if (p && (index < bp->b_xio.xio_npages)) {
3862                         if (p->busy) {
3863                                 kprintf("vm_hold_free_pages: doffset: %lld, "
3864                                         "loffset: %lld\n",
3865                                         (long long)bp->b_bio2.bio_offset,
3866                                         (long long)bp->b_loffset);
3867                         }
3868                         bp->b_xio.xio_pages[index] = NULL;
3869                         pmap_kremove(pg);
3870                         vm_page_busy(p);
3871                         vm_page_unwire(p, 0);
3872                         vm_page_free(p);
3873                 }
3874         }
3875         bp->b_xio.xio_npages = newnpages;
3876 }
3877
3878 /*
3879  * vmapbuf:
3880  *
3881  *      Map a user buffer into KVM via a pbuf.  On return the buffer's
3882  *      b_data, b_bufsize, and b_bcount will be set, and its XIO page array
3883  *      initialized.
3884  */
3885 int
3886 vmapbuf(struct buf *bp, caddr_t udata, int bytes)
3887 {
3888         caddr_t addr;
3889         vm_offset_t va;
3890         vm_page_t m;
3891         int vmprot;
3892         int error;
3893         int pidx;
3894         int i;
3895
3896         /* 
3897          * bp had better have a command and it better be a pbuf.
3898          */
3899         KKASSERT(bp->b_cmd != BUF_CMD_DONE);
3900         KKASSERT(bp->b_flags & B_PAGING);
3901
3902         if (bytes < 0)
3903                 return (-1);
3904
3905         /*
3906          * Map the user data into KVM.  Mappings have to be page-aligned.
3907          */
3908         addr = (caddr_t)trunc_page((vm_offset_t)udata);
3909         pidx = 0;
3910
3911         vmprot = VM_PROT_READ;
3912         if (bp->b_cmd == BUF_CMD_READ)
3913                 vmprot |= VM_PROT_WRITE;
3914
3915         while (addr < udata + bytes) {
3916                 /*
3917                  * Do the vm_fault if needed; do the copy-on-write thing
3918                  * when reading stuff off device into memory.
3919                  *
3920                  * vm_fault_page*() returns a held VM page.
3921                  */
3922                 va = (addr >= udata) ? (vm_offset_t)addr : (vm_offset_t)udata;
3923                 va = trunc_page(va);
3924
3925                 m = vm_fault_page_quick(va, vmprot, &error);
3926                 if (m == NULL) {
3927                         for (i = 0; i < pidx; ++i) {
3928                             vm_page_unhold(bp->b_xio.xio_pages[i]);
3929                             bp->b_xio.xio_pages[i] = NULL;
3930                         }
3931                         return(-1);
3932                 }
3933                 bp->b_xio.xio_pages[pidx] = m;
3934                 addr += PAGE_SIZE;
3935                 ++pidx;
3936         }
3937
3938         /*
3939          * Map the page array and set the buffer fields to point to
3940          * the mapped data buffer.
3941          */
3942         if (pidx > btoc(MAXPHYS))
3943                 panic("vmapbuf: mapped more than MAXPHYS");
3944         pmap_qenter((vm_offset_t)bp->b_kvabase, bp->b_xio.xio_pages, pidx);
3945
3946         bp->b_xio.xio_npages = pidx;
3947         bp->b_data = bp->b_kvabase + ((int)(intptr_t)udata & PAGE_MASK);
3948         bp->b_bcount = bytes;
3949         bp->b_bufsize = bytes;
3950         return(0);
3951 }
3952
3953 /*
3954  * vunmapbuf:
3955  *
3956  *      Free the io map PTEs associated with this IO operation.
3957  *      We also invalidate the TLB entries and restore the original b_addr.
3958  */
3959 void
3960 vunmapbuf(struct buf *bp)
3961 {
3962         int pidx;
3963         int npages;
3964
3965         KKASSERT(bp->b_flags & B_PAGING);
3966
3967         npages = bp->b_xio.xio_npages;
3968         pmap_qremove(trunc_page((vm_offset_t)bp->b_data), npages);
3969         for (pidx = 0; pidx < npages; ++pidx) {
3970                 vm_page_unhold(bp->b_xio.xio_pages[pidx]);
3971                 bp->b_xio.xio_pages[pidx] = NULL;
3972         }
3973         bp->b_xio.xio_npages = 0;
3974         bp->b_data = bp->b_kvabase;
3975 }
3976
3977 /*
3978  * Scan all buffers in the system and issue the callback.
3979  */
3980 int
3981 scan_all_buffers(int (*callback)(struct buf *, void *), void *info)
3982 {
3983         int count = 0;
3984         int error;
3985         int n;
3986
3987         for (n = 0; n < nbuf; ++n) {
3988                 if ((error = callback(&buf[n], info)) < 0) {
3989                         count = error;
3990                         break;
3991                 }
3992                 count += error;
3993         }
3994         return (count);
3995 }
3996
3997 /*
3998  * print out statistics from the current status of the buffer pool
3999  * this can be toggeled by the system control option debug.syncprt
4000  */
4001 #ifdef DEBUG
4002 void
4003 vfs_bufstats(void)
4004 {
4005         int i, j, count;
4006         struct buf *bp;
4007         struct bqueues *dp;
4008         int counts[(MAXBSIZE / PAGE_SIZE) + 1];
4009         static char *bname[3] = { "LOCKED", "LRU", "AGE" };
4010
4011         for (dp = bufqueues, i = 0; dp < &bufqueues[3]; dp++, i++) {
4012                 count = 0;
4013                 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
4014                         counts[j] = 0;
4015                 crit_enter();
4016                 TAILQ_FOREACH(bp, dp, b_freelist) {
4017                         counts[bp->b_bufsize/PAGE_SIZE]++;
4018                         count++;
4019                 }
4020                 crit_exit();
4021                 kprintf("%s: total-%d", bname[i], count);
4022                 for (j = 0; j <= MAXBSIZE/PAGE_SIZE; j++)
4023                         if (counts[j] != 0)
4024                                 kprintf(", %d-%d", j * PAGE_SIZE, counts[j]);
4025                 kprintf("\n");
4026         }
4027 }
4028 #endif
4029
4030 #ifdef DDB
4031
4032 DB_SHOW_COMMAND(buffer, db_show_buffer)
4033 {
4034         /* get args */
4035         struct buf *bp = (struct buf *)addr;
4036
4037         if (!have_addr) {
4038                 db_printf("usage: show buffer <addr>\n");
4039                 return;
4040         }
4041
4042         db_printf("b_flags = 0x%b\n", (u_int)bp->b_flags, PRINT_BUF_FLAGS);
4043         db_printf("b_cmd = %d\n", bp->b_cmd);
4044         db_printf("b_error = %d, b_bufsize = %d, b_bcount = %d, "
4045                   "b_resid = %d\n, b_data = %p, "
4046                   "bio_offset(disk) = %lld, bio_offset(phys) = %lld\n",
4047                   bp->b_error, bp->b_bufsize, bp->b_bcount, bp->b_resid,
4048                   bp->b_data,
4049                   (long long)bp->b_bio2.bio_offset,
4050                   (long long)(bp->b_bio2.bio_next ?
4051                                 bp->b_bio2.bio_next->bio_offset : (off_t)-1));
4052         if (bp->b_xio.xio_npages) {
4053                 int i;
4054                 db_printf("b_xio.xio_npages = %d, pages(OBJ, IDX, PA): ",
4055                         bp->b_xio.xio_npages);
4056                 for (i = 0; i < bp->b_xio.xio_npages; i++) {
4057                         vm_page_t m;
4058                         m = bp->b_xio.xio_pages[i];
4059                         db_printf("(%p, 0x%lx, 0x%lx)", (void *)m->object,
4060                             (u_long)m->pindex, (u_long)VM_PAGE_TO_PHYS(m));
4061                         if ((i + 1) < bp->b_xio.xio_npages)
4062                                 db_printf(",");
4063                 }
4064                 db_printf("\n");
4065         }
4066 }
4067 #endif /* DDB */