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