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