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