Merge branch 'master' of ssh://crater.dragonflybsd.org/repository/git/dragonfly
[dragonfly.git] / sys / vfs / hammer / hammer_io.c
1 /*
2  * Copyright (c) 2007-2008 The DragonFly Project.  All rights reserved.
3  * 
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  * 
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  * 
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  * 
34  * $DragonFly: src/sys/vfs/hammer/hammer_io.c,v 1.55 2008/09/15 17:02:49 dillon Exp $
35  */
36 /*
37  * IO Primitives and buffer cache management
38  *
39  * All major data-tracking structures in HAMMER contain a struct hammer_io
40  * which is used to manage their backing store.  We use filesystem buffers
41  * for backing store and we leave them passively associated with their
42  * HAMMER structures.
43  *
44  * If the kernel tries to destroy a passively associated buf which we cannot
45  * yet let go we set B_LOCKED in the buffer and then actively released it
46  * later when we can.
47  */
48
49 #include "hammer.h"
50 #include <sys/fcntl.h>
51 #include <sys/nlookup.h>
52 #include <sys/buf.h>
53 #include <sys/buf2.h>
54
55 static void hammer_io_modify(hammer_io_t io, int count);
56 static void hammer_io_deallocate(struct buf *bp);
57 #if 0
58 static void hammer_io_direct_read_complete(struct bio *nbio);
59 #endif
60 static void hammer_io_direct_write_complete(struct bio *nbio);
61 static int hammer_io_direct_uncache_callback(hammer_inode_t ip, void *data);
62 static void hammer_io_set_modlist(struct hammer_io *io);
63 static void hammer_io_flush_mark(hammer_volume_t volume);
64
65
66 /*
67  * Initialize a new, already-zero'd hammer_io structure, or reinitialize
68  * an existing hammer_io structure which may have switched to another type.
69  */
70 void
71 hammer_io_init(hammer_io_t io, hammer_volume_t volume, enum hammer_io_type type)
72 {
73         io->volume = volume;
74         io->hmp = volume->io.hmp;
75         io->type = type;
76 }
77
78 /*
79  * Helper routine to disassociate a buffer cache buffer from an I/O
80  * structure.  The buffer is unlocked and marked appropriate for reclamation.
81  *
82  * The io may have 0 or 1 references depending on who called us.  The
83  * caller is responsible for dealing with the refs.
84  *
85  * This call can only be made when no action is required on the buffer.
86  *
87  * The caller must own the buffer and the IO must indicate that the
88  * structure no longer owns it (io.released != 0).
89  */
90 static void
91 hammer_io_disassociate(hammer_io_structure_t iou)
92 {
93         struct buf *bp = iou->io.bp;
94
95         KKASSERT(iou->io.released);
96         KKASSERT(iou->io.modified == 0);
97         KKASSERT(LIST_FIRST(&bp->b_dep) == (void *)iou);
98         buf_dep_init(bp);
99         iou->io.bp = NULL;
100
101         /*
102          * If the buffer was locked someone wanted to get rid of it.
103          */
104         if (bp->b_flags & B_LOCKED) {
105                 --hammer_count_io_locked;
106                 bp->b_flags &= ~B_LOCKED;
107         }
108         if (iou->io.reclaim) {
109                 bp->b_flags |= B_NOCACHE|B_RELBUF;
110                 iou->io.reclaim = 0;
111         }
112
113         switch(iou->io.type) {
114         case HAMMER_STRUCTURE_VOLUME:
115                 iou->volume.ondisk = NULL;
116                 break;
117         case HAMMER_STRUCTURE_DATA_BUFFER:
118         case HAMMER_STRUCTURE_META_BUFFER:
119         case HAMMER_STRUCTURE_UNDO_BUFFER:
120                 iou->buffer.ondisk = NULL;
121                 break;
122         }
123 }
124
125 /*
126  * Wait for any physical IO to complete
127  *
128  * XXX we aren't interlocked against a spinlock or anything so there
129  *     is a small window in the interlock / io->running == 0 test.
130  */
131 void
132 hammer_io_wait(hammer_io_t io)
133 {
134         if (io->running) {
135                 for (;;) {
136                         io->waiting = 1;
137                         tsleep_interlock(io, 0);
138                         if (io->running == 0)
139                                 break;
140                         tsleep(io, PINTERLOCKED, "hmrflw", hz);
141                         if (io->running == 0)
142                                 break;
143                 }
144         }
145 }
146
147 /*
148  * Wait for all hammer_io-initated write I/O's to complete.  This is not
149  * supposed to count direct I/O's but some can leak through (for
150  * non-full-sized direct I/Os).
151  */
152 void
153 hammer_io_wait_all(hammer_mount_t hmp, const char *ident)
154 {
155         hammer_io_flush_sync(hmp);
156         crit_enter();
157         while (hmp->io_running_space)
158                 tsleep(&hmp->io_running_space, 0, ident, 0);
159         crit_exit();
160 }
161
162 /*
163  * Clear a flagged error condition on a I/O buffer.  The caller must hold
164  * its own ref on the buffer.
165  */
166 void
167 hammer_io_clear_error(struct hammer_io *io)
168 {
169         if (io->ioerror) {
170                 io->ioerror = 0;
171                 hammer_unref(&io->lock);
172                 KKASSERT(io->lock.refs > 0);
173         }
174 }
175
176
177 #define HAMMER_MAXRA    4
178
179 /*
180  * Load bp for a HAMMER structure.  The io must be exclusively locked by
181  * the caller.
182  *
183  * This routine is mostly used on meta-data and small-data blocks.  Generally
184  * speaking HAMMER assumes some locality of reference and will cluster 
185  * a 64K read.
186  *
187  * Note that clustering occurs at the device layer, not the logical layer.
188  * If the buffers do not apply to the current operation they may apply to
189  * some other.
190  */
191 int
192 hammer_io_read(struct vnode *devvp, struct hammer_io *io, hammer_off_t limit)
193 {
194         struct buf *bp;
195         int   error;
196
197         if ((bp = io->bp) == NULL) {
198                 hammer_count_io_running_read += io->bytes;
199                 if (hammer_cluster_enable) {
200                         error = cluster_read(devvp, limit,
201                                              io->offset, io->bytes,
202                                              HAMMER_CLUSTER_SIZE,
203                                              HAMMER_CLUSTER_BUFS, &io->bp);
204                 } else {
205                         error = bread(devvp, io->offset, io->bytes, &io->bp);
206                 }
207                 hammer_stats_disk_read += io->bytes;
208                 hammer_count_io_running_read -= io->bytes;
209
210                 /*
211                  * The code generally assumes b_ops/b_dep has been set-up,
212                  * even if we error out here.
213                  */
214                 bp = io->bp;
215                 bp->b_ops = &hammer_bioops;
216                 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
217                 LIST_INSERT_HEAD(&bp->b_dep, &io->worklist, node);
218                 BUF_KERNPROC(bp);
219                 KKASSERT(io->modified == 0);
220                 KKASSERT(io->running == 0);
221                 KKASSERT(io->waiting == 0);
222                 io->released = 0;       /* we hold an active lock on bp */
223         } else {
224                 error = 0;
225         }
226         return(error);
227 }
228
229 /*
230  * Similar to hammer_io_read() but returns a zero'd out buffer instead.
231  * Must be called with the IO exclusively locked.
232  *
233  * vfs_bio_clrbuf() is kinda nasty, enforce serialization against background
234  * I/O by forcing the buffer to not be in a released state before calling
235  * it.
236  *
237  * This function will also mark the IO as modified but it will not
238  * increment the modify_refs count.
239  */
240 int
241 hammer_io_new(struct vnode *devvp, struct hammer_io *io)
242 {
243         struct buf *bp;
244
245         if ((bp = io->bp) == NULL) {
246                 io->bp = getblk(devvp, io->offset, io->bytes, 0, 0);
247                 bp = io->bp;
248                 bp->b_ops = &hammer_bioops;
249                 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
250                 LIST_INSERT_HEAD(&bp->b_dep, &io->worklist, node);
251                 io->released = 0;
252                 KKASSERT(io->running == 0);
253                 io->waiting = 0;
254                 BUF_KERNPROC(bp);
255         } else {
256                 if (io->released) {
257                         regetblk(bp);
258                         BUF_KERNPROC(bp);
259                         io->released = 0;
260                 }
261         }
262         hammer_io_modify(io, 0);
263         vfs_bio_clrbuf(bp);
264         return(0);
265 }
266
267 /*
268  * Advance the activity count on the underlying buffer because
269  * HAMMER does not getblk/brelse on every access.
270  */
271 void
272 hammer_io_advance(struct hammer_io *io)
273 {
274         if (io->bp)
275                 buf_act_advance(io->bp);
276 }
277
278 /*
279  * Remove potential device level aliases against buffers managed by high level
280  * vnodes.  Aliases can also be created due to mixed buffer sizes or via
281  * direct access to the backing store device.
282  *
283  * This is nasty because the buffers are also VMIO-backed.  Even if a buffer
284  * does not exist its backing VM pages might, and we have to invalidate
285  * those as well or a getblk() will reinstate them.
286  *
287  * Buffer cache buffers associated with hammer_buffers cannot be
288  * invalidated.
289  */
290 int
291 hammer_io_inval(hammer_volume_t volume, hammer_off_t zone2_offset)
292 {
293         hammer_io_structure_t iou;
294         hammer_off_t phys_offset;
295         struct buf *bp;
296         int error;
297
298         phys_offset = volume->ondisk->vol_buf_beg +
299                       (zone2_offset & HAMMER_OFF_SHORT_MASK);
300         crit_enter();
301         if ((bp = findblk(volume->devvp, phys_offset, FINDBLK_TEST)) != NULL)
302                 bp = getblk(volume->devvp, phys_offset, bp->b_bufsize, 0, 0);
303         else
304                 bp = getblk(volume->devvp, phys_offset, HAMMER_BUFSIZE, 0, 0);
305         if ((iou = (void *)LIST_FIRST(&bp->b_dep)) != NULL) {
306 #if 0
307                 hammer_ref(&iou->io.lock);
308                 hammer_io_clear_modify(&iou->io, 1);
309                 bundirty(bp);
310                 iou->io.released = 0;
311                 BUF_KERNPROC(bp);
312                 iou->io.reclaim = 1;
313                 iou->io.waitdep = 1;
314                 KKASSERT(iou->io.lock.refs == 1);
315                 hammer_rel_buffer(&iou->buffer, 0);
316                 /*hammer_io_deallocate(bp);*/
317 #endif
318                 bqrelse(bp);
319                 error = EAGAIN;
320         } else {
321                 KKASSERT((bp->b_flags & B_LOCKED) == 0);
322                 bundirty(bp);
323                 bp->b_flags |= B_NOCACHE|B_RELBUF;
324                 brelse(bp);
325                 error = 0;
326         }
327         crit_exit();
328         return(error);
329 }
330
331 /*
332  * This routine is called on the last reference to a hammer structure.
333  * The io is usually interlocked with io.loading and io.refs must be 1.
334  *
335  * This routine may return a non-NULL bp to the caller for dispoal.  Disposal
336  * simply means the caller finishes decrementing the ref-count on the 
337  * IO structure then brelse()'s the bp.  The bp may or may not still be
338  * passively associated with the IO.
339  * 
340  * The only requirement here is that modified meta-data and volume-header
341  * buffer may NOT be disassociated from the IO structure, and consequently
342  * we also leave such buffers actively associated with the IO if they already
343  * are (since the kernel can't do anything with them anyway).  Only the
344  * flusher is allowed to write such buffers out.  Modified pure-data and
345  * undo buffers are returned to the kernel but left passively associated
346  * so we can track when the kernel writes the bp out.
347  */
348 struct buf *
349 hammer_io_release(struct hammer_io *io, int flush)
350 {
351         union hammer_io_structure *iou = (void *)io;
352         struct buf *bp;
353
354         if ((bp = io->bp) == NULL)
355                 return(NULL);
356
357         /*
358          * Try to flush a dirty IO to disk if asked to by the
359          * caller or if the kernel tried to flush the buffer in the past.
360          *
361          * Kernel-initiated flushes are only allowed for pure-data buffers.
362          * meta-data and volume buffers can only be flushed explicitly
363          * by HAMMER.
364          */
365         if (io->modified) {
366                 if (flush) {
367                         hammer_io_flush(io, 0);
368                 } else if (bp->b_flags & B_LOCKED) {
369                         switch(io->type) {
370                         case HAMMER_STRUCTURE_DATA_BUFFER:
371                                 hammer_io_flush(io, 0);
372                                 break;
373                         case HAMMER_STRUCTURE_UNDO_BUFFER:
374                                 hammer_io_flush(io, hammer_undo_reclaim(io));
375                                 break;
376                         default:
377                                 break;
378                         }
379                 } /* else no explicit request to flush the buffer */
380         }
381
382         /*
383          * Wait for the IO to complete if asked to.  This occurs when
384          * the buffer must be disposed of definitively during an umount
385          * or buffer invalidation.
386          */
387         if (io->waitdep && io->running) {
388                 hammer_io_wait(io);
389         }
390
391         /*
392          * Return control of the buffer to the kernel (with the provisio
393          * that our bioops can override kernel decisions with regards to
394          * the buffer).
395          */
396         if ((flush || io->reclaim) && io->modified == 0 && io->running == 0) {
397                 /*
398                  * Always disassociate the bp if an explicit flush
399                  * was requested and the IO completed with no error
400                  * (so unmount can really clean up the structure).
401                  */
402                 if (io->released) {
403                         regetblk(bp);
404                         BUF_KERNPROC(bp);
405                 } else {
406                         io->released = 1;
407                 }
408                 hammer_io_disassociate((hammer_io_structure_t)io);
409                 /* return the bp */
410         } else if (io->modified) {
411                 /*
412                  * Only certain IO types can be released to the kernel if
413                  * the buffer has been modified.
414                  *
415                  * volume and meta-data IO types may only be explicitly
416                  * flushed by HAMMER.
417                  */
418                 switch(io->type) {
419                 case HAMMER_STRUCTURE_DATA_BUFFER:
420                 case HAMMER_STRUCTURE_UNDO_BUFFER:
421                         if (io->released == 0) {
422                                 io->released = 1;
423                                 bdwrite(bp);
424                         }
425                         break;
426                 default:
427                         break;
428                 }
429                 bp = NULL;      /* bp left associated */
430         } else if (io->released == 0) {
431                 /*
432                  * Clean buffers can be generally released to the kernel.
433                  * We leave the bp passively associated with the HAMMER
434                  * structure and use bioops to disconnect it later on
435                  * if the kernel wants to discard the buffer.
436                  *
437                  * We can steal the structure's ownership of the bp.
438                  */
439                 io->released = 1;
440                 if (bp->b_flags & B_LOCKED) {
441                         hammer_io_disassociate(iou);
442                         /* return the bp */
443                 } else {
444                         if (io->reclaim) {
445                                 hammer_io_disassociate(iou);
446                                 /* return the bp */
447                         } else {
448                                 /* return the bp (bp passively associated) */
449                         }
450                 }
451         } else {
452                 /*
453                  * A released buffer is passively associate with our
454                  * hammer_io structure.  The kernel cannot destroy it
455                  * without making a bioops call.  If the kernel (B_LOCKED)
456                  * or we (reclaim) requested that the buffer be destroyed
457                  * we destroy it, otherwise we do a quick get/release to
458                  * reset its position in the kernel's LRU list.
459                  *
460                  * Leaving the buffer passively associated allows us to
461                  * use the kernel's LRU buffer flushing mechanisms rather
462                  * then rolling our own.
463                  *
464                  * XXX there are two ways of doing this.  We can re-acquire
465                  * and passively release to reset the LRU, or not.
466                  */
467                 if (io->running == 0) {
468                         regetblk(bp);
469                         if ((bp->b_flags & B_LOCKED) || io->reclaim) {
470                                 hammer_io_disassociate(iou);
471                                 /* return the bp */
472                         } else {
473                                 /* return the bp (bp passively associated) */
474                         }
475                 } else {
476                         /*
477                          * bp is left passively associated but we do not
478                          * try to reacquire it.  Interactions with the io
479                          * structure will occur on completion of the bp's
480                          * I/O.
481                          */
482                         bp = NULL;
483                 }
484         }
485         return(bp);
486 }
487
488 /*
489  * This routine is called with a locked IO when a flush is desired and
490  * no other references to the structure exists other then ours.  This
491  * routine is ONLY called when HAMMER believes it is safe to flush a
492  * potentially modified buffer out.
493  */
494 void
495 hammer_io_flush(struct hammer_io *io, int reclaim)
496 {
497         struct buf *bp;
498
499         /*
500          * Degenerate case - nothing to flush if nothing is dirty.
501          */
502         if (io->modified == 0) {
503                 return;
504         }
505
506         KKASSERT(io->bp);
507         KKASSERT(io->modify_refs <= 0);
508
509         /*
510          * Acquire ownership of the bp, particularly before we clear our
511          * modified flag.
512          *
513          * We are going to bawrite() this bp.  Don't leave a window where
514          * io->released is set, we actually own the bp rather then our
515          * buffer.
516          */
517         bp = io->bp;
518         if (io->released) {
519                 regetblk(bp);
520                 /* BUF_KERNPROC(io->bp); */
521                 /* io->released = 0; */
522                 KKASSERT(io->released);
523                 KKASSERT(io->bp == bp);
524         }
525         io->released = 1;
526
527         if (reclaim) {
528                 io->reclaim = 1;
529                 if ((bp->b_flags & B_LOCKED) == 0) {
530                         bp->b_flags |= B_LOCKED;
531                         ++hammer_count_io_locked;
532                 }
533         }
534
535         /*
536          * Acquire exclusive access to the bp and then clear the modified
537          * state of the buffer prior to issuing I/O to interlock any
538          * modifications made while the I/O is in progress.  This shouldn't
539          * happen anyway but losing data would be worse.  The modified bit
540          * will be rechecked after the IO completes.
541          *
542          * NOTE: This call also finalizes the buffer's content (inval == 0).
543          *
544          * This is only legal when lock.refs == 1 (otherwise we might clear
545          * the modified bit while there are still users of the cluster
546          * modifying the data).
547          *
548          * Do this before potentially blocking so any attempt to modify the
549          * ondisk while we are blocked blocks waiting for us.
550          */
551         hammer_ref(&io->lock);
552         hammer_io_clear_modify(io, 0);
553         hammer_unref(&io->lock);
554
555         if (hammer_debug_io & 0x0002)
556                 kprintf("hammer io_write %016jx\n", bp->b_bio1.bio_offset);
557
558         /*
559          * Transfer ownership to the kernel and initiate I/O.
560          */
561         io->running = 1;
562         io->hmp->io_running_space += io->bytes;
563         hammer_count_io_running_write += io->bytes;
564         bawrite(bp);
565         hammer_io_flush_mark(io->volume);
566 }
567
568 /************************************************************************
569  *                              BUFFER DIRTYING                         *
570  ************************************************************************
571  *
572  * These routines deal with dependancies created when IO buffers get
573  * modified.  The caller must call hammer_modify_*() on a referenced
574  * HAMMER structure prior to modifying its on-disk data.
575  *
576  * Any intent to modify an IO buffer acquires the related bp and imposes
577  * various write ordering dependancies.
578  */
579
580 /*
581  * Mark a HAMMER structure as undergoing modification.  Meta-data buffers
582  * are locked until the flusher can deal with them, pure data buffers
583  * can be written out.
584  */
585 static
586 void
587 hammer_io_modify(hammer_io_t io, int count)
588 {
589         /*
590          * io->modify_refs must be >= 0
591          */
592         while (io->modify_refs < 0) {
593                 io->waitmod = 1;
594                 tsleep(io, 0, "hmrmod", 0);
595         }
596
597         /*
598          * Shortcut if nothing to do.
599          */
600         KKASSERT(io->lock.refs != 0 && io->bp != NULL);
601         io->modify_refs += count;
602         if (io->modified && io->released == 0)
603                 return;
604
605         hammer_lock_ex(&io->lock);
606         if (io->modified == 0) {
607                 hammer_io_set_modlist(io);
608                 io->modified = 1;
609         }
610         if (io->released) {
611                 regetblk(io->bp);
612                 BUF_KERNPROC(io->bp);
613                 io->released = 0;
614                 KKASSERT(io->modified != 0);
615         }
616         hammer_unlock(&io->lock);
617 }
618
619 static __inline
620 void
621 hammer_io_modify_done(hammer_io_t io)
622 {
623         KKASSERT(io->modify_refs > 0);
624         --io->modify_refs;
625         if (io->modify_refs == 0 && io->waitmod) {
626                 io->waitmod = 0;
627                 wakeup(io);
628         }
629 }
630
631 void
632 hammer_io_write_interlock(hammer_io_t io)
633 {
634         while (io->modify_refs != 0) {
635                 io->waitmod = 1;
636                 tsleep(io, 0, "hmrmod", 0);
637         }
638         io->modify_refs = -1;
639 }
640
641 void
642 hammer_io_done_interlock(hammer_io_t io)
643 {
644         KKASSERT(io->modify_refs == -1);
645         io->modify_refs = 0;
646         if (io->waitmod) {
647                 io->waitmod = 0;
648                 wakeup(io);
649         }
650 }
651
652 /*
653  * Caller intends to modify a volume's ondisk structure.
654  *
655  * This is only allowed if we are the flusher or we have a ref on the
656  * sync_lock.
657  */
658 void
659 hammer_modify_volume(hammer_transaction_t trans, hammer_volume_t volume,
660                      void *base, int len)
661 {
662         KKASSERT (trans == NULL || trans->sync_lock_refs > 0);
663
664         hammer_io_modify(&volume->io, 1);
665         if (len) {
666                 intptr_t rel_offset = (intptr_t)base - (intptr_t)volume->ondisk;
667                 KKASSERT((rel_offset & ~(intptr_t)HAMMER_BUFMASK) == 0);
668                 hammer_generate_undo(trans,
669                          HAMMER_ENCODE_RAW_VOLUME(volume->vol_no, rel_offset),
670                          base, len);
671         }
672 }
673
674 /*
675  * Caller intends to modify a buffer's ondisk structure.
676  *
677  * This is only allowed if we are the flusher or we have a ref on the
678  * sync_lock.
679  */
680 void
681 hammer_modify_buffer(hammer_transaction_t trans, hammer_buffer_t buffer,
682                      void *base, int len)
683 {
684         KKASSERT (trans == NULL || trans->sync_lock_refs > 0);
685
686         hammer_io_modify(&buffer->io, 1);
687         if (len) {
688                 intptr_t rel_offset = (intptr_t)base - (intptr_t)buffer->ondisk;
689                 KKASSERT((rel_offset & ~(intptr_t)HAMMER_BUFMASK) == 0);
690                 hammer_generate_undo(trans,
691                                      buffer->zone2_offset + rel_offset,
692                                      base, len);
693         }
694 }
695
696 void
697 hammer_modify_volume_done(hammer_volume_t volume)
698 {
699         hammer_io_modify_done(&volume->io);
700 }
701
702 void
703 hammer_modify_buffer_done(hammer_buffer_t buffer)
704 {
705         hammer_io_modify_done(&buffer->io);
706 }
707
708 /*
709  * Mark an entity as not being dirty any more and finalize any
710  * delayed adjustments to the buffer.
711  *
712  * Delayed adjustments are an important performance enhancement, allowing
713  * us to avoid recalculating B-Tree node CRCs over and over again when
714  * making bulk-modifications to the B-Tree.
715  *
716  * If inval is non-zero delayed adjustments are ignored.
717  *
718  * This routine may dereference related btree nodes and cause the
719  * buffer to be dereferenced.  The caller must own a reference on io.
720  */
721 void
722 hammer_io_clear_modify(struct hammer_io *io, int inval)
723 {
724         if (io->modified == 0)
725                 return;
726
727         /*
728          * Take us off the mod-list and clear the modified bit.
729          */
730         KKASSERT(io->mod_list != NULL);
731         if (io->mod_list == &io->hmp->volu_list ||
732             io->mod_list == &io->hmp->meta_list) {
733                 io->hmp->locked_dirty_space -= io->bytes;
734                 hammer_count_dirtybufspace -= io->bytes;
735         }
736         TAILQ_REMOVE(io->mod_list, io, mod_entry);
737         io->mod_list = NULL;
738         io->modified = 0;
739
740         /*
741          * If this bit is not set there are no delayed adjustments.
742          */
743         if (io->gencrc == 0)
744                 return;
745         io->gencrc = 0;
746
747         /*
748          * Finalize requested CRCs.  The NEEDSCRC flag also holds a reference
749          * on the node (& underlying buffer).  Release the node after clearing
750          * the flag.
751          */
752         if (io->type == HAMMER_STRUCTURE_META_BUFFER) {
753                 hammer_buffer_t buffer = (void *)io;
754                 hammer_node_t node;
755
756 restart:
757                 TAILQ_FOREACH(node, &buffer->clist, entry) {
758                         if ((node->flags & HAMMER_NODE_NEEDSCRC) == 0)
759                                 continue;
760                         node->flags &= ~HAMMER_NODE_NEEDSCRC;
761                         KKASSERT(node->ondisk);
762                         if (inval == 0)
763                                 node->ondisk->crc = crc32(&node->ondisk->crc + 1, HAMMER_BTREE_CRCSIZE);
764                         hammer_rel_node(node);
765                         goto restart;
766                 }
767         }
768         /* caller must still have ref on io */
769         KKASSERT(io->lock.refs > 0);
770 }
771
772 /*
773  * Clear the IO's modify list.  Even though the IO is no longer modified
774  * it may still be on the lose_list.  This routine is called just before
775  * the governing hammer_buffer is destroyed.
776  */
777 void
778 hammer_io_clear_modlist(struct hammer_io *io)
779 {
780         KKASSERT(io->modified == 0);
781         if (io->mod_list) {
782                 crit_enter();   /* biodone race against list */
783                 KKASSERT(io->mod_list == &io->hmp->lose_list);
784                 TAILQ_REMOVE(io->mod_list, io, mod_entry);
785                 io->mod_list = NULL;
786                 crit_exit();
787         }
788 }
789
790 static void
791 hammer_io_set_modlist(struct hammer_io *io)
792 {
793         struct hammer_mount *hmp = io->hmp;
794
795         KKASSERT(io->mod_list == NULL);
796
797         switch(io->type) {
798         case HAMMER_STRUCTURE_VOLUME:
799                 io->mod_list = &hmp->volu_list;
800                 hmp->locked_dirty_space += io->bytes;
801                 hammer_count_dirtybufspace += io->bytes;
802                 break;
803         case HAMMER_STRUCTURE_META_BUFFER:
804                 io->mod_list = &hmp->meta_list;
805                 hmp->locked_dirty_space += io->bytes;
806                 hammer_count_dirtybufspace += io->bytes;
807                 break;
808         case HAMMER_STRUCTURE_UNDO_BUFFER:
809                 io->mod_list = &hmp->undo_list;
810                 break;
811         case HAMMER_STRUCTURE_DATA_BUFFER:
812                 io->mod_list = &hmp->data_list;
813                 break;
814         }
815         TAILQ_INSERT_TAIL(io->mod_list, io, mod_entry);
816 }
817
818 /************************************************************************
819  *                              HAMMER_BIOOPS                           *
820  ************************************************************************
821  *
822  */
823
824 /*
825  * Pre-IO initiation kernel callback - cluster build only
826  */
827 static void
828 hammer_io_start(struct buf *bp)
829 {
830 }
831
832 /*
833  * Post-IO completion kernel callback - MAY BE CALLED FROM INTERRUPT!
834  *
835  * NOTE: HAMMER may modify a buffer after initiating I/O.  The modified bit
836  * may also be set if we were marking a cluster header open.  Only remove
837  * our dependancy if the modified bit is clear.
838  */
839 static void
840 hammer_io_complete(struct buf *bp)
841 {
842         union hammer_io_structure *iou = (void *)LIST_FIRST(&bp->b_dep);
843
844         KKASSERT(iou->io.released == 1);
845
846         /*
847          * Deal with people waiting for I/O to drain
848          */
849         if (iou->io.running) {
850                 /*
851                  * Deal with critical write errors.  Once a critical error
852                  * has been flagged in hmp the UNDO FIFO will not be updated.
853                  * That way crash recover will give us a consistent
854                  * filesystem.
855                  *
856                  * Because of this we can throw away failed UNDO buffers.  If
857                  * we throw away META or DATA buffers we risk corrupting
858                  * the now read-only version of the filesystem visible to
859                  * the user.  Clear B_ERROR so the buffer is not re-dirtied
860                  * by the kernel and ref the io so it doesn't get thrown
861                  * away.
862                  */
863                 if (bp->b_flags & B_ERROR) {
864                         hammer_critical_error(iou->io.hmp, NULL, bp->b_error,
865                                               "while flushing meta-data");
866                         switch(iou->io.type) {
867                         case HAMMER_STRUCTURE_UNDO_BUFFER:
868                                 break;
869                         default:
870                                 if (iou->io.ioerror == 0) {
871                                         iou->io.ioerror = 1;
872                                         if (iou->io.lock.refs == 0)
873                                                 ++hammer_count_refedbufs;
874                                         hammer_ref(&iou->io.lock);
875                                 }
876                                 break;
877                         }
878                         bp->b_flags &= ~B_ERROR;
879                         bundirty(bp);
880 #if 0
881                         hammer_io_set_modlist(&iou->io);
882                         iou->io.modified = 1;
883 #endif
884                 }
885                 hammer_stats_disk_write += iou->io.bytes;
886                 hammer_count_io_running_write -= iou->io.bytes;
887                 iou->io.hmp->io_running_space -= iou->io.bytes;
888                 if (iou->io.hmp->io_running_space == 0)
889                         wakeup(&iou->io.hmp->io_running_space);
890                 KKASSERT(iou->io.hmp->io_running_space >= 0);
891                 iou->io.running = 0;
892         } else {
893                 hammer_stats_disk_read += iou->io.bytes;
894         }
895
896         if (iou->io.waiting) {
897                 iou->io.waiting = 0;
898                 wakeup(iou);
899         }
900
901         /*
902          * If B_LOCKED is set someone wanted to deallocate the bp at some
903          * point, do it now if refs has become zero.
904          */
905         if ((bp->b_flags & B_LOCKED) && iou->io.lock.refs == 0) {
906                 KKASSERT(iou->io.modified == 0);
907                 --hammer_count_io_locked;
908                 bp->b_flags &= ~B_LOCKED;
909                 hammer_io_deallocate(bp);
910                 /* structure may be dead now */
911         }
912 }
913
914 /*
915  * Callback from kernel when it wishes to deallocate a passively
916  * associated structure.  This mostly occurs with clean buffers
917  * but it may be possible for a holding structure to be marked dirty
918  * while its buffer is passively associated.  The caller owns the bp.
919  *
920  * If we cannot disassociate we set B_LOCKED to prevent the buffer
921  * from getting reused.
922  *
923  * WARNING: Because this can be called directly by getnewbuf we cannot
924  * recurse into the tree.  If a bp cannot be immediately disassociated
925  * our only recourse is to set B_LOCKED.
926  *
927  * WARNING: This may be called from an interrupt via hammer_io_complete()
928  */
929 static void
930 hammer_io_deallocate(struct buf *bp)
931 {
932         hammer_io_structure_t iou = (void *)LIST_FIRST(&bp->b_dep);
933
934         KKASSERT((bp->b_flags & B_LOCKED) == 0 && iou->io.running == 0);
935         if (iou->io.lock.refs > 0 || iou->io.modified) {
936                 /*
937                  * It is not legal to disassociate a modified buffer.  This
938                  * case really shouldn't ever occur.
939                  */
940                 bp->b_flags |= B_LOCKED;
941                 ++hammer_count_io_locked;
942         } else {
943                 /*
944                  * Disassociate the BP.  If the io has no refs left we
945                  * have to add it to the loose list.
946                  */
947                 hammer_io_disassociate(iou);
948                 if (iou->io.type != HAMMER_STRUCTURE_VOLUME) {
949                         KKASSERT(iou->io.bp == NULL);
950                         KKASSERT(iou->io.mod_list == NULL);
951                         crit_enter();   /* biodone race against list */
952                         iou->io.mod_list = &iou->io.hmp->lose_list;
953                         TAILQ_INSERT_TAIL(iou->io.mod_list, &iou->io, mod_entry);
954                         crit_exit();
955                 }
956         }
957 }
958
959 static int
960 hammer_io_fsync(struct vnode *vp)
961 {
962         return(0);
963 }
964
965 /*
966  * NOTE: will not be called unless we tell the kernel about the
967  * bioops.  Unused... we use the mount's VFS_SYNC instead.
968  */
969 static int
970 hammer_io_sync(struct mount *mp)
971 {
972         return(0);
973 }
974
975 static void
976 hammer_io_movedeps(struct buf *bp1, struct buf *bp2)
977 {
978 }
979
980 /*
981  * I/O pre-check for reading and writing.  HAMMER only uses this for
982  * B_CACHE buffers so checkread just shouldn't happen, but if it does
983  * allow it.
984  *
985  * Writing is a different case.  We don't want the kernel to try to write
986  * out a buffer that HAMMER may be modifying passively or which has a
987  * dependancy.  In addition, kernel-demanded writes can only proceed for
988  * certain types of buffers (i.e. UNDO and DATA types).  Other dirty
989  * buffer types can only be explicitly written by the flusher.
990  *
991  * checkwrite will only be called for bdwrite()n buffers.  If we return
992  * success the kernel is guaranteed to initiate the buffer write.
993  */
994 static int
995 hammer_io_checkread(struct buf *bp)
996 {
997         return(0);
998 }
999
1000 static int
1001 hammer_io_checkwrite(struct buf *bp)
1002 {
1003         hammer_io_t io = (void *)LIST_FIRST(&bp->b_dep);
1004
1005         /*
1006          * This shouldn't happen under normal operation.
1007          */
1008         if (io->type == HAMMER_STRUCTURE_VOLUME ||
1009             io->type == HAMMER_STRUCTURE_META_BUFFER) {
1010                 if (!panicstr)
1011                         panic("hammer_io_checkwrite: illegal buffer");
1012                 if ((bp->b_flags & B_LOCKED) == 0) {
1013                         bp->b_flags |= B_LOCKED;
1014                         ++hammer_count_io_locked;
1015                 }
1016                 return(1);
1017         }
1018
1019         /*
1020          * We can only clear the modified bit if the IO is not currently
1021          * undergoing modification.  Otherwise we may miss changes.
1022          *
1023          * Only data and undo buffers can reach here.  These buffers do
1024          * not have terminal crc functions but we temporarily reference
1025          * the IO anyway, just in case.
1026          */
1027         if (io->modify_refs == 0 && io->modified) {
1028                 hammer_ref(&io->lock);
1029                 hammer_io_clear_modify(io, 0);
1030                 hammer_unref(&io->lock);
1031         } else if (io->modified) {
1032                 KKASSERT(io->type == HAMMER_STRUCTURE_DATA_BUFFER);
1033         }
1034
1035         /*
1036          * The kernel is going to start the IO, set io->running.
1037          */
1038         KKASSERT(io->running == 0);
1039         io->running = 1;
1040         io->hmp->io_running_space += io->bytes;
1041         hammer_count_io_running_write += io->bytes;
1042         return(0);
1043 }
1044
1045 /*
1046  * Return non-zero if we wish to delay the kernel's attempt to flush
1047  * this buffer to disk.
1048  */
1049 static int
1050 hammer_io_countdeps(struct buf *bp, int n)
1051 {
1052         return(0);
1053 }
1054
1055 struct bio_ops hammer_bioops = {
1056         .io_start       = hammer_io_start,
1057         .io_complete    = hammer_io_complete,
1058         .io_deallocate  = hammer_io_deallocate,
1059         .io_fsync       = hammer_io_fsync,
1060         .io_sync        = hammer_io_sync,
1061         .io_movedeps    = hammer_io_movedeps,
1062         .io_countdeps   = hammer_io_countdeps,
1063         .io_checkread   = hammer_io_checkread,
1064         .io_checkwrite  = hammer_io_checkwrite,
1065 };
1066
1067 /************************************************************************
1068  *                              DIRECT IO OPS                           *
1069  ************************************************************************
1070  *
1071  * These functions operate directly on the buffer cache buffer associated
1072  * with a front-end vnode rather then a back-end device vnode.
1073  */
1074
1075 /*
1076  * Read a buffer associated with a front-end vnode directly from the
1077  * disk media.  The bio may be issued asynchronously.  If leaf is non-NULL
1078  * we validate the CRC.
1079  *
1080  * We must check for the presence of a HAMMER buffer to handle the case
1081  * where the reblocker has rewritten the data (which it does via the HAMMER
1082  * buffer system, not via the high-level vnode buffer cache), but not yet
1083  * committed the buffer to the media. 
1084  */
1085 int
1086 hammer_io_direct_read(hammer_mount_t hmp, struct bio *bio,
1087                       hammer_btree_leaf_elm_t leaf)
1088 {
1089         hammer_off_t buf_offset;
1090         hammer_off_t zone2_offset;
1091         hammer_volume_t volume;
1092         struct buf *bp;
1093         struct bio *nbio;
1094         int vol_no;
1095         int error;
1096
1097         buf_offset = bio->bio_offset;
1098         KKASSERT((buf_offset & HAMMER_OFF_ZONE_MASK) ==
1099                  HAMMER_ZONE_LARGE_DATA);
1100
1101         /*
1102          * The buffer cache may have an aliased buffer (the reblocker can
1103          * write them).  If it does we have to sync any dirty data before
1104          * we can build our direct-read.  This is a non-critical code path.
1105          */
1106         bp = bio->bio_buf;
1107         hammer_sync_buffers(hmp, buf_offset, bp->b_bufsize);
1108
1109         /*
1110          * Resolve to a zone-2 offset.  The conversion just requires
1111          * munging the top 4 bits but we want to abstract it anyway
1112          * so the blockmap code can verify the zone assignment.
1113          */
1114         zone2_offset = hammer_blockmap_lookup(hmp, buf_offset, &error);
1115         if (error)
1116                 goto done;
1117         KKASSERT((zone2_offset & HAMMER_OFF_ZONE_MASK) ==
1118                  HAMMER_ZONE_RAW_BUFFER);
1119
1120         /*
1121          * Resolve volume and raw-offset for 3rd level bio.  The
1122          * offset will be specific to the volume.
1123          */
1124         vol_no = HAMMER_VOL_DECODE(zone2_offset);
1125         volume = hammer_get_volume(hmp, vol_no, &error);
1126         if (error == 0 && zone2_offset >= volume->maxbuf_off)
1127                 error = EIO;
1128
1129         if (error == 0) {
1130                 /*
1131                  * 3rd level bio
1132                  */
1133                 nbio = push_bio(bio);
1134                 nbio->bio_offset = volume->ondisk->vol_buf_beg +
1135                                    (zone2_offset & HAMMER_OFF_SHORT_MASK);
1136 #if 0
1137                 /*
1138                  * XXX disabled - our CRC check doesn't work if the OS
1139                  * does bogus_page replacement on the direct-read.
1140                  */
1141                 if (leaf && hammer_verify_data) {
1142                         nbio->bio_done = hammer_io_direct_read_complete;
1143                         nbio->bio_caller_info1.uvalue32 = leaf->data_crc;
1144                 }
1145 #endif
1146                 hammer_stats_disk_read += bp->b_bufsize;
1147                 vn_strategy(volume->devvp, nbio);
1148         }
1149         hammer_rel_volume(volume, 0);
1150 done:
1151         if (error) {
1152                 kprintf("hammer_direct_read: failed @ %016llx\n",
1153                         (long long)zone2_offset);
1154                 bp->b_error = error;
1155                 bp->b_flags |= B_ERROR;
1156                 biodone(bio);
1157         }
1158         return(error);
1159 }
1160
1161 #if 0
1162 /*
1163  * On completion of the BIO this callback must check the data CRC
1164  * and chain to the previous bio.
1165  */
1166 static
1167 void
1168 hammer_io_direct_read_complete(struct bio *nbio)
1169 {
1170         struct bio *obio;
1171         struct buf *bp;
1172         u_int32_t rec_crc = nbio->bio_caller_info1.uvalue32;
1173
1174         bp = nbio->bio_buf;
1175         if (crc32(bp->b_data, bp->b_bufsize) != rec_crc) {
1176                 kprintf("HAMMER: data_crc error @%016llx/%d\n",
1177                         nbio->bio_offset, bp->b_bufsize);
1178                 if (hammer_debug_critical)
1179                         Debugger("data_crc on read");
1180                 bp->b_flags |= B_ERROR;
1181                 bp->b_error = EIO;
1182         }
1183         obio = pop_bio(nbio);
1184         biodone(obio);
1185 }
1186 #endif
1187
1188 /*
1189  * Write a buffer associated with a front-end vnode directly to the
1190  * disk media.  The bio may be issued asynchronously.
1191  *
1192  * The BIO is associated with the specified record and RECF_DIRECT_IO
1193  * is set.  The recorded is added to its object.
1194  */
1195 int
1196 hammer_io_direct_write(hammer_mount_t hmp, hammer_record_t record,
1197                        struct bio *bio)
1198 {
1199         hammer_btree_leaf_elm_t leaf = &record->leaf;
1200         hammer_off_t buf_offset;
1201         hammer_off_t zone2_offset;
1202         hammer_volume_t volume;
1203         hammer_buffer_t buffer;
1204         struct buf *bp;
1205         struct bio *nbio;
1206         char *ptr;
1207         int vol_no;
1208         int error;
1209
1210         buf_offset = leaf->data_offset;
1211
1212         KKASSERT(buf_offset > HAMMER_ZONE_BTREE);
1213         KKASSERT(bio->bio_buf->b_cmd == BUF_CMD_WRITE);
1214
1215         if ((buf_offset & HAMMER_BUFMASK) == 0 &&
1216             leaf->data_len >= HAMMER_BUFSIZE) {
1217                 /*
1218                  * We are using the vnode's bio to write directly to the
1219                  * media, any hammer_buffer at the same zone-X offset will
1220                  * now have stale data.
1221                  */
1222                 zone2_offset = hammer_blockmap_lookup(hmp, buf_offset, &error);
1223                 vol_no = HAMMER_VOL_DECODE(zone2_offset);
1224                 volume = hammer_get_volume(hmp, vol_no, &error);
1225
1226                 if (error == 0 && zone2_offset >= volume->maxbuf_off)
1227                         error = EIO;
1228                 if (error == 0) {
1229                         bp = bio->bio_buf;
1230                         KKASSERT((bp->b_bufsize & HAMMER_BUFMASK) == 0);
1231                         /*
1232                         hammer_del_buffers(hmp, buf_offset,
1233                                            zone2_offset, bp->b_bufsize);
1234                         */
1235
1236                         /*
1237                          * Second level bio - cached zone2 offset.
1238                          *
1239                          * (We can put our bio_done function in either the
1240                          *  2nd or 3rd level).
1241                          */
1242                         nbio = push_bio(bio);
1243                         nbio->bio_offset = zone2_offset;
1244                         nbio->bio_done = hammer_io_direct_write_complete;
1245                         nbio->bio_caller_info1.ptr = record;
1246                         record->zone2_offset = zone2_offset;
1247                         record->flags |= HAMMER_RECF_DIRECT_IO |
1248                                          HAMMER_RECF_DIRECT_INVAL;
1249
1250                         /*
1251                          * Third level bio - raw offset specific to the
1252                          * correct volume.
1253                          */
1254                         zone2_offset &= HAMMER_OFF_SHORT_MASK;
1255                         nbio = push_bio(nbio);
1256                         nbio->bio_offset = volume->ondisk->vol_buf_beg +
1257                                            zone2_offset;
1258                         hammer_stats_disk_write += bp->b_bufsize;
1259                         vn_strategy(volume->devvp, nbio);
1260                         hammer_io_flush_mark(volume);
1261                 }
1262                 hammer_rel_volume(volume, 0);
1263         } else {
1264                 /* 
1265                  * Must fit in a standard HAMMER buffer.  In this case all
1266                  * consumers use the HAMMER buffer system and RECF_DIRECT_IO
1267                  * does not need to be set-up.
1268                  */
1269                 KKASSERT(((buf_offset ^ (buf_offset + leaf->data_len - 1)) & ~HAMMER_BUFMASK64) == 0);
1270                 buffer = NULL;
1271                 ptr = hammer_bread(hmp, buf_offset, &error, &buffer);
1272                 if (error == 0) {
1273                         bp = bio->bio_buf;
1274                         bp->b_flags |= B_AGE;
1275                         hammer_io_modify(&buffer->io, 1);
1276                         bcopy(bp->b_data, ptr, leaf->data_len);
1277                         hammer_io_modify_done(&buffer->io);
1278                         hammer_rel_buffer(buffer, 0);
1279                         bp->b_resid = 0;
1280                         biodone(bio);
1281                 }
1282         }
1283         if (error == 0) {
1284                 /*
1285                  * The record is all setup now, add it.  Potential conflics
1286                  * have already been dealt with.
1287                  */
1288                 error = hammer_mem_add(record);
1289                 KKASSERT(error == 0);
1290         } else {
1291                 /*
1292                  * Major suckage occured.  Also note:  The record was never added
1293                  * to the tree so we do not have to worry about the backend.
1294                  */
1295                 kprintf("hammer_direct_write: failed @ %016llx\n",
1296                         (long long)leaf->data_offset);
1297                 bp = bio->bio_buf;
1298                 bp->b_resid = 0;
1299                 bp->b_error = EIO;
1300                 bp->b_flags |= B_ERROR;
1301                 biodone(bio);
1302                 record->flags |= HAMMER_RECF_DELETED_FE;
1303                 hammer_rel_mem_record(record);
1304         }
1305         return(error);
1306 }
1307
1308 /*
1309  * On completion of the BIO this callback must disconnect
1310  * it from the hammer_record and chain to the previous bio.
1311  *
1312  * An I/O error forces the mount to read-only.  Data buffers
1313  * are not B_LOCKED like meta-data buffers are, so we have to
1314  * throw the buffer away to prevent the kernel from retrying.
1315  */
1316 static
1317 void
1318 hammer_io_direct_write_complete(struct bio *nbio)
1319 {
1320         struct bio *obio;
1321         struct buf *bp;
1322         hammer_record_t record = nbio->bio_caller_info1.ptr;
1323
1324         bp = nbio->bio_buf;
1325         obio = pop_bio(nbio);
1326         if (bp->b_flags & B_ERROR) {
1327                 hammer_critical_error(record->ip->hmp, record->ip,
1328                                       bp->b_error,
1329                                       "while writing bulk data");
1330                 bp->b_flags |= B_INVAL;
1331         }
1332         biodone(obio);
1333
1334         KKASSERT(record != NULL);
1335         KKASSERT(record->flags & HAMMER_RECF_DIRECT_IO);
1336         if (record->flags & HAMMER_RECF_DIRECT_WAIT) {
1337                 record->flags &= ~(HAMMER_RECF_DIRECT_IO |
1338                                    HAMMER_RECF_DIRECT_WAIT);
1339                 /* record can disappear once DIRECT_IO flag is cleared */
1340                 wakeup(&record->flags);
1341         } else {
1342                 record->flags &= ~HAMMER_RECF_DIRECT_IO;
1343                 /* record can disappear once DIRECT_IO flag is cleared */
1344         }
1345 }
1346
1347
1348 /*
1349  * This is called before a record is either committed to the B-Tree
1350  * or destroyed, to resolve any associated direct-IO. 
1351  *
1352  * (1) We must wait for any direct-IO related to the record to complete.
1353  *
1354  * (2) We must remove any buffer cache aliases for data accessed via
1355  *     leaf->data_offset or zone2_offset so non-direct-IO consumers  
1356  *     (the mirroring and reblocking code) do not see stale data.
1357  */
1358 void
1359 hammer_io_direct_wait(hammer_record_t record)
1360 {
1361         /*
1362          * Wait for I/O to complete
1363          */
1364         if (record->flags & HAMMER_RECF_DIRECT_IO) {
1365                 crit_enter();
1366                 while (record->flags & HAMMER_RECF_DIRECT_IO) {
1367                         record->flags |= HAMMER_RECF_DIRECT_WAIT;
1368                         tsleep(&record->flags, 0, "hmdiow", 0);
1369                 }
1370                 crit_exit();
1371         }
1372
1373         /*
1374          * Invalidate any related buffer cache aliases associated with the
1375          * backing device.  This is needed because the buffer cache buffer
1376          * for file data is associated with the file vnode, not the backing
1377          * device vnode.
1378          *
1379          * XXX I do not think this case can occur any more now that
1380          * reservations ensure that all such buffers are removed before
1381          * an area can be reused.
1382          */
1383         if (record->flags & HAMMER_RECF_DIRECT_INVAL) {
1384                 KKASSERT(record->leaf.data_offset);
1385                 hammer_del_buffers(record->ip->hmp, record->leaf.data_offset,
1386                                    record->zone2_offset, record->leaf.data_len,
1387                                    1);
1388                 record->flags &= ~HAMMER_RECF_DIRECT_INVAL;
1389         }
1390 }
1391
1392 /*
1393  * This is called to remove the second-level cached zone-2 offset from
1394  * frontend buffer cache buffers, now stale due to a data relocation.
1395  * These offsets are generated by cluster_read() via VOP_BMAP, or directly
1396  * by hammer_vop_strategy_read().
1397  *
1398  * This is rather nasty because here we have something like the reblocker
1399  * scanning the raw B-Tree with no held references on anything, really,
1400  * other then a shared lock on the B-Tree node, and we have to access the
1401  * frontend's buffer cache to check for and clean out the association.
1402  * Specifically, if the reblocker is moving data on the disk, these cached
1403  * offsets will become invalid.
1404  *
1405  * Only data record types associated with the large-data zone are subject
1406  * to direct-io and need to be checked.
1407  *
1408  */
1409 void
1410 hammer_io_direct_uncache(hammer_mount_t hmp, hammer_btree_leaf_elm_t leaf)
1411 {
1412         struct hammer_inode_info iinfo;
1413         int zone;
1414
1415         if (leaf->base.rec_type != HAMMER_RECTYPE_DATA)
1416                 return;
1417         zone = HAMMER_ZONE_DECODE(leaf->data_offset);
1418         if (zone != HAMMER_ZONE_LARGE_DATA_INDEX)
1419                 return;
1420         iinfo.obj_id = leaf->base.obj_id;
1421         iinfo.obj_asof = 0;     /* unused */
1422         iinfo.obj_localization = leaf->base.localization &
1423                                  HAMMER_LOCALIZE_PSEUDOFS_MASK;
1424         iinfo.u.leaf = leaf;
1425         hammer_scan_inode_snapshots(hmp, &iinfo,
1426                                     hammer_io_direct_uncache_callback,
1427                                     leaf);
1428 }
1429
1430 static int
1431 hammer_io_direct_uncache_callback(hammer_inode_t ip, void *data)
1432 {
1433         hammer_inode_info_t iinfo = data;
1434         hammer_off_t data_offset;
1435         hammer_off_t file_offset;
1436         struct vnode *vp;
1437         struct buf *bp;
1438         int blksize;
1439
1440         if (ip->vp == NULL)
1441                 return(0);
1442         data_offset = iinfo->u.leaf->data_offset;
1443         file_offset = iinfo->u.leaf->base.key - iinfo->u.leaf->data_len;
1444         blksize = iinfo->u.leaf->data_len;
1445         KKASSERT((blksize & HAMMER_BUFMASK) == 0);
1446
1447         hammer_ref(&ip->lock);
1448         if (hammer_get_vnode(ip, &vp) == 0) {
1449                 if ((bp = findblk(ip->vp, file_offset, FINDBLK_TEST)) != NULL &&
1450                     bp->b_bio2.bio_offset != NOOFFSET) {
1451                         bp = getblk(ip->vp, file_offset, blksize, 0, 0);
1452                         bp->b_bio2.bio_offset = NOOFFSET;
1453                         brelse(bp);
1454                 }
1455                 vput(vp);
1456         }
1457         hammer_rel_inode(ip, 0);
1458         return(0);
1459 }
1460
1461
1462 /*
1463  * This function is called when writes may have occured on the volume,
1464  * indicating that the device may be holding cached writes.
1465  */
1466 static void
1467 hammer_io_flush_mark(hammer_volume_t volume)
1468 {
1469         volume->vol_flags |= HAMMER_VOLF_NEEDFLUSH;
1470 }
1471
1472 /*
1473  * This function ensures that the device has flushed any cached writes out.
1474  */
1475 void
1476 hammer_io_flush_sync(hammer_mount_t hmp)
1477 {
1478         hammer_volume_t volume;
1479         struct buf *bp_base = NULL;
1480         struct buf *bp;
1481
1482         RB_FOREACH(volume, hammer_vol_rb_tree, &hmp->rb_vols_root) {
1483                 if (volume->vol_flags & HAMMER_VOLF_NEEDFLUSH) {
1484                         volume->vol_flags &= ~HAMMER_VOLF_NEEDFLUSH;
1485                         bp = getpbuf(NULL);
1486                         bp->b_bio1.bio_offset = 0;
1487                         bp->b_bufsize = 0;
1488                         bp->b_bcount = 0;
1489                         bp->b_cmd = BUF_CMD_FLUSH;
1490                         bp->b_bio1.bio_caller_info1.cluster_head = bp_base;
1491                         bp->b_bio1.bio_done = biodone_sync;
1492                         bp->b_bio1.bio_flags |= BIO_SYNC;
1493                         bp_base = bp;
1494                         vn_strategy(volume->devvp, &bp->b_bio1);
1495                 }
1496         }
1497         while ((bp = bp_base) != NULL) {
1498                 bp_base = bp->b_bio1.bio_caller_info1.cluster_head;
1499                 biowait(&bp->b_bio1, "hmrFLS");
1500                 relpbuf(bp, NULL);
1501         }
1502 }