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