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