HAMMER 61F/Many: Stabilization w/ simultanious pruning and reblocking
[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.49 2008/07/14 03:20: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
63 /*
64  * Initialize a new, already-zero'd hammer_io structure, or reinitialize
65  * an existing hammer_io structure which may have switched to another type.
66  */
67 void
68 hammer_io_init(hammer_io_t io, hammer_mount_t hmp, enum hammer_io_type type)
69 {
70         io->hmp = hmp;
71         io->type = type;
72 }
73
74 /*
75  * Helper routine to disassociate a buffer cache buffer from an I/O
76  * structure.  The buffer is unlocked and marked appropriate for reclamation.
77  *
78  * The io may have 0 or 1 references depending on who called us.  The
79  * caller is responsible for dealing with the refs.
80  *
81  * This call can only be made when no action is required on the buffer.
82  *
83  * The caller must own the buffer and the IO must indicate that the
84  * structure no longer owns it (io.released != 0).
85  */
86 static void
87 hammer_io_disassociate(hammer_io_structure_t iou)
88 {
89         struct buf *bp = iou->io.bp;
90
91         KKASSERT(iou->io.released);
92         KKASSERT(iou->io.modified == 0);
93         KKASSERT(LIST_FIRST(&bp->b_dep) == (void *)iou);
94         buf_dep_init(bp);
95         iou->io.bp = NULL;
96
97         /*
98          * If the buffer was locked someone wanted to get rid of it.
99          */
100         if (bp->b_flags & B_LOCKED) {
101                 --hammer_count_io_locked;
102                 bp->b_flags &= ~B_LOCKED;
103         }
104         if (iou->io.reclaim) {
105                 bp->b_flags |= B_NOCACHE|B_RELBUF;
106                 iou->io.reclaim = 0;
107         }
108
109         switch(iou->io.type) {
110         case HAMMER_STRUCTURE_VOLUME:
111                 iou->volume.ondisk = NULL;
112                 break;
113         case HAMMER_STRUCTURE_DATA_BUFFER:
114         case HAMMER_STRUCTURE_META_BUFFER:
115         case HAMMER_STRUCTURE_UNDO_BUFFER:
116                 iou->buffer.ondisk = NULL;
117                 break;
118         }
119 }
120
121 /*
122  * Wait for any physical IO to complete
123  */
124 void
125 hammer_io_wait(hammer_io_t io)
126 {
127         if (io->running) {
128                 crit_enter();
129                 tsleep_interlock(io);
130                 io->waiting = 1;
131                 for (;;) {
132                         tsleep(io, 0, "hmrflw", 0);
133                         if (io->running == 0)
134                                 break;
135                         tsleep_interlock(io);
136                         io->waiting = 1;
137                         if (io->running == 0)
138                                 break;
139                 }
140                 crit_exit();
141         }
142 }
143
144 /*
145  * Wait for all hammer_io-initated write I/O's to complete.  This is not
146  * supposed to count direct I/O's but some can leak through (for
147  * non-full-sized direct I/Os).
148  */
149 void
150 hammer_io_wait_all(hammer_mount_t hmp, const char *ident)
151 {
152         crit_enter();
153         while (hmp->io_running_space)
154                 tsleep(&hmp->io_running_space, 0, ident, 0);
155         crit_exit();
156 }
157
158 #define HAMMER_MAXRA    4
159
160 /*
161  * Load bp for a HAMMER structure.  The io must be exclusively locked by
162  * the caller.
163  *
164  * This routine is mostly used on meta-data and small-data blocks.  Generally
165  * speaking HAMMER assumes some locality of reference and will cluster 
166  * a 64K read.
167  *
168  * Note that clustering occurs at the device layer, not the logical layer.
169  * If the buffers do not apply to the current operation they may apply to
170  * some other.
171  */
172 int
173 hammer_io_read(struct vnode *devvp, struct hammer_io *io, hammer_off_t limit)
174 {
175         struct buf *bp;
176         int   error;
177
178         if ((bp = io->bp) == NULL) {
179                 hammer_count_io_running_read += io->bytes;
180 #if 1
181                 error = cluster_read(devvp, limit, io->offset, io->bytes,
182                                      HAMMER_CLUSTER_SIZE,
183                                      HAMMER_CLUSTER_BUFS, &io->bp);
184 #else
185                 error = bread(devvp, io->offset, io->bytes, &io->bp);
186 #endif
187                 hammer_count_io_running_read -= io->bytes;
188                 if (error == 0) {
189                         bp = io->bp;
190                         bp->b_ops = &hammer_bioops;
191                         KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
192                         LIST_INSERT_HEAD(&bp->b_dep, &io->worklist, node);
193                         BUF_KERNPROC(bp);
194                 }
195                 KKASSERT(io->modified == 0);
196                 KKASSERT(io->running == 0);
197                 KKASSERT(io->waiting == 0);
198                 io->released = 0;       /* we hold an active lock on bp */
199         } else {
200                 error = 0;
201         }
202         return(error);
203 }
204
205 /*
206  * Similar to hammer_io_read() but returns a zero'd out buffer instead.
207  * Must be called with the IO exclusively locked.
208  *
209  * vfs_bio_clrbuf() is kinda nasty, enforce serialization against background
210  * I/O by forcing the buffer to not be in a released state before calling
211  * it.
212  *
213  * This function will also mark the IO as modified but it will not
214  * increment the modify_refs count.
215  */
216 int
217 hammer_io_new(struct vnode *devvp, struct hammer_io *io)
218 {
219         struct buf *bp;
220
221         if ((bp = io->bp) == NULL) {
222                 io->bp = getblk(devvp, io->offset, io->bytes, 0, 0);
223                 bp = io->bp;
224                 bp->b_ops = &hammer_bioops;
225                 KKASSERT(LIST_FIRST(&bp->b_dep) == NULL);
226                 LIST_INSERT_HEAD(&bp->b_dep, &io->worklist, node);
227                 io->released = 0;
228                 KKASSERT(io->running == 0);
229                 io->waiting = 0;
230                 BUF_KERNPROC(bp);
231         } else {
232                 if (io->released) {
233                         regetblk(bp);
234                         BUF_KERNPROC(bp);
235                         io->released = 0;
236                 }
237         }
238         hammer_io_modify(io, 0);
239         vfs_bio_clrbuf(bp);
240         return(0);
241 }
242
243 /*
244  * Remove potential device level aliases against buffers managed by high level
245  * vnodes.
246  */
247 void
248 hammer_io_inval(hammer_volume_t volume, hammer_off_t zone2_offset)
249 {
250         hammer_io_structure_t iou;
251         hammer_off_t phys_offset;
252         struct buf *bp;
253
254         phys_offset = volume->ondisk->vol_buf_beg +
255                       (zone2_offset & HAMMER_OFF_SHORT_MASK);
256         crit_enter();
257         if ((bp = findblk(volume->devvp, phys_offset)) != NULL) {
258                 bp = getblk(volume->devvp, phys_offset, bp->b_bufsize, 0, 0);
259                 if ((iou = (void *)LIST_FIRST(&bp->b_dep)) != NULL) {
260                         hammer_io_clear_modify(&iou->io, 1);
261                         bundirty(bp);
262                         iou->io.reclaim = 1;
263                         hammer_io_deallocate(bp);
264                 } else {
265                         KKASSERT((bp->b_flags & B_LOCKED) == 0);
266                         bundirty(bp);
267                         bp->b_flags |= B_NOCACHE|B_RELBUF;
268                 }
269                 brelse(bp);
270         }
271         crit_exit();
272 }
273
274 /*
275  * This routine is called on the last reference to a hammer structure.
276  * The io is usually interlocked with io.loading and io.refs must be 1.
277  *
278  * This routine may return a non-NULL bp to the caller for dispoal.  Disposal
279  * simply means the caller finishes decrementing the ref-count on the 
280  * IO structure then brelse()'s the bp.  The bp may or may not still be
281  * passively associated with the IO.
282  * 
283  * The only requirement here is that modified meta-data and volume-header
284  * buffer may NOT be disassociated from the IO structure, and consequently
285  * we also leave such buffers actively associated with the IO if they already
286  * are (since the kernel can't do anything with them anyway).  Only the
287  * flusher is allowed to write such buffers out.  Modified pure-data and
288  * undo buffers are returned to the kernel but left passively associated
289  * so we can track when the kernel writes the bp out.
290  */
291 struct buf *
292 hammer_io_release(struct hammer_io *io, int flush)
293 {
294         union hammer_io_structure *iou = (void *)io;
295         struct buf *bp;
296
297         if ((bp = io->bp) == NULL)
298                 return(NULL);
299
300         /*
301          * Try to flush a dirty IO to disk if asked to by the
302          * caller or if the kernel tried to flush the buffer in the past.
303          *
304          * Kernel-initiated flushes are only allowed for pure-data buffers.
305          * meta-data and volume buffers can only be flushed explicitly
306          * by HAMMER.
307          */
308         if (io->modified) {
309                 if (flush) {
310                         hammer_io_flush(io);
311                 } else if (bp->b_flags & B_LOCKED) {
312                         switch(io->type) {
313                         case HAMMER_STRUCTURE_DATA_BUFFER:
314                         case HAMMER_STRUCTURE_UNDO_BUFFER:
315                                 hammer_io_flush(io);
316                                 break;
317                         default:
318                                 break;
319                         }
320                 } /* else no explicit request to flush the buffer */
321         }
322
323         /*
324          * Wait for the IO to complete if asked to.
325          */
326         if (io->waitdep && io->running) {
327                 hammer_io_wait(io);
328         }
329
330         /*
331          * Return control of the buffer to the kernel (with the provisio
332          * that our bioops can override kernel decisions with regards to
333          * the buffer).
334          */
335         if ((flush || io->reclaim) && io->modified == 0 && io->running == 0) {
336                 /*
337                  * Always disassociate the bp if an explicit flush
338                  * was requested and the IO completed with no error
339                  * (so unmount can really clean up the structure).
340                  */
341                 if (io->released) {
342                         regetblk(bp);
343                         BUF_KERNPROC(bp);
344                 } else {
345                         io->released = 1;
346                 }
347                 hammer_io_disassociate((hammer_io_structure_t)io);
348                 /* return the bp */
349         } else if (io->modified) {
350                 /*
351                  * Only certain IO types can be released to the kernel if
352                  * the buffer has been modified.
353                  *
354                  * volume and meta-data IO types may only be explicitly
355                  * flushed by HAMMER.
356                  */
357                 switch(io->type) {
358                 case HAMMER_STRUCTURE_DATA_BUFFER:
359                 case HAMMER_STRUCTURE_UNDO_BUFFER:
360                         if (io->released == 0) {
361                                 io->released = 1;
362                                 bdwrite(bp);
363                         }
364                         break;
365                 default:
366                         break;
367                 }
368                 bp = NULL;      /* bp left associated */
369         } else if (io->released == 0) {
370                 /*
371                  * Clean buffers can be generally released to the kernel.
372                  * We leave the bp passively associated with the HAMMER
373                  * structure and use bioops to disconnect it later on
374                  * if the kernel wants to discard the buffer.
375                  *
376                  * We can steal the structure's ownership of the bp.
377                  */
378                 io->released = 1;
379                 if (bp->b_flags & B_LOCKED) {
380                         hammer_io_disassociate(iou);
381                         /* return the bp */
382                 } else {
383                         if (io->reclaim) {
384                                 hammer_io_disassociate(iou);
385                                 /* return the bp */
386                         } else {
387                                 /* return the bp (bp passively associated) */
388                         }
389                 }
390         } else {
391                 /*
392                  * A released buffer is passively associate with our
393                  * hammer_io structure.  The kernel cannot destroy it
394                  * without making a bioops call.  If the kernel (B_LOCKED)
395                  * or we (reclaim) requested that the buffer be destroyed
396                  * we destroy it, otherwise we do a quick get/release to
397                  * reset its position in the kernel's LRU list.
398                  *
399                  * Leaving the buffer passively associated allows us to
400                  * use the kernel's LRU buffer flushing mechanisms rather
401                  * then rolling our own.
402                  *
403                  * XXX there are two ways of doing this.  We can re-acquire
404                  * and passively release to reset the LRU, or not.
405                  */
406                 if (io->running == 0) {
407                         regetblk(bp);
408                         if ((bp->b_flags & B_LOCKED) || io->reclaim) {
409                                 hammer_io_disassociate(iou);
410                                 /* return the bp */
411                         } else {
412                                 /* return the bp (bp passively associated) */
413                         }
414                 } else {
415                         /*
416                          * bp is left passively associated but we do not
417                          * try to reacquire it.  Interactions with the io
418                          * structure will occur on completion of the bp's
419                          * I/O.
420                          */
421                         bp = NULL;
422                 }
423         }
424         return(bp);
425 }
426
427 /*
428  * This routine is called with a locked IO when a flush is desired and
429  * no other references to the structure exists other then ours.  This
430  * routine is ONLY called when HAMMER believes it is safe to flush a
431  * potentially modified buffer out.
432  */
433 void
434 hammer_io_flush(struct hammer_io *io)
435 {
436         struct buf *bp;
437
438         /*
439          * Degenerate case - nothing to flush if nothing is dirty.
440          */
441         if (io->modified == 0) {
442                 return;
443         }
444
445         KKASSERT(io->bp);
446         KKASSERT(io->modify_refs <= 0);
447
448         /*
449          * Acquire ownership of the bp, particularly before we clear our
450          * modified flag.
451          *
452          * We are going to bawrite() this bp.  Don't leave a window where
453          * io->released is set, we actually own the bp rather then our
454          * buffer.
455          */
456         bp = io->bp;
457         if (io->released) {
458                 regetblk(bp);
459                 /* BUF_KERNPROC(io->bp); */
460                 /* io->released = 0; */
461                 KKASSERT(io->released);
462                 KKASSERT(io->bp == bp);
463         }
464         io->released = 1;
465
466         /*
467          * Acquire exclusive access to the bp and then clear the modified
468          * state of the buffer prior to issuing I/O to interlock any
469          * modifications made while the I/O is in progress.  This shouldn't
470          * happen anyway but losing data would be worse.  The modified bit
471          * will be rechecked after the IO completes.
472          *
473          * NOTE: This call also finalizes the buffer's content (inval == 0).
474          *
475          * This is only legal when lock.refs == 1 (otherwise we might clear
476          * the modified bit while there are still users of the cluster
477          * modifying the data).
478          *
479          * Do this before potentially blocking so any attempt to modify the
480          * ondisk while we are blocked blocks waiting for us.
481          */
482         hammer_io_clear_modify(io, 0);
483
484         /*
485          * Transfer ownership to the kernel and initiate I/O.
486          */
487         io->running = 1;
488         io->hmp->io_running_space += io->bytes;
489         hammer_count_io_running_write += io->bytes;
490         bawrite(bp);
491 }
492
493 /************************************************************************
494  *                              BUFFER DIRTYING                         *
495  ************************************************************************
496  *
497  * These routines deal with dependancies created when IO buffers get
498  * modified.  The caller must call hammer_modify_*() on a referenced
499  * HAMMER structure prior to modifying its on-disk data.
500  *
501  * Any intent to modify an IO buffer acquires the related bp and imposes
502  * various write ordering dependancies.
503  */
504
505 /*
506  * Mark a HAMMER structure as undergoing modification.  Meta-data buffers
507  * are locked until the flusher can deal with them, pure data buffers
508  * can be written out.
509  */
510 static
511 void
512 hammer_io_modify(hammer_io_t io, int count)
513 {
514         struct hammer_mount *hmp = io->hmp;
515
516         /*
517          * io->modify_refs must be >= 0
518          */
519         while (io->modify_refs < 0) {
520                 io->waitmod = 1;
521                 tsleep(io, 0, "hmrmod", 0);
522         }
523
524         /*
525          * Shortcut if nothing to do.
526          */
527         KKASSERT(io->lock.refs != 0 && io->bp != NULL);
528         io->modify_refs += count;
529         if (io->modified && io->released == 0)
530                 return;
531
532         hammer_lock_ex(&io->lock);
533         if (io->modified == 0) {
534                 KKASSERT(io->mod_list == NULL);
535                 switch(io->type) {
536                 case HAMMER_STRUCTURE_VOLUME:
537                         io->mod_list = &hmp->volu_list;
538                         hmp->locked_dirty_space += io->bytes;
539                         hammer_count_dirtybufspace += io->bytes;
540                         break;
541                 case HAMMER_STRUCTURE_META_BUFFER:
542                         io->mod_list = &hmp->meta_list;
543                         hmp->locked_dirty_space += io->bytes;
544                         hammer_count_dirtybufspace += io->bytes;
545                         break;
546                 case HAMMER_STRUCTURE_UNDO_BUFFER:
547                         io->mod_list = &hmp->undo_list;
548                         break;
549                 case HAMMER_STRUCTURE_DATA_BUFFER:
550                         io->mod_list = &hmp->data_list;
551                         break;
552                 }
553                 TAILQ_INSERT_TAIL(io->mod_list, io, mod_entry);
554                 io->modified = 1;
555         }
556         if (io->released) {
557                 regetblk(io->bp);
558                 BUF_KERNPROC(io->bp);
559                 io->released = 0;
560                 KKASSERT(io->modified != 0);
561         }
562         hammer_unlock(&io->lock);
563 }
564
565 static __inline
566 void
567 hammer_io_modify_done(hammer_io_t io)
568 {
569         KKASSERT(io->modify_refs > 0);
570         --io->modify_refs;
571         if (io->modify_refs == 0 && io->waitmod) {
572                 io->waitmod = 0;
573                 wakeup(io);
574         }
575 }
576
577 void
578 hammer_io_write_interlock(hammer_io_t io)
579 {
580         while (io->modify_refs != 0) {
581                 io->waitmod = 1;
582                 tsleep(io, 0, "hmrmod", 0);
583         }
584         io->modify_refs = -1;
585 }
586
587 void
588 hammer_io_done_interlock(hammer_io_t io)
589 {
590         KKASSERT(io->modify_refs == -1);
591         io->modify_refs = 0;
592         if (io->waitmod) {
593                 io->waitmod = 0;
594                 wakeup(io);
595         }
596 }
597
598 /*
599  * Caller intends to modify a volume's ondisk structure.
600  *
601  * This is only allowed if we are the flusher or we have a ref on the
602  * sync_lock.
603  */
604 void
605 hammer_modify_volume(hammer_transaction_t trans, hammer_volume_t volume,
606                      void *base, int len)
607 {
608         KKASSERT (trans == NULL || trans->sync_lock_refs > 0);
609
610         hammer_io_modify(&volume->io, 1);
611         if (len) {
612                 intptr_t rel_offset = (intptr_t)base - (intptr_t)volume->ondisk;
613                 KKASSERT((rel_offset & ~(intptr_t)HAMMER_BUFMASK) == 0);
614                 hammer_generate_undo(trans, &volume->io,
615                          HAMMER_ENCODE_RAW_VOLUME(volume->vol_no, rel_offset),
616                          base, len);
617         }
618 }
619
620 /*
621  * Caller intends to modify a buffer's ondisk structure.
622  *
623  * This is only allowed if we are the flusher or we have a ref on the
624  * sync_lock.
625  */
626 void
627 hammer_modify_buffer(hammer_transaction_t trans, hammer_buffer_t buffer,
628                      void *base, int len)
629 {
630         KKASSERT (trans == NULL || trans->sync_lock_refs > 0);
631
632         hammer_io_modify(&buffer->io, 1);
633         if (len) {
634                 intptr_t rel_offset = (intptr_t)base - (intptr_t)buffer->ondisk;
635                 KKASSERT((rel_offset & ~(intptr_t)HAMMER_BUFMASK) == 0);
636                 hammer_generate_undo(trans, &buffer->io,
637                                      buffer->zone2_offset + rel_offset,
638                                      base, len);
639         }
640 }
641
642 void
643 hammer_modify_volume_done(hammer_volume_t volume)
644 {
645         hammer_io_modify_done(&volume->io);
646 }
647
648 void
649 hammer_modify_buffer_done(hammer_buffer_t buffer)
650 {
651         hammer_io_modify_done(&buffer->io);
652 }
653
654 /*
655  * Mark an entity as not being dirty any more and finalize any
656  * delayed adjustments to the buffer.
657  *
658  * Delayed adjustments are an important performance enhancement, allowing
659  * us to avoid recalculating B-Tree node CRCs over and over again when
660  * making bulk-modifications to the B-Tree.
661  *
662  * If inval is non-zero delayed adjustments are ignored.
663  */
664 void
665 hammer_io_clear_modify(struct hammer_io *io, int inval)
666 {
667         if (io->modified == 0)
668                 return;
669
670         /*
671          * Take us off the mod-list and clear the modified bit.
672          */
673         KKASSERT(io->mod_list != NULL);
674         if (io->mod_list == &io->hmp->volu_list ||
675             io->mod_list == &io->hmp->meta_list) {
676                 io->hmp->locked_dirty_space -= io->bytes;
677                 hammer_count_dirtybufspace -= io->bytes;
678         }
679         TAILQ_REMOVE(io->mod_list, io, mod_entry);
680         io->mod_list = NULL;
681         io->modified = 0;
682
683         /*
684          * If this bit is not set there are no delayed adjustments.
685          */
686         if (io->gencrc == 0)
687                 return;
688         io->gencrc = 0;
689
690         /*
691          * Finalize requested CRCs.  The NEEDSCRC flag also holds a reference
692          * on the node (& underlying buffer).  Release the node after clearing
693          * the flag.
694          */
695         if (io->type == HAMMER_STRUCTURE_META_BUFFER) {
696                 hammer_buffer_t buffer = (void *)io;
697                 hammer_node_t node;
698
699 restart:
700                 TAILQ_FOREACH(node, &buffer->clist, entry) {
701                         if ((node->flags & HAMMER_NODE_NEEDSCRC) == 0)
702                                 continue;
703                         node->flags &= ~HAMMER_NODE_NEEDSCRC;
704                         KKASSERT(node->ondisk);
705                         if (inval == 0)
706                                 node->ondisk->crc = crc32(&node->ondisk->crc + 1, HAMMER_BTREE_CRCSIZE);
707                         hammer_rel_node(node);
708                         goto restart;
709                 }
710         }
711
712 }
713
714 /*
715  * Clear the IO's modify list.  Even though the IO is no longer modified
716  * it may still be on the lose_list.  This routine is called just before
717  * the governing hammer_buffer is destroyed.
718  */
719 void
720 hammer_io_clear_modlist(struct hammer_io *io)
721 {
722         KKASSERT(io->modified == 0);
723         if (io->mod_list) {
724                 crit_enter();   /* biodone race against list */
725                 KKASSERT(io->mod_list == &io->hmp->lose_list);
726                 TAILQ_REMOVE(io->mod_list, io, mod_entry);
727                 io->mod_list = NULL;
728                 crit_exit();
729         }
730 }
731
732 /************************************************************************
733  *                              HAMMER_BIOOPS                           *
734  ************************************************************************
735  *
736  */
737
738 /*
739  * Pre-IO initiation kernel callback - cluster build only
740  */
741 static void
742 hammer_io_start(struct buf *bp)
743 {
744 }
745
746 /*
747  * Post-IO completion kernel callback - MAY BE CALLED FROM INTERRUPT!
748  *
749  * NOTE: HAMMER may modify a buffer after initiating I/O.  The modified bit
750  * may also be set if we were marking a cluster header open.  Only remove
751  * our dependancy if the modified bit is clear.
752  */
753 static void
754 hammer_io_complete(struct buf *bp)
755 {
756         union hammer_io_structure *iou = (void *)LIST_FIRST(&bp->b_dep);
757
758         KKASSERT(iou->io.released == 1);
759
760         /*
761          * Deal with people waiting for I/O to drain
762          */
763         if (iou->io.running) {
764                 hammer_count_io_running_write -= iou->io.bytes;
765                 iou->io.hmp->io_running_space -= iou->io.bytes;
766                 if (iou->io.hmp->io_running_space == 0)
767                         wakeup(&iou->io.hmp->io_running_space);
768                 KKASSERT(iou->io.hmp->io_running_space >= 0);
769                 iou->io.running = 0;
770         }
771
772         if (iou->io.waiting) {
773                 iou->io.waiting = 0;
774                 wakeup(iou);
775         }
776
777         /*
778          * If B_LOCKED is set someone wanted to deallocate the bp at some
779          * point, do it now if refs has become zero.
780          */
781         if ((bp->b_flags & B_LOCKED) && iou->io.lock.refs == 0) {
782                 KKASSERT(iou->io.modified == 0);
783                 --hammer_count_io_locked;
784                 bp->b_flags &= ~B_LOCKED;
785                 hammer_io_deallocate(bp);
786                 /* structure may be dead now */
787         }
788 }
789
790 /*
791  * Callback from kernel when it wishes to deallocate a passively
792  * associated structure.  This mostly occurs with clean buffers
793  * but it may be possible for a holding structure to be marked dirty
794  * while its buffer is passively associated.  The caller owns the bp.
795  *
796  * If we cannot disassociate we set B_LOCKED to prevent the buffer
797  * from getting reused.
798  *
799  * WARNING: Because this can be called directly by getnewbuf we cannot
800  * recurse into the tree.  If a bp cannot be immediately disassociated
801  * our only recourse is to set B_LOCKED.
802  *
803  * WARNING: This may be called from an interrupt via hammer_io_complete()
804  */
805 static void
806 hammer_io_deallocate(struct buf *bp)
807 {
808         hammer_io_structure_t iou = (void *)LIST_FIRST(&bp->b_dep);
809
810         KKASSERT((bp->b_flags & B_LOCKED) == 0 && iou->io.running == 0);
811         if (iou->io.lock.refs > 0 || iou->io.modified) {
812                 /*
813                  * It is not legal to disassociate a modified buffer.  This
814                  * case really shouldn't ever occur.
815                  */
816                 bp->b_flags |= B_LOCKED;
817                 ++hammer_count_io_locked;
818         } else {
819                 /*
820                  * Disassociate the BP.  If the io has no refs left we
821                  * have to add it to the loose list.
822                  */
823                 hammer_io_disassociate(iou);
824                 if (iou->io.type != HAMMER_STRUCTURE_VOLUME) {
825                         KKASSERT(iou->io.bp == NULL);
826                         KKASSERT(iou->io.mod_list == NULL);
827                         crit_enter();   /* biodone race against list */
828                         iou->io.mod_list = &iou->io.hmp->lose_list;
829                         TAILQ_INSERT_TAIL(iou->io.mod_list, &iou->io, mod_entry);
830                         crit_exit();
831                 }
832         }
833 }
834
835 static int
836 hammer_io_fsync(struct vnode *vp)
837 {
838         return(0);
839 }
840
841 /*
842  * NOTE: will not be called unless we tell the kernel about the
843  * bioops.  Unused... we use the mount's VFS_SYNC instead.
844  */
845 static int
846 hammer_io_sync(struct mount *mp)
847 {
848         return(0);
849 }
850
851 static void
852 hammer_io_movedeps(struct buf *bp1, struct buf *bp2)
853 {
854 }
855
856 /*
857  * I/O pre-check for reading and writing.  HAMMER only uses this for
858  * B_CACHE buffers so checkread just shouldn't happen, but if it does
859  * allow it.
860  *
861  * Writing is a different case.  We don't want the kernel to try to write
862  * out a buffer that HAMMER may be modifying passively or which has a
863  * dependancy.  In addition, kernel-demanded writes can only proceed for
864  * certain types of buffers (i.e. UNDO and DATA types).  Other dirty
865  * buffer types can only be explicitly written by the flusher.
866  *
867  * checkwrite will only be called for bdwrite()n buffers.  If we return
868  * success the kernel is guaranteed to initiate the buffer write.
869  */
870 static int
871 hammer_io_checkread(struct buf *bp)
872 {
873         return(0);
874 }
875
876 static int
877 hammer_io_checkwrite(struct buf *bp)
878 {
879         hammer_io_t io = (void *)LIST_FIRST(&bp->b_dep);
880
881         /*
882          * This shouldn't happen under normal operation.
883          */
884         if (io->type == HAMMER_STRUCTURE_VOLUME ||
885             io->type == HAMMER_STRUCTURE_META_BUFFER) {
886                 if (!panicstr)
887                         panic("hammer_io_checkwrite: illegal buffer");
888                 if ((bp->b_flags & B_LOCKED) == 0) {
889                         bp->b_flags |= B_LOCKED;
890                         ++hammer_count_io_locked;
891                 }
892                 return(1);
893         }
894
895         /*
896          * We can only clear the modified bit if the IO is not currently
897          * undergoing modification.  Otherwise we may miss changes.
898          */
899         if (io->modify_refs == 0 && io->modified)
900                 hammer_io_clear_modify(io, 0);
901
902         /*
903          * The kernel is going to start the IO, set io->running.
904          */
905         KKASSERT(io->running == 0);
906         io->running = 1;
907         io->hmp->io_running_space += io->bytes;
908         hammer_count_io_running_write += io->bytes;
909         return(0);
910 }
911
912 /*
913  * Return non-zero if we wish to delay the kernel's attempt to flush
914  * this buffer to disk.
915  */
916 static int
917 hammer_io_countdeps(struct buf *bp, int n)
918 {
919         return(0);
920 }
921
922 struct bio_ops hammer_bioops = {
923         .io_start       = hammer_io_start,
924         .io_complete    = hammer_io_complete,
925         .io_deallocate  = hammer_io_deallocate,
926         .io_fsync       = hammer_io_fsync,
927         .io_sync        = hammer_io_sync,
928         .io_movedeps    = hammer_io_movedeps,
929         .io_countdeps   = hammer_io_countdeps,
930         .io_checkread   = hammer_io_checkread,
931         .io_checkwrite  = hammer_io_checkwrite,
932 };
933
934 /************************************************************************
935  *                              DIRECT IO OPS                           *
936  ************************************************************************
937  *
938  * These functions operate directly on the buffer cache buffer associated
939  * with a front-end vnode rather then a back-end device vnode.
940  */
941
942 /*
943  * Read a buffer associated with a front-end vnode directly from the
944  * disk media.  The bio may be issued asynchronously.  If leaf is non-NULL
945  * we validate the CRC.
946  *
947  * A second-level bio already resolved to a zone-2 offset (typically by
948  * the BMAP code, or by a previous hammer_io_direct_write()), is passed. 
949  *
950  * We must check for the presence of a HAMMER buffer to handle the case
951  * where the reblocker has rewritten the data (which it does via the HAMMER
952  * buffer system, not via the high-level vnode buffer cache), but not yet
953  * committed the buffer to the media. 
954  */
955 int
956 hammer_io_direct_read(hammer_mount_t hmp, struct bio *bio,
957                       hammer_btree_leaf_elm_t leaf)
958 {
959         hammer_off_t buf_offset;
960         hammer_off_t zone2_offset;
961         hammer_volume_t volume;
962         struct buf *bp;
963         struct bio *nbio;
964         int vol_no;
965         int error;
966
967         buf_offset = bio->bio_offset;
968         KKASSERT((buf_offset & HAMMER_OFF_ZONE_MASK) ==
969                  HAMMER_ZONE_LARGE_DATA);
970
971         /*
972          * The buffer cache may have an aliased buffer (the reblocker can
973          * write them).  If it does we have to sync any dirty data before
974          * we can build our direct-read.  This is a non-critical code path.
975          */
976         bp = bio->bio_buf;
977         hammer_sync_buffers(hmp, buf_offset, bp->b_bufsize);
978
979         /*
980          * Resolve to a zone-2 offset.  The conversion just requires
981          * munging the top 4 bits but we want to abstract it anyway
982          * so the blockmap code can verify the zone assignment.
983          */
984         zone2_offset = hammer_blockmap_lookup(hmp, buf_offset, &error);
985         if (error)
986                 goto done;
987         KKASSERT((zone2_offset & HAMMER_OFF_ZONE_MASK) ==
988                  HAMMER_ZONE_RAW_BUFFER);
989
990         /*
991          * Resolve volume and raw-offset for 3rd level bio.  The
992          * offset will be specific to the volume.
993          */
994         vol_no = HAMMER_VOL_DECODE(zone2_offset);
995         volume = hammer_get_volume(hmp, vol_no, &error);
996         if (error == 0 && zone2_offset >= volume->maxbuf_off)
997                 error = EIO;
998
999         if (error == 0) {
1000                 zone2_offset &= HAMMER_OFF_SHORT_MASK;
1001
1002                 nbio = push_bio(bio);
1003                 nbio->bio_offset = volume->ondisk->vol_buf_beg +
1004                                    zone2_offset;
1005 #if 0
1006                 /*
1007                  * XXX disabled - our CRC check doesn't work if the OS
1008                  * does bogus_page replacement on the direct-read.
1009                  */
1010                 if (leaf && hammer_verify_data) {
1011                         nbio->bio_done = hammer_io_direct_read_complete;
1012                         nbio->bio_caller_info1.uvalue32 = leaf->data_crc;
1013                 }
1014 #endif
1015                 vn_strategy(volume->devvp, nbio);
1016         }
1017         hammer_rel_volume(volume, 0);
1018 done:
1019         if (error) {
1020                 kprintf("hammer_direct_read: failed @ %016llx\n",
1021                         zone2_offset);
1022                 bp->b_error = error;
1023                 bp->b_flags |= B_ERROR;
1024                 biodone(bio);
1025         }
1026         return(error);
1027 }
1028
1029 #if 0
1030 /*
1031  * On completion of the BIO this callback must check the data CRC
1032  * and chain to the previous bio.
1033  */
1034 static
1035 void
1036 hammer_io_direct_read_complete(struct bio *nbio)
1037 {
1038         struct bio *obio;
1039         struct buf *bp;
1040         u_int32_t rec_crc = nbio->bio_caller_info1.uvalue32;
1041
1042         bp = nbio->bio_buf;
1043         if (crc32(bp->b_data, bp->b_bufsize) != rec_crc) {
1044                 kprintf("HAMMER: data_crc error @%016llx/%d\n",
1045                         nbio->bio_offset, bp->b_bufsize);
1046                 if (hammer_debug_debug)
1047                         Debugger("");
1048                 bp->b_flags |= B_ERROR;
1049                 bp->b_error = EIO;
1050         }
1051         obio = pop_bio(nbio);
1052         biodone(obio);
1053 }
1054 #endif
1055
1056 /*
1057  * Write a buffer associated with a front-end vnode directly to the
1058  * disk media.  The bio may be issued asynchronously.
1059  *
1060  * The BIO is associated with the specified record and RECF_DIRECT_IO
1061  * is set.
1062  */
1063 int
1064 hammer_io_direct_write(hammer_mount_t hmp, hammer_record_t record,
1065                        struct bio *bio)
1066 {
1067         hammer_btree_leaf_elm_t leaf = &record->leaf;
1068         hammer_off_t buf_offset;
1069         hammer_off_t zone2_offset;
1070         hammer_volume_t volume;
1071         hammer_buffer_t buffer;
1072         struct buf *bp;
1073         struct bio *nbio;
1074         char *ptr;
1075         int vol_no;
1076         int error;
1077
1078         buf_offset = leaf->data_offset;
1079
1080         KKASSERT(buf_offset > HAMMER_ZONE_BTREE);
1081         KKASSERT(bio->bio_buf->b_cmd == BUF_CMD_WRITE);
1082
1083         if ((buf_offset & HAMMER_BUFMASK) == 0 &&
1084             leaf->data_len >= HAMMER_BUFSIZE) {
1085                 /*
1086                  * We are using the vnode's bio to write directly to the
1087                  * media, any hammer_buffer at the same zone-X offset will
1088                  * now have stale data.
1089                  */
1090                 zone2_offset = hammer_blockmap_lookup(hmp, buf_offset, &error);
1091                 vol_no = HAMMER_VOL_DECODE(zone2_offset);
1092                 volume = hammer_get_volume(hmp, vol_no, &error);
1093
1094                 if (error == 0 && zone2_offset >= volume->maxbuf_off)
1095                         error = EIO;
1096                 if (error == 0) {
1097                         bp = bio->bio_buf;
1098                         KKASSERT((bp->b_bufsize & HAMMER_BUFMASK) == 0);
1099                         hammer_del_buffers(hmp, buf_offset,
1100                                            zone2_offset, bp->b_bufsize);
1101
1102                         /*
1103                          * Second level bio - cached zone2 offset.
1104                          *
1105                          * (We can put our bio_done function in either the
1106                          *  2nd or 3rd level).
1107                          */
1108                         nbio = push_bio(bio);
1109                         nbio->bio_offset = zone2_offset;
1110                         nbio->bio_done = hammer_io_direct_write_complete;
1111                         nbio->bio_caller_info1.ptr = record;
1112                         record->flags |= HAMMER_RECF_DIRECT_IO;
1113
1114                         /*
1115                          * Third level bio - raw offset specific to the
1116                          * correct volume.
1117                          */
1118                         zone2_offset &= HAMMER_OFF_SHORT_MASK;
1119                         nbio = push_bio(nbio);
1120                         nbio->bio_offset = volume->ondisk->vol_buf_beg +
1121                                            zone2_offset;
1122                         vn_strategy(volume->devvp, nbio);
1123                 }
1124                 hammer_rel_volume(volume, 0);
1125         } else {
1126                 /* 
1127                  * Must fit in a standard HAMMER buffer.  In this case all
1128                  * consumers use the HAMMER buffer system and RECF_DIRECT_IO
1129                  * does not need to be set-up.
1130                  */
1131                 KKASSERT(((buf_offset ^ (buf_offset + leaf->data_len - 1)) & ~HAMMER_BUFMASK64) == 0);
1132                 buffer = NULL;
1133                 ptr = hammer_bread(hmp, buf_offset, &error, &buffer);
1134                 if (error == 0) {
1135                         bp = bio->bio_buf;
1136                         bp->b_flags |= B_AGE;
1137                         hammer_io_modify(&buffer->io, 1);
1138                         bcopy(bp->b_data, ptr, leaf->data_len);
1139                         hammer_io_modify_done(&buffer->io);
1140                         hammer_rel_buffer(buffer, 0);
1141                         bp->b_resid = 0;
1142                         biodone(bio);
1143                 }
1144         }
1145         if (error) {
1146                 kprintf("hammer_direct_write: failed @ %016llx\n",
1147                         leaf->data_offset);
1148                 bp = bio->bio_buf;
1149                 bp->b_resid = 0;
1150                 bp->b_error = EIO;
1151                 bp->b_flags |= B_ERROR;
1152                 biodone(bio);
1153         }
1154         return(error);
1155 }
1156
1157 /*
1158  * On completion of the BIO this callback must disconnect
1159  * it from the hammer_record and chain to the previous bio.
1160  */
1161 static
1162 void
1163 hammer_io_direct_write_complete(struct bio *nbio)
1164 {
1165         struct bio *obio;
1166         hammer_record_t record = nbio->bio_caller_info1.ptr;
1167
1168         obio = pop_bio(nbio);
1169         biodone(obio);
1170         KKASSERT(record != NULL && (record->flags & HAMMER_RECF_DIRECT_IO));
1171         record->flags &= ~HAMMER_RECF_DIRECT_IO;
1172         if (record->flags & HAMMER_RECF_DIRECT_WAIT) {
1173                 record->flags &= ~HAMMER_RECF_DIRECT_WAIT;
1174                 wakeup(&record->flags);
1175         }
1176 }
1177
1178
1179 /*
1180  * This is called before a record is either committed to the B-Tree
1181  * or destroyed, to resolve any associated direct-IO.  We must
1182  * ensure that the data is available on-media to other consumers
1183  * such as the reblocker or mirroring code.
1184  *
1185  * Note that other consumers might access the data via the block
1186  * device's buffer cache and not the high level vnode's buffer cache.
1187  */
1188 void
1189 hammer_io_direct_wait(hammer_record_t record)
1190 {
1191         crit_enter();
1192         while (record->flags & HAMMER_RECF_DIRECT_IO) {
1193                 record->flags |= HAMMER_RECF_DIRECT_WAIT;
1194                 tsleep(&record->flags, 0, "hmdiow", 0);
1195         }
1196         crit_exit();
1197 }
1198
1199 /*
1200  * This is called to remove the second-level cached zone-2 offset from
1201  * frontend buffer cache buffers, now stale due to a data relocation.
1202  * These offsets are generated by cluster_read() via VOP_BMAP, or directly
1203  * by hammer_vop_strategy_read().
1204  *
1205  * This is rather nasty because here we have something like the reblocker
1206  * scanning the raw B-Tree with no held references on anything, really,
1207  * other then a shared lock on the B-Tree node, and we have to access the
1208  * frontend's buffer cache to check for and clean out the association.
1209  * Specifically, if the reblocker is moving data on the disk, these cached
1210  * offsets will become invalid.
1211  *
1212  * Only data record types associated with the large-data zone are subject
1213  * to direct-io and need to be checked.
1214  *
1215  */
1216 void
1217 hammer_io_direct_uncache(hammer_mount_t hmp, hammer_btree_leaf_elm_t leaf)
1218 {
1219         struct hammer_inode_info iinfo;
1220         int zone;
1221
1222         if (leaf->base.rec_type != HAMMER_RECTYPE_DATA)
1223                 return;
1224         zone = HAMMER_ZONE_DECODE(leaf->data_offset);
1225         if (zone != HAMMER_ZONE_LARGE_DATA_INDEX)
1226                 return;
1227         iinfo.obj_id = leaf->base.obj_id;
1228         iinfo.obj_asof = 0;     /* unused */
1229         iinfo.obj_localization = leaf->base.localization &
1230                                  HAMMER_LOCALIZE_PSEUDOFS_MASK;
1231         iinfo.u.leaf = leaf;
1232         hammer_scan_inode_snapshots(hmp, &iinfo,
1233                                     hammer_io_direct_uncache_callback,
1234                                     leaf);
1235 }
1236
1237 static int
1238 hammer_io_direct_uncache_callback(hammer_inode_t ip, void *data)
1239 {
1240         hammer_inode_info_t iinfo = data;
1241         hammer_off_t data_offset;
1242         hammer_off_t file_offset;
1243         struct vnode *vp;
1244         struct buf *bp;
1245         int blksize;
1246
1247         if (ip->vp == NULL)
1248                 return(0);
1249         data_offset = iinfo->u.leaf->data_offset;
1250         file_offset = iinfo->u.leaf->base.key - iinfo->u.leaf->data_len;
1251         blksize = iinfo->u.leaf->data_len;
1252         KKASSERT((blksize & HAMMER_BUFMASK) == 0);
1253
1254         hammer_ref(&ip->lock);
1255         if (hammer_get_vnode(ip, &vp) == 0) {
1256                 if ((bp = findblk(ip->vp, file_offset)) != NULL &&
1257                     bp->b_bio2.bio_offset != NOOFFSET) {
1258                         bp = getblk(ip->vp, file_offset, blksize, 0, 0);
1259                         bp->b_bio2.bio_offset = NOOFFSET;
1260                         brelse(bp);
1261                 }
1262                 vput(vp);
1263         }
1264         hammer_rel_inode(ip, 0);
1265         return(0);
1266 }
1267