2a6a2c21af0d2caa3c56f8e8ae5292494f47a5d2
[dragonfly.git] / sys / vfs / hammer / hammer_ondisk.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_ondisk.c,v 1.76 2008/08/29 20:19:08 dillon Exp $
35  */
36 /*
37  * Manage HAMMER's on-disk structures.  These routines are primarily
38  * responsible for interfacing with the kernel's I/O subsystem and for
39  * managing in-memory structures.
40  */
41
42 #include "hammer.h"
43 #include <sys/fcntl.h>
44 #include <sys/nlookup.h>
45 #include <sys/buf.h>
46 #include <sys/buf2.h>
47
48 static void hammer_free_volume(hammer_volume_t volume);
49 static int hammer_load_volume(hammer_volume_t volume);
50 static int hammer_load_buffer(hammer_buffer_t buffer, int isnew);
51 static int hammer_load_node(hammer_transaction_t trans,
52                                 hammer_node_t node, int isnew);
53
54 static int
55 hammer_vol_rb_compare(hammer_volume_t vol1, hammer_volume_t vol2)
56 {
57         if (vol1->vol_no < vol2->vol_no)
58                 return(-1);
59         if (vol1->vol_no > vol2->vol_no)
60                 return(1);
61         return(0);
62 }
63
64 /*
65  * hammer_buffer structures are indexed via their zoneX_offset, not
66  * their zone2_offset.
67  */
68 static int
69 hammer_buf_rb_compare(hammer_buffer_t buf1, hammer_buffer_t buf2)
70 {
71         if (buf1->zoneX_offset < buf2->zoneX_offset)
72                 return(-1);
73         if (buf1->zoneX_offset > buf2->zoneX_offset)
74                 return(1);
75         return(0);
76 }
77
78 static int
79 hammer_nod_rb_compare(hammer_node_t node1, hammer_node_t node2)
80 {
81         if (node1->node_offset < node2->node_offset)
82                 return(-1);
83         if (node1->node_offset > node2->node_offset)
84                 return(1);
85         return(0);
86 }
87
88 RB_GENERATE2(hammer_vol_rb_tree, hammer_volume, rb_node,
89              hammer_vol_rb_compare, int32_t, vol_no);
90 RB_GENERATE2(hammer_buf_rb_tree, hammer_buffer, rb_node,
91              hammer_buf_rb_compare, hammer_off_t, zoneX_offset);
92 RB_GENERATE2(hammer_nod_rb_tree, hammer_node, rb_node,
93              hammer_nod_rb_compare, hammer_off_t, node_offset);
94
95 /************************************************************************
96  *                              VOLUMES                                 *
97  ************************************************************************
98  *
99  * Load a HAMMER volume by name.  Returns 0 on success or a positive error
100  * code on failure.  Volumes must be loaded at mount time, get_volume() will
101  * not load a new volume.
102  *
103  * Calls made to hammer_load_volume() or single-threaded
104  */
105 int
106 hammer_install_volume(struct hammer_mount *hmp, const char *volname,
107                       struct vnode *devvp)
108 {
109         struct mount *mp;
110         hammer_volume_t volume;
111         struct hammer_volume_ondisk *ondisk;
112         struct nlookupdata nd;
113         struct buf *bp = NULL;
114         int error;
115         int ronly;
116         int setmp = 0;
117
118         mp = hmp->mp;
119         ronly = ((mp->mnt_flag & MNT_RDONLY) ? 1 : 0);
120
121         /*
122          * Allocate a volume structure
123          */
124         ++hammer_count_volumes;
125         volume = kmalloc(sizeof(*volume), hmp->m_misc, M_WAITOK|M_ZERO);
126         volume->vol_name = kstrdup(volname, hmp->m_misc);
127         volume->io.hmp = hmp;   /* bootstrap */
128         hammer_io_init(&volume->io, volume, HAMMER_STRUCTURE_VOLUME);
129         volume->io.offset = 0LL;
130         volume->io.bytes = HAMMER_BUFSIZE;
131
132         /*
133          * Get the device vnode
134          */
135         if (devvp == NULL) {
136                 error = nlookup_init(&nd, volume->vol_name, UIO_SYSSPACE, NLC_FOLLOW);
137                 if (error == 0)
138                         error = nlookup(&nd);
139                 if (error == 0)
140                         error = cache_vref(&nd.nl_nch, nd.nl_cred, &volume->devvp);
141                 nlookup_done(&nd);
142         } else {
143                 error = 0;
144                 volume->devvp = devvp;
145         }
146
147         if (error == 0) {
148                 if (vn_isdisk(volume->devvp, &error)) {
149                         error = vfs_mountedon(volume->devvp);
150                 }
151         }
152         if (error == 0 && vcount(volume->devvp) > 0)
153                 error = EBUSY;
154         if (error == 0) {
155                 vn_lock(volume->devvp, LK_EXCLUSIVE | LK_RETRY);
156                 error = vinvalbuf(volume->devvp, V_SAVE, 0, 0);
157                 if (error == 0) {
158                         error = VOP_OPEN(volume->devvp, 
159                                          (ronly ? FREAD : FREAD|FWRITE),
160                                          FSCRED, NULL);
161                 }
162                 vn_unlock(volume->devvp);
163         }
164         if (error) {
165                 hammer_free_volume(volume);
166                 return(error);
167         }
168         volume->devvp->v_rdev->si_mountpoint = mp;
169         setmp = 1;
170
171         /*
172          * Extract the volume number from the volume header and do various
173          * sanity checks.
174          */
175         error = bread(volume->devvp, 0LL, HAMMER_BUFSIZE, &bp);
176         if (error)
177                 goto late_failure;
178         ondisk = (void *)bp->b_data;
179         if (ondisk->vol_signature != HAMMER_FSBUF_VOLUME) {
180                 kprintf("hammer_mount: volume %s has an invalid header\n",
181                         volume->vol_name);
182                 error = EFTYPE;
183                 goto late_failure;
184         }
185         volume->vol_no = ondisk->vol_no;
186         volume->buffer_base = ondisk->vol_buf_beg;
187         volume->vol_flags = ondisk->vol_flags;
188         volume->nblocks = ondisk->vol_nblocks; 
189         volume->maxbuf_off = HAMMER_ENCODE_RAW_BUFFER(volume->vol_no,
190                                     ondisk->vol_buf_end - ondisk->vol_buf_beg);
191         volume->maxraw_off = ondisk->vol_buf_end;
192
193         if (RB_EMPTY(&hmp->rb_vols_root)) {
194                 hmp->fsid = ondisk->vol_fsid;
195         } else if (bcmp(&hmp->fsid, &ondisk->vol_fsid, sizeof(uuid_t))) {
196                 kprintf("hammer_mount: volume %s's fsid does not match "
197                         "other volumes\n", volume->vol_name);
198                 error = EFTYPE;
199                 goto late_failure;
200         }
201
202         /*
203          * Insert the volume structure into the red-black tree.
204          */
205         if (RB_INSERT(hammer_vol_rb_tree, &hmp->rb_vols_root, volume)) {
206                 kprintf("hammer_mount: volume %s has a duplicate vol_no %d\n",
207                         volume->vol_name, volume->vol_no);
208                 error = EEXIST;
209         }
210
211         /*
212          * Set the root volume .  HAMMER special cases rootvol the structure.
213          * We do not hold a ref because this would prevent related I/O
214          * from being flushed.
215          */
216         if (error == 0 && ondisk->vol_rootvol == ondisk->vol_no) {
217                 hmp->rootvol = volume;
218                 hmp->nvolumes = ondisk->vol_count;
219                 if (bp) {
220                         brelse(bp);
221                         bp = NULL;
222                 }
223                 hmp->mp->mnt_stat.f_blocks += ondisk->vol0_stat_bigblocks *
224                         (HAMMER_LARGEBLOCK_SIZE / HAMMER_BUFSIZE);
225                 hmp->mp->mnt_vstat.f_blocks += ondisk->vol0_stat_bigblocks *
226                         (HAMMER_LARGEBLOCK_SIZE / HAMMER_BUFSIZE);
227         }
228 late_failure:
229         if (bp)
230                 brelse(bp);
231         if (error) {
232                 /*vinvalbuf(volume->devvp, V_SAVE, 0, 0);*/
233                 if (setmp)
234                         volume->devvp->v_rdev->si_mountpoint = NULL;
235                 VOP_CLOSE(volume->devvp, ronly ? FREAD : FREAD|FWRITE);
236                 hammer_free_volume(volume);
237         }
238         return (error);
239 }
240
241 /*
242  * This is called for each volume when updating the mount point from
243  * read-write to read-only or vise-versa.
244  */
245 int
246 hammer_adjust_volume_mode(hammer_volume_t volume, void *data __unused)
247 {
248         if (volume->devvp) {
249                 vn_lock(volume->devvp, LK_EXCLUSIVE | LK_RETRY);
250                 if (volume->io.hmp->ronly) {
251                         /* do not call vinvalbuf */
252                         VOP_OPEN(volume->devvp, FREAD, FSCRED, NULL);
253                         VOP_CLOSE(volume->devvp, FREAD|FWRITE);
254                 } else {
255                         /* do not call vinvalbuf */
256                         VOP_OPEN(volume->devvp, FREAD|FWRITE, FSCRED, NULL);
257                         VOP_CLOSE(volume->devvp, FREAD);
258                 }
259                 vn_unlock(volume->devvp);
260         }
261         return(0);
262 }
263
264 /*
265  * Unload and free a HAMMER volume.  Must return >= 0 to continue scan
266  * so returns -1 on failure.
267  */
268 int
269 hammer_unload_volume(hammer_volume_t volume, void *data __unused)
270 {
271         hammer_mount_t hmp = volume->io.hmp;
272         int ronly = ((hmp->mp->mnt_flag & MNT_RDONLY) ? 1 : 0);
273         struct buf *bp;
274
275         /*
276          * Clean up the root volume pointer, which is held unlocked in hmp.
277          */
278         if (hmp->rootvol == volume)
279                 hmp->rootvol = NULL;
280
281         /*
282          * We must not flush a dirty buffer to disk on umount.  It should
283          * have already been dealt with by the flusher, or we may be in
284          * catastrophic failure.
285          */
286         hammer_io_clear_modify(&volume->io, 1);
287         volume->io.waitdep = 1;
288         bp = hammer_io_release(&volume->io, 1);
289
290         /*
291          * Clean up the persistent ref ioerror might have on the volume
292          */
293         if (volume->io.ioerror) {
294                 volume->io.ioerror = 0;
295                 hammer_unref(&volume->io.lock);
296         }
297
298         /*
299          * There should be no references on the volume, no clusters, and
300          * no super-clusters.
301          */
302         KKASSERT(volume->io.lock.refs == 0);
303         if (bp)
304                 brelse(bp);
305
306         volume->ondisk = NULL;
307         if (volume->devvp) {
308                 if (volume->devvp->v_rdev &&
309                     volume->devvp->v_rdev->si_mountpoint == hmp->mp
310                 ) {
311                         volume->devvp->v_rdev->si_mountpoint = NULL;
312                 }
313                 if (ronly) {
314                         /*
315                          * Make sure we don't sync anything to disk if we
316                          * are in read-only mode (1) or critically-errored
317                          * (2).  Note that there may be dirty buffers in
318                          * normal read-only mode from crash recovery.
319                          */
320                         vinvalbuf(volume->devvp, 0, 0, 0);
321                         VOP_CLOSE(volume->devvp, FREAD);
322                 } else {
323                         /*
324                          * Normal termination, save any dirty buffers
325                          * (XXX there really shouldn't be any).
326                          */
327                         vinvalbuf(volume->devvp, V_SAVE, 0, 0);
328                         VOP_CLOSE(volume->devvp, FREAD|FWRITE);
329                 }
330         }
331
332         /*
333          * Destroy the structure
334          */
335         RB_REMOVE(hammer_vol_rb_tree, &hmp->rb_vols_root, volume);
336         hammer_free_volume(volume);
337         return(0);
338 }
339
340 static
341 void
342 hammer_free_volume(hammer_volume_t volume)
343 {
344         hammer_mount_t hmp = volume->io.hmp;
345
346         if (volume->vol_name) {
347                 kfree(volume->vol_name, hmp->m_misc);
348                 volume->vol_name = NULL;
349         }
350         if (volume->devvp) {
351                 vrele(volume->devvp);
352                 volume->devvp = NULL;
353         }
354         --hammer_count_volumes;
355         kfree(volume, hmp->m_misc);
356 }
357
358 /*
359  * Get a HAMMER volume.  The volume must already exist.
360  */
361 hammer_volume_t
362 hammer_get_volume(struct hammer_mount *hmp, int32_t vol_no, int *errorp)
363 {
364         struct hammer_volume *volume;
365
366         /*
367          * Locate the volume structure
368          */
369         volume = RB_LOOKUP(hammer_vol_rb_tree, &hmp->rb_vols_root, vol_no);
370         if (volume == NULL) {
371                 *errorp = ENOENT;
372                 return(NULL);
373         }
374         hammer_ref(&volume->io.lock);
375
376         /*
377          * Deal with on-disk info
378          */
379         if (volume->ondisk == NULL || volume->io.loading) {
380                 *errorp = hammer_load_volume(volume);
381                 if (*errorp) {
382                         hammer_rel_volume(volume, 1);
383                         volume = NULL;
384                 }
385         } else {
386                 *errorp = 0;
387         }
388         return(volume);
389 }
390
391 int
392 hammer_ref_volume(hammer_volume_t volume)
393 {
394         int error;
395
396         hammer_ref(&volume->io.lock);
397
398         /*
399          * Deal with on-disk info
400          */
401         if (volume->ondisk == NULL || volume->io.loading) {
402                 error = hammer_load_volume(volume);
403                 if (error)
404                         hammer_rel_volume(volume, 1);
405         } else {
406                 error = 0;
407         }
408         return (error);
409 }
410
411 hammer_volume_t
412 hammer_get_root_volume(struct hammer_mount *hmp, int *errorp)
413 {
414         hammer_volume_t volume;
415
416         volume = hmp->rootvol;
417         KKASSERT(volume != NULL);
418         hammer_ref(&volume->io.lock);
419
420         /*
421          * Deal with on-disk info
422          */
423         if (volume->ondisk == NULL || volume->io.loading) {
424                 *errorp = hammer_load_volume(volume);
425                 if (*errorp) {
426                         hammer_rel_volume(volume, 1);
427                         volume = NULL;
428                 }
429         } else {
430                 *errorp = 0;
431         }
432         return (volume);
433 }
434
435 /*
436  * Load a volume's on-disk information.  The volume must be referenced and
437  * not locked.  We temporarily acquire an exclusive lock to interlock
438  * against releases or multiple get's.
439  */
440 static int
441 hammer_load_volume(hammer_volume_t volume)
442 {
443         int error;
444
445         ++volume->io.loading;
446         hammer_lock_ex(&volume->io.lock);
447
448         if (volume->ondisk == NULL) {
449                 error = hammer_io_read(volume->devvp, &volume->io,
450                                        volume->maxraw_off);
451                 if (error == 0)
452                         volume->ondisk = (void *)volume->io.bp->b_data;
453         } else {
454                 error = 0;
455         }
456         --volume->io.loading;
457         hammer_unlock(&volume->io.lock);
458         return(error);
459 }
460
461 /*
462  * Release a volume.  Call hammer_io_release on the last reference.  We have
463  * to acquire an exclusive lock to interlock against volume->ondisk tests
464  * in hammer_load_volume(), and hammer_io_release() also expects an exclusive
465  * lock to be held.
466  *
467  * Volumes are not unloaded from memory during normal operation.
468  */
469 void
470 hammer_rel_volume(hammer_volume_t volume, int flush)
471 {
472         struct buf *bp = NULL;
473
474         crit_enter();
475         if (volume->io.lock.refs == 1) {
476                 ++volume->io.loading;
477                 hammer_lock_ex(&volume->io.lock);
478                 if (volume->io.lock.refs == 1) {
479                         volume->ondisk = NULL;
480                         bp = hammer_io_release(&volume->io, flush);
481                 }
482                 --volume->io.loading;
483                 hammer_unlock(&volume->io.lock);
484         }
485         hammer_unref(&volume->io.lock);
486         if (bp)
487                 brelse(bp);
488         crit_exit();
489 }
490
491 int
492 hammer_mountcheck_volumes(struct hammer_mount *hmp)
493 {
494         hammer_volume_t vol;
495         int i;
496
497         for (i = 0; i < hmp->nvolumes; ++i) {
498                 vol = RB_LOOKUP(hammer_vol_rb_tree, &hmp->rb_vols_root, i);
499                 if (vol == NULL)
500                         return(EINVAL);
501         }
502         return(0);
503 }
504
505 /************************************************************************
506  *                              BUFFERS                                 *
507  ************************************************************************
508  *
509  * Manage buffers.  Currently most blockmap-backed zones are direct-mapped
510  * to zone-2 buffer offsets, without a translation stage.  However, the
511  * hammer_buffer structure is indexed by its zoneX_offset, not its
512  * zone2_offset.
513  *
514  * The proper zone must be maintained throughout the code-base all the way
515  * through to the big-block allocator, or routines like hammer_del_buffers()
516  * will not be able to locate all potentially conflicting buffers.
517  */
518 hammer_buffer_t
519 hammer_get_buffer(hammer_mount_t hmp, hammer_off_t buf_offset,
520                   int bytes, int isnew, int *errorp)
521 {
522         hammer_buffer_t buffer;
523         hammer_volume_t volume;
524         hammer_off_t    zone2_offset;
525         hammer_io_type_t iotype;
526         int vol_no;
527         int zone;
528
529         buf_offset &= ~HAMMER_BUFMASK64;
530 again:
531         /*
532          * Shortcut if the buffer is already cached
533          */
534         buffer = RB_LOOKUP(hammer_buf_rb_tree, &hmp->rb_bufs_root, buf_offset);
535         if (buffer) {
536                 if (buffer->io.lock.refs == 0)
537                         ++hammer_count_refedbufs;
538                 hammer_ref(&buffer->io.lock);
539
540                 /*
541                  * Once refed the ondisk field will not be cleared by
542                  * any other action.
543                  */
544                 if (buffer->ondisk && buffer->io.loading == 0) {
545                         *errorp = 0;
546                         hammer_io_advance(&buffer->io);
547                         return(buffer);
548                 }
549
550                 /*
551                  * The buffer is no longer loose if it has a ref, and
552                  * cannot become loose once it gains a ref.  Loose
553                  * buffers will never be in a modified state.  This should
554                  * only occur on the 0->1 transition of refs.
555                  *
556                  * lose_list can be modified via a biodone() interrupt.
557                  */
558                 if (buffer->io.mod_list == &hmp->lose_list) {
559                         crit_enter();   /* biodone race against list */
560                         TAILQ_REMOVE(buffer->io.mod_list, &buffer->io,
561                                      mod_entry);
562                         crit_exit();
563                         buffer->io.mod_list = NULL;
564                         KKASSERT(buffer->io.modified == 0);
565                 }
566                 goto found;
567         }
568
569         /*
570          * What is the buffer class?
571          */
572         zone = HAMMER_ZONE_DECODE(buf_offset);
573
574         switch(zone) {
575         case HAMMER_ZONE_LARGE_DATA_INDEX:
576         case HAMMER_ZONE_SMALL_DATA_INDEX:
577                 iotype = HAMMER_STRUCTURE_DATA_BUFFER;
578                 break;
579         case HAMMER_ZONE_UNDO_INDEX:
580                 iotype = HAMMER_STRUCTURE_UNDO_BUFFER;
581                 break;
582         case HAMMER_ZONE_META_INDEX:
583         default:
584                 /*
585                  * NOTE: inode data and directory entries are placed in this
586                  * zone.  inode atime/mtime is updated in-place and thus
587                  * buffers containing inodes must be synchronized as
588                  * meta-buffers, same as buffers containing B-Tree info.
589                  */
590                 iotype = HAMMER_STRUCTURE_META_BUFFER;
591                 break;
592         }
593
594         /*
595          * Handle blockmap offset translations
596          */
597         if (zone >= HAMMER_ZONE_BTREE_INDEX) {
598                 zone2_offset = hammer_blockmap_lookup(hmp, buf_offset, errorp);
599         } else if (zone == HAMMER_ZONE_UNDO_INDEX) {
600                 zone2_offset = hammer_undo_lookup(hmp, buf_offset, errorp);
601         } else {
602                 KKASSERT(zone == HAMMER_ZONE_RAW_BUFFER_INDEX);
603                 zone2_offset = buf_offset;
604                 *errorp = 0;
605         }
606         if (*errorp)
607                 return(NULL);
608
609         /*
610          * NOTE: zone2_offset and maxbuf_off are both full zone-2 offset
611          * specifications.
612          */
613         KKASSERT((zone2_offset & HAMMER_OFF_ZONE_MASK) ==
614                  HAMMER_ZONE_RAW_BUFFER);
615         vol_no = HAMMER_VOL_DECODE(zone2_offset);
616         volume = hammer_get_volume(hmp, vol_no, errorp);
617         if (volume == NULL)
618                 return(NULL);
619
620         KKASSERT(zone2_offset < volume->maxbuf_off);
621
622         /*
623          * Allocate a new buffer structure.  We will check for races later.
624          */
625         ++hammer_count_buffers;
626         buffer = kmalloc(sizeof(*buffer), hmp->m_misc,
627                          M_WAITOK|M_ZERO|M_USE_RESERVE);
628         buffer->zone2_offset = zone2_offset;
629         buffer->zoneX_offset = buf_offset;
630
631         hammer_io_init(&buffer->io, volume, iotype);
632         buffer->io.offset = volume->ondisk->vol_buf_beg +
633                             (zone2_offset & HAMMER_OFF_SHORT_MASK);
634         buffer->io.bytes = bytes;
635         TAILQ_INIT(&buffer->clist);
636         hammer_ref(&buffer->io.lock);
637
638         /*
639          * Insert the buffer into the RB tree and handle late collisions.
640          */
641         if (RB_INSERT(hammer_buf_rb_tree, &hmp->rb_bufs_root, buffer)) {
642                 hammer_rel_volume(volume, 0);
643                 buffer->io.volume = NULL;       /* safety */
644                 hammer_unref(&buffer->io.lock); /* safety */
645                 --hammer_count_buffers;
646                 kfree(buffer, hmp->m_misc);
647                 goto again;
648         }
649         ++hammer_count_refedbufs;
650 found:
651
652         /*
653          * Deal with on-disk info and loading races.
654          */
655         if (buffer->ondisk == NULL || buffer->io.loading) {
656                 *errorp = hammer_load_buffer(buffer, isnew);
657                 if (*errorp) {
658                         hammer_rel_buffer(buffer, 1);
659                         buffer = NULL;
660                 } else {
661                         hammer_io_advance(&buffer->io);
662                 }
663         } else {
664                 *errorp = 0;
665                 hammer_io_advance(&buffer->io);
666         }
667         return(buffer);
668 }
669
670 /*
671  * This is used by the direct-read code to deal with large-data buffers
672  * created by the reblocker and mirror-write code.  The direct-read code
673  * bypasses the HAMMER buffer subsystem and so any aliased dirty or write-
674  * running hammer buffers must be fully synced to disk before we can issue
675  * the direct-read.
676  *
677  * This code path is not considered critical as only the rebocker and
678  * mirror-write code will create large-data buffers via the HAMMER buffer
679  * subsystem.  They do that because they operate at the B-Tree level and
680  * do not access the vnode/inode structures.
681  */
682 void
683 hammer_sync_buffers(hammer_mount_t hmp, hammer_off_t base_offset, int bytes)
684 {
685         hammer_buffer_t buffer;
686         int error;
687
688         KKASSERT((base_offset & HAMMER_OFF_ZONE_MASK) ==
689                  HAMMER_ZONE_LARGE_DATA);
690
691         while (bytes > 0) {
692                 buffer = RB_LOOKUP(hammer_buf_rb_tree, &hmp->rb_bufs_root,
693                                    base_offset);
694                 if (buffer && (buffer->io.modified || buffer->io.running)) {
695                         error = hammer_ref_buffer(buffer);
696                         if (error == 0) {
697                                 hammer_io_wait(&buffer->io);
698                                 if (buffer->io.modified) {
699                                         hammer_io_write_interlock(&buffer->io);
700                                         hammer_io_flush(&buffer->io, 0);
701                                         hammer_io_done_interlock(&buffer->io);
702                                         hammer_io_wait(&buffer->io);
703                                 }
704                                 hammer_rel_buffer(buffer, 0);
705                         }
706                 }
707                 base_offset += HAMMER_BUFSIZE;
708                 bytes -= HAMMER_BUFSIZE;
709         }
710 }
711
712 /*
713  * Destroy all buffers covering the specified zoneX offset range.  This
714  * is called when the related blockmap layer2 entry is freed or when
715  * a direct write bypasses our buffer/buffer-cache subsystem.
716  *
717  * The buffers may be referenced by the caller itself.  Setting reclaim
718  * will cause the buffer to be destroyed when it's ref count reaches zero.
719  *
720  * Return 0 on success, EAGAIN if some buffers could not be destroyed due
721  * to additional references held by other threads, or some other (typically
722  * fatal) error.
723  */
724 int
725 hammer_del_buffers(hammer_mount_t hmp, hammer_off_t base_offset,
726                    hammer_off_t zone2_offset, int bytes,
727                    int report_conflicts)
728 {
729         hammer_buffer_t buffer;
730         hammer_volume_t volume;
731         int vol_no;
732         int error;
733         int ret_error;
734
735         vol_no = HAMMER_VOL_DECODE(zone2_offset);
736         volume = hammer_get_volume(hmp, vol_no, &ret_error);
737         KKASSERT(ret_error == 0);
738
739         while (bytes > 0) {
740                 buffer = RB_LOOKUP(hammer_buf_rb_tree, &hmp->rb_bufs_root,
741                                    base_offset);
742                 if (buffer) {
743                         error = hammer_ref_buffer(buffer);
744                         if (error == 0 && buffer->io.lock.refs != 1) {
745                                 error = EAGAIN;
746                                 hammer_rel_buffer(buffer, 0);
747                         }
748                         if (error == 0) {
749                                 KKASSERT(buffer->zone2_offset == zone2_offset);
750                                 hammer_io_clear_modify(&buffer->io, 1);
751                                 buffer->io.reclaim = 1;
752                                 buffer->io.waitdep = 1;
753                                 KKASSERT(buffer->io.volume == volume);
754                                 hammer_rel_buffer(buffer, 0);
755                         }
756                 } else {
757                         error = hammer_io_inval(volume, zone2_offset);
758                 }
759                 if (error) {
760                         ret_error = error;
761                         if (report_conflicts ||
762                             (hammer_debug_general & 0x8000)) {
763                                 kprintf("hammer_del_buffers: unable to "
764                                         "invalidate %016llx buffer=%p rep=%d\n",
765                                         (long long)base_offset,
766                                         buffer, report_conflicts);
767                         }
768                 }
769                 base_offset += HAMMER_BUFSIZE;
770                 zone2_offset += HAMMER_BUFSIZE;
771                 bytes -= HAMMER_BUFSIZE;
772         }
773         hammer_rel_volume(volume, 0);
774         return (ret_error);
775 }
776
777 static int
778 hammer_load_buffer(hammer_buffer_t buffer, int isnew)
779 {
780         hammer_volume_t volume;
781         int error;
782
783         /*
784          * Load the buffer's on-disk info
785          */
786         volume = buffer->io.volume;
787         ++buffer->io.loading;
788         hammer_lock_ex(&buffer->io.lock);
789
790         if (hammer_debug_io & 0x0001) {
791                 kprintf("load_buffer %016llx %016llx isnew=%d od=%p\n",
792                         (long long)buffer->zoneX_offset,
793                         (long long)buffer->zone2_offset,
794                         isnew, buffer->ondisk);
795         }
796
797         if (buffer->ondisk == NULL) {
798                 if (isnew) {
799                         error = hammer_io_new(volume->devvp, &buffer->io);
800                 } else {
801                         error = hammer_io_read(volume->devvp, &buffer->io,
802                                                volume->maxraw_off);
803                 }
804                 if (error == 0)
805                         buffer->ondisk = (void *)buffer->io.bp->b_data;
806         } else if (isnew) {
807                 error = hammer_io_new(volume->devvp, &buffer->io);
808         } else {
809                 error = 0;
810         }
811         --buffer->io.loading;
812         hammer_unlock(&buffer->io.lock);
813         return (error);
814 }
815
816 /*
817  * NOTE: Called from RB_SCAN, must return >= 0 for scan to continue.
818  * This routine is only called during unmount or when a volume is
819  * removed.
820  *
821  * If data != NULL, it specifies a volume whoose buffers should
822  * be unloaded.
823  */
824 int
825 hammer_unload_buffer(hammer_buffer_t buffer, void *data)
826 {
827         struct hammer_volume *volume = (struct hammer_volume *) data;
828
829         if (volume != NULL && volume != buffer->io.volume) {
830                 /*
831                  * We are only interested in unloading buffers of volume,
832                  * so skip it
833                  */
834                 return 0;
835         }
836
837         /*
838          * Clean up the persistent ref ioerror might have on the buffer
839          * and acquire a ref (steal ioerror's if we can).
840          */
841         if (buffer->io.ioerror) {
842                 buffer->io.ioerror = 0;
843         } else {
844                 if (buffer->io.lock.refs == 0)
845                         ++hammer_count_refedbufs;
846                 hammer_ref(&buffer->io.lock);
847         }
848
849         /*
850          * We must not flush a dirty buffer to disk on umount.  It should
851          * have already been dealt with by the flusher, or we may be in
852          * catastrophic failure.
853          *
854          * We must set waitdep to ensure that a running buffer is waited
855          * on and released prior to us trying to unload the volume.
856          */
857         hammer_io_clear_modify(&buffer->io, 1);
858         hammer_flush_buffer_nodes(buffer);
859         KKASSERT(buffer->io.lock.refs == 1);
860         buffer->io.waitdep = 1;
861         hammer_rel_buffer(buffer, 2);
862         return(0);
863 }
864
865 /*
866  * Reference a buffer that is either already referenced or via a specially
867  * handled pointer (aka cursor->buffer).
868  */
869 int
870 hammer_ref_buffer(hammer_buffer_t buffer)
871 {
872         int error;
873
874         if (buffer->io.lock.refs == 0)
875                 ++hammer_count_refedbufs;
876         hammer_ref(&buffer->io.lock);
877
878         /*
879          * At this point a biodone() will not touch the buffer other then
880          * incidental bits.  However, lose_list can be modified via
881          * a biodone() interrupt.
882          *
883          * No longer loose
884          */
885         if (buffer->io.mod_list == &buffer->io.hmp->lose_list) {
886                 crit_enter();
887                 TAILQ_REMOVE(buffer->io.mod_list, &buffer->io, mod_entry);
888                 buffer->io.mod_list = NULL;
889                 crit_exit();
890         }
891
892         if (buffer->ondisk == NULL || buffer->io.loading) {
893                 error = hammer_load_buffer(buffer, 0);
894                 if (error) {
895                         hammer_rel_buffer(buffer, 1);
896                         /*
897                          * NOTE: buffer pointer can become stale after
898                          * the above release.
899                          */
900                 }
901         } else {
902                 error = 0;
903         }
904         return(error);
905 }
906
907 /*
908  * Release a buffer.  We have to deal with several places where
909  * another thread can ref the buffer.
910  *
911  * Only destroy the structure itself if the related buffer cache buffer
912  * was disassociated from it.  This ties the management of the structure
913  * to the buffer cache subsystem.  buffer->ondisk determines whether the
914  * embedded io is referenced or not.
915  */
916 void
917 hammer_rel_buffer(hammer_buffer_t buffer, int flush)
918 {
919         hammer_volume_t volume;
920         hammer_mount_t hmp;
921         struct buf *bp = NULL;
922         int freeme = 0;
923
924         hmp = buffer->io.hmp;
925
926         crit_enter();
927         if (buffer->io.lock.refs == 1) {
928                 ++buffer->io.loading;   /* force interlock check */
929                 hammer_lock_ex(&buffer->io.lock);
930                 if (buffer->io.lock.refs == 1) {
931                         bp = hammer_io_release(&buffer->io, flush);
932
933                         if (buffer->io.lock.refs == 1)
934                                 --hammer_count_refedbufs;
935
936                         if (buffer->io.bp == NULL &&
937                             buffer->io.lock.refs == 1) {
938                                 /*
939                                  * Final cleanup
940                                  *
941                                  * NOTE: It is impossible for any associated
942                                  * B-Tree nodes to have refs if the buffer
943                                  * has no additional refs.
944                                  */
945                                 RB_REMOVE(hammer_buf_rb_tree,
946                                           &buffer->io.hmp->rb_bufs_root,
947                                           buffer);
948                                 volume = buffer->io.volume;
949                                 buffer->io.volume = NULL; /* sanity */
950                                 hammer_rel_volume(volume, 0);
951                                 hammer_io_clear_modlist(&buffer->io);
952                                 hammer_flush_buffer_nodes(buffer);
953                                 KKASSERT(TAILQ_EMPTY(&buffer->clist));
954                                 freeme = 1;
955                         }
956                 }
957                 --buffer->io.loading;
958                 hammer_unlock(&buffer->io.lock);
959         }
960         hammer_unref(&buffer->io.lock);
961         crit_exit();
962         if (bp)
963                 brelse(bp);
964         if (freeme) {
965                 --hammer_count_buffers;
966                 kfree(buffer, hmp->m_misc);
967         }
968 }
969
970 /*
971  * Access the filesystem buffer containing the specified hammer offset.
972  * buf_offset is a conglomeration of the volume number and vol_buf_beg
973  * relative buffer offset.  It must also have bit 55 set to be valid.
974  * (see hammer_off_t in hammer_disk.h).
975  *
976  * Any prior buffer in *bufferp will be released and replaced by the
977  * requested buffer.
978  *
979  * NOTE: The buffer is indexed via its zoneX_offset but we allow the
980  * passed cached *bufferp to match against either zoneX or zone2.
981  */
982 static __inline
983 void *
984 _hammer_bread(hammer_mount_t hmp, hammer_off_t buf_offset, int bytes,
985              int *errorp, struct hammer_buffer **bufferp)
986 {
987         hammer_buffer_t buffer;
988         int32_t xoff = (int32_t)buf_offset & HAMMER_BUFMASK;
989
990         buf_offset &= ~HAMMER_BUFMASK64;
991         KKASSERT((buf_offset & HAMMER_OFF_ZONE_MASK) != 0);
992
993         buffer = *bufferp;
994         if (buffer == NULL || (buffer->zone2_offset != buf_offset &&
995                                buffer->zoneX_offset != buf_offset)) {
996                 if (buffer)
997                         hammer_rel_buffer(buffer, 0);
998                 buffer = hammer_get_buffer(hmp, buf_offset, bytes, 0, errorp);
999                 *bufferp = buffer;
1000         } else {
1001                 *errorp = 0;
1002         }
1003
1004         /*
1005          * Return a pointer to the buffer data.
1006          */
1007         if (buffer == NULL)
1008                 return(NULL);
1009         else
1010                 return((char *)buffer->ondisk + xoff);
1011 }
1012
1013 void *
1014 hammer_bread(hammer_mount_t hmp, hammer_off_t buf_offset,
1015              int *errorp, struct hammer_buffer **bufferp)
1016 {
1017         return(_hammer_bread(hmp, buf_offset, HAMMER_BUFSIZE, errorp, bufferp));
1018 }
1019
1020 void *
1021 hammer_bread_ext(hammer_mount_t hmp, hammer_off_t buf_offset, int bytes,
1022                  int *errorp, struct hammer_buffer **bufferp)
1023 {
1024         bytes = (bytes + HAMMER_BUFMASK) & ~HAMMER_BUFMASK;
1025         return(_hammer_bread(hmp, buf_offset, bytes, errorp, bufferp));
1026 }
1027
1028 /*
1029  * Access the filesystem buffer containing the specified hammer offset.
1030  * No disk read operation occurs.  The result buffer may contain garbage.
1031  *
1032  * Any prior buffer in *bufferp will be released and replaced by the
1033  * requested buffer.
1034  *
1035  * This function marks the buffer dirty but does not increment its
1036  * modify_refs count.
1037  */
1038 static __inline
1039 void *
1040 _hammer_bnew(hammer_mount_t hmp, hammer_off_t buf_offset, int bytes,
1041              int *errorp, struct hammer_buffer **bufferp)
1042 {
1043         hammer_buffer_t buffer;
1044         int32_t xoff = (int32_t)buf_offset & HAMMER_BUFMASK;
1045
1046         buf_offset &= ~HAMMER_BUFMASK64;
1047
1048         buffer = *bufferp;
1049         if (buffer == NULL || (buffer->zone2_offset != buf_offset &&
1050                                buffer->zoneX_offset != buf_offset)) {
1051                 if (buffer)
1052                         hammer_rel_buffer(buffer, 0);
1053                 buffer = hammer_get_buffer(hmp, buf_offset, bytes, 1, errorp);
1054                 *bufferp = buffer;
1055         } else {
1056                 *errorp = 0;
1057         }
1058
1059         /*
1060          * Return a pointer to the buffer data.
1061          */
1062         if (buffer == NULL)
1063                 return(NULL);
1064         else
1065                 return((char *)buffer->ondisk + xoff);
1066 }
1067
1068 void *
1069 hammer_bnew(hammer_mount_t hmp, hammer_off_t buf_offset,
1070              int *errorp, struct hammer_buffer **bufferp)
1071 {
1072         return(_hammer_bnew(hmp, buf_offset, HAMMER_BUFSIZE, errorp, bufferp));
1073 }
1074
1075 void *
1076 hammer_bnew_ext(hammer_mount_t hmp, hammer_off_t buf_offset, int bytes,
1077                 int *errorp, struct hammer_buffer **bufferp)
1078 {
1079         bytes = (bytes + HAMMER_BUFMASK) & ~HAMMER_BUFMASK;
1080         return(_hammer_bnew(hmp, buf_offset, bytes, errorp, bufferp));
1081 }
1082
1083 /************************************************************************
1084  *                              NODES                                   *
1085  ************************************************************************
1086  *
1087  * Manage B-Tree nodes.  B-Tree nodes represent the primary indexing
1088  * method used by the HAMMER filesystem.
1089  *
1090  * Unlike other HAMMER structures, a hammer_node can be PASSIVELY
1091  * associated with its buffer, and will only referenced the buffer while
1092  * the node itself is referenced.
1093  *
1094  * A hammer_node can also be passively associated with other HAMMER
1095  * structures, such as inodes, while retaining 0 references.  These
1096  * associations can be cleared backwards using a pointer-to-pointer in
1097  * the hammer_node.
1098  *
1099  * This allows the HAMMER implementation to cache hammer_nodes long-term
1100  * and short-cut a great deal of the infrastructure's complexity.  In
1101  * most cases a cached node can be reacquired without having to dip into
1102  * either the buffer or cluster management code.
1103  *
1104  * The caller must pass a referenced cluster on call and will retain
1105  * ownership of the reference on return.  The node will acquire its own
1106  * additional references, if necessary.
1107  */
1108 hammer_node_t
1109 hammer_get_node(hammer_transaction_t trans, hammer_off_t node_offset,
1110                 int isnew, int *errorp)
1111 {
1112         hammer_mount_t hmp = trans->hmp;
1113         hammer_node_t node;
1114
1115         KKASSERT((node_offset & HAMMER_OFF_ZONE_MASK) == HAMMER_ZONE_BTREE);
1116
1117         /*
1118          * Locate the structure, allocating one if necessary.
1119          */
1120 again:
1121         node = RB_LOOKUP(hammer_nod_rb_tree, &hmp->rb_nods_root, node_offset);
1122         if (node == NULL) {
1123                 ++hammer_count_nodes;
1124                 node = kmalloc(sizeof(*node), hmp->m_misc, M_WAITOK|M_ZERO|M_USE_RESERVE);
1125                 node->node_offset = node_offset;
1126                 node->hmp = hmp;
1127                 TAILQ_INIT(&node->cursor_list);
1128                 TAILQ_INIT(&node->cache_list);
1129                 if (RB_INSERT(hammer_nod_rb_tree, &hmp->rb_nods_root, node)) {
1130                         --hammer_count_nodes;
1131                         kfree(node, hmp->m_misc);
1132                         goto again;
1133                 }
1134         }
1135         hammer_ref(&node->lock);
1136         if (node->ondisk) {
1137                 *errorp = 0;
1138                 hammer_io_advance(&node->buffer->io);
1139         } else {
1140                 *errorp = hammer_load_node(trans, node, isnew);
1141                 trans->flags |= HAMMER_TRANSF_DIDIO;
1142         }
1143         if (*errorp) {
1144                 hammer_rel_node(node);
1145                 node = NULL;
1146         }
1147         return(node);
1148 }
1149
1150 /*
1151  * Reference an already-referenced node.
1152  */
1153 void
1154 hammer_ref_node(hammer_node_t node)
1155 {
1156         KKASSERT(node->lock.refs > 0 && node->ondisk != NULL);
1157         hammer_ref(&node->lock);
1158 }
1159
1160 /*
1161  * Load a node's on-disk data reference.
1162  */
1163 static int
1164 hammer_load_node(hammer_transaction_t trans, hammer_node_t node, int isnew)
1165 {
1166         hammer_buffer_t buffer;
1167         hammer_off_t buf_offset;
1168         int error;
1169
1170         error = 0;
1171         ++node->loading;
1172         hammer_lock_ex(&node->lock);
1173         if (node->ondisk == NULL) {
1174                 /*
1175                  * This is a little confusing but the jist is that
1176                  * node->buffer determines whether the node is on
1177                  * the buffer's clist and node->ondisk determines
1178                  * whether the buffer is referenced.
1179                  *
1180                  * We could be racing a buffer release, in which case
1181                  * node->buffer may become NULL while we are blocked
1182                  * referencing the buffer.
1183                  */
1184                 if ((buffer = node->buffer) != NULL) {
1185                         error = hammer_ref_buffer(buffer);
1186                         if (error == 0 && node->buffer == NULL) {
1187                                 TAILQ_INSERT_TAIL(&buffer->clist,
1188                                                   node, entry);
1189                                 node->buffer = buffer;
1190                         }
1191                 } else {
1192                         buf_offset = node->node_offset & ~HAMMER_BUFMASK64;
1193                         buffer = hammer_get_buffer(node->hmp, buf_offset,
1194                                                    HAMMER_BUFSIZE, 0, &error);
1195                         if (buffer) {
1196                                 KKASSERT(error == 0);
1197                                 TAILQ_INSERT_TAIL(&buffer->clist,
1198                                                   node, entry);
1199                                 node->buffer = buffer;
1200                         }
1201                 }
1202                 if (error)
1203                         goto failed;
1204                 node->ondisk = (void *)((char *)buffer->ondisk +
1205                                         (node->node_offset & HAMMER_BUFMASK));
1206
1207                 /*
1208                  * Check CRC.  NOTE: Neither flag is set and the CRC is not
1209                  * generated on new B-Tree nodes.
1210                  */
1211                 if (isnew == 0 && 
1212                     (node->flags & HAMMER_NODE_CRCANY) == 0) {
1213                         if (hammer_crc_test_btree(node->ondisk) == 0) {
1214                                 if (hammer_debug_critical)
1215                                         Debugger("CRC FAILED: B-TREE NODE");
1216                                 node->flags |= HAMMER_NODE_CRCBAD;
1217                         } else {
1218                                 node->flags |= HAMMER_NODE_CRCGOOD;
1219                         }
1220                 }
1221         }
1222         if (node->flags & HAMMER_NODE_CRCBAD) {
1223                 if (trans->flags & HAMMER_TRANSF_CRCDOM)
1224                         error = EDOM;
1225                 else
1226                         error = EIO;
1227         }
1228 failed:
1229         --node->loading;
1230         hammer_unlock(&node->lock);
1231         return (error);
1232 }
1233
1234 /*
1235  * Safely reference a node, interlock against flushes via the IO subsystem.
1236  */
1237 hammer_node_t
1238 hammer_ref_node_safe(hammer_transaction_t trans, hammer_node_cache_t cache,
1239                      int *errorp)
1240 {
1241         hammer_node_t node;
1242
1243         node = cache->node;
1244         if (node != NULL) {
1245                 hammer_ref(&node->lock);
1246                 if (node->ondisk) {
1247                         if (node->flags & HAMMER_NODE_CRCBAD) {
1248                                 if (trans->flags & HAMMER_TRANSF_CRCDOM)
1249                                         *errorp = EDOM;
1250                                 else
1251                                         *errorp = EIO;
1252                         } else {
1253                                 *errorp = 0;
1254                         }
1255                 } else {
1256                         *errorp = hammer_load_node(trans, node, 0);
1257                 }
1258                 if (*errorp) {
1259                         hammer_rel_node(node);
1260                         node = NULL;
1261                 }
1262         } else {
1263                 *errorp = ENOENT;
1264         }
1265         return(node);
1266 }
1267
1268 /*
1269  * Release a hammer_node.  On the last release the node dereferences
1270  * its underlying buffer and may or may not be destroyed.
1271  */
1272 void
1273 hammer_rel_node(hammer_node_t node)
1274 {
1275         hammer_buffer_t buffer;
1276
1277         /*
1278          * If this isn't the last ref just decrement the ref count and
1279          * return.
1280          */
1281         if (node->lock.refs > 1) {
1282                 hammer_unref(&node->lock);
1283                 return;
1284         }
1285
1286         /*
1287          * If there is no ondisk info or no buffer the node failed to load,
1288          * remove the last reference and destroy the node.
1289          */
1290         if (node->ondisk == NULL) {
1291                 hammer_unref(&node->lock);
1292                 hammer_flush_node(node);
1293                 /* node is stale now */
1294                 return;
1295         }
1296
1297         /*
1298          * Do not disassociate the node from the buffer if it represents
1299          * a modified B-Tree node that still needs its crc to be generated.
1300          */
1301         if (node->flags & HAMMER_NODE_NEEDSCRC)
1302                 return;
1303
1304         /*
1305          * Do final cleanups and then either destroy the node and leave it
1306          * passively cached.  The buffer reference is removed regardless.
1307          */
1308         buffer = node->buffer;
1309         node->ondisk = NULL;
1310
1311         if ((node->flags & HAMMER_NODE_FLUSH) == 0) {
1312                 hammer_unref(&node->lock);
1313                 hammer_rel_buffer(buffer, 0);
1314                 return;
1315         }
1316
1317         /*
1318          * Destroy the node.
1319          */
1320         hammer_unref(&node->lock);
1321         hammer_flush_node(node);
1322         /* node is stale */
1323         hammer_rel_buffer(buffer, 0);
1324 }
1325
1326 /*
1327  * Free space on-media associated with a B-Tree node.
1328  */
1329 void
1330 hammer_delete_node(hammer_transaction_t trans, hammer_node_t node)
1331 {
1332         KKASSERT((node->flags & HAMMER_NODE_DELETED) == 0);
1333         node->flags |= HAMMER_NODE_DELETED;
1334         hammer_blockmap_free(trans, node->node_offset, sizeof(*node->ondisk));
1335 }
1336
1337 /*
1338  * Passively cache a referenced hammer_node.  The caller may release
1339  * the node on return.
1340  */
1341 void
1342 hammer_cache_node(hammer_node_cache_t cache, hammer_node_t node)
1343 {
1344         /*
1345          * If the node doesn't exist, or is being deleted, don't cache it!
1346          *
1347          * The node can only ever be NULL in the I/O failure path.
1348          */
1349         if (node == NULL || (node->flags & HAMMER_NODE_DELETED))
1350                 return;
1351         if (cache->node == node)
1352                 return;
1353         while (cache->node)
1354                 hammer_uncache_node(cache);
1355         if (node->flags & HAMMER_NODE_DELETED)
1356                 return;
1357         cache->node = node;
1358         TAILQ_INSERT_TAIL(&node->cache_list, cache, entry);
1359 }
1360
1361 void
1362 hammer_uncache_node(hammer_node_cache_t cache)
1363 {
1364         hammer_node_t node;
1365
1366         if ((node = cache->node) != NULL) {
1367                 TAILQ_REMOVE(&node->cache_list, cache, entry);
1368                 cache->node = NULL;
1369                 if (TAILQ_EMPTY(&node->cache_list))
1370                         hammer_flush_node(node);
1371         }
1372 }
1373
1374 /*
1375  * Remove a node's cache references and destroy the node if it has no
1376  * other references or backing store.
1377  */
1378 void
1379 hammer_flush_node(hammer_node_t node)
1380 {
1381         hammer_node_cache_t cache;
1382         hammer_buffer_t buffer;
1383         hammer_mount_t hmp = node->hmp;
1384
1385         while ((cache = TAILQ_FIRST(&node->cache_list)) != NULL) {
1386                 TAILQ_REMOVE(&node->cache_list, cache, entry);
1387                 cache->node = NULL;
1388         }
1389         if (node->lock.refs == 0 && node->ondisk == NULL) {
1390                 KKASSERT((node->flags & HAMMER_NODE_NEEDSCRC) == 0);
1391                 RB_REMOVE(hammer_nod_rb_tree, &node->hmp->rb_nods_root, node);
1392                 if ((buffer = node->buffer) != NULL) {
1393                         node->buffer = NULL;
1394                         TAILQ_REMOVE(&buffer->clist, node, entry);
1395                         /* buffer is unreferenced because ondisk is NULL */
1396                 }
1397                 --hammer_count_nodes;
1398                 kfree(node, hmp->m_misc);
1399         }
1400 }
1401
1402 /*
1403  * Flush passively cached B-Tree nodes associated with this buffer.
1404  * This is only called when the buffer is about to be destroyed, so
1405  * none of the nodes should have any references.  The buffer is locked.
1406  *
1407  * We may be interlocked with the buffer.
1408  */
1409 void
1410 hammer_flush_buffer_nodes(hammer_buffer_t buffer)
1411 {
1412         hammer_node_t node;
1413
1414         while ((node = TAILQ_FIRST(&buffer->clist)) != NULL) {
1415                 KKASSERT(node->ondisk == NULL);
1416                 KKASSERT((node->flags & HAMMER_NODE_NEEDSCRC) == 0);
1417
1418                 if (node->lock.refs == 0) {
1419                         hammer_ref(&node->lock);
1420                         node->flags |= HAMMER_NODE_FLUSH;
1421                         hammer_rel_node(node);
1422                 } else {
1423                         KKASSERT(node->loading != 0);
1424                         KKASSERT(node->buffer != NULL);
1425                         buffer = node->buffer;
1426                         node->buffer = NULL;
1427                         TAILQ_REMOVE(&buffer->clist, node, entry);
1428                         /* buffer is unreferenced because ondisk is NULL */
1429                 }
1430         }
1431 }
1432
1433
1434 /************************************************************************
1435  *                              ALLOCATORS                              *
1436  ************************************************************************/
1437
1438 /*
1439  * Allocate a B-Tree node.
1440  */
1441 hammer_node_t
1442 hammer_alloc_btree(hammer_transaction_t trans, hammer_off_t hint, int *errorp)
1443 {
1444         hammer_buffer_t buffer = NULL;
1445         hammer_node_t node = NULL;
1446         hammer_off_t node_offset;
1447
1448         node_offset = hammer_blockmap_alloc(trans, HAMMER_ZONE_BTREE_INDEX,
1449                                             sizeof(struct hammer_node_ondisk),
1450                                             hint, errorp);
1451         if (*errorp == 0) {
1452                 node = hammer_get_node(trans, node_offset, 1, errorp);
1453                 hammer_modify_node_noundo(trans, node);
1454                 bzero(node->ondisk, sizeof(*node->ondisk));
1455                 hammer_modify_node_done(node);
1456         }
1457         if (buffer)
1458                 hammer_rel_buffer(buffer, 0);
1459         return(node);
1460 }
1461
1462 /*
1463  * Allocate data.  If the address of a data buffer is supplied then
1464  * any prior non-NULL *data_bufferp will be released and *data_bufferp
1465  * will be set to the related buffer.  The caller must release it when
1466  * finally done.  The initial *data_bufferp should be set to NULL by
1467  * the caller.
1468  *
1469  * The caller is responsible for making hammer_modify*() calls on the
1470  * *data_bufferp.
1471  */
1472 void *
1473 hammer_alloc_data(hammer_transaction_t trans, int32_t data_len, 
1474                   u_int16_t rec_type, hammer_off_t *data_offsetp,
1475                   struct hammer_buffer **data_bufferp,
1476                   hammer_off_t hint, int *errorp)
1477 {
1478         void *data;
1479         int zone;
1480
1481         /*
1482          * Allocate data
1483          */
1484         if (data_len) {
1485                 switch(rec_type) {
1486                 case HAMMER_RECTYPE_INODE:
1487                 case HAMMER_RECTYPE_DIRENTRY:
1488                 case HAMMER_RECTYPE_EXT:
1489                 case HAMMER_RECTYPE_FIX:
1490                 case HAMMER_RECTYPE_PFS:
1491                 case HAMMER_RECTYPE_SNAPSHOT:
1492                 case HAMMER_RECTYPE_CONFIG:
1493                         zone = HAMMER_ZONE_META_INDEX;
1494                         break;
1495                 case HAMMER_RECTYPE_DATA:
1496                 case HAMMER_RECTYPE_DB:
1497                         if (data_len <= HAMMER_BUFSIZE / 2) {
1498                                 zone = HAMMER_ZONE_SMALL_DATA_INDEX;
1499                         } else {
1500                                 data_len = (data_len + HAMMER_BUFMASK) &
1501                                            ~HAMMER_BUFMASK;
1502                                 zone = HAMMER_ZONE_LARGE_DATA_INDEX;
1503                         }
1504                         break;
1505                 default:
1506                         panic("hammer_alloc_data: rec_type %04x unknown",
1507                               rec_type);
1508                         zone = 0;       /* NOT REACHED */
1509                         break;
1510                 }
1511                 *data_offsetp = hammer_blockmap_alloc(trans, zone, data_len,
1512                                                       hint, errorp);
1513         } else {
1514                 *data_offsetp = 0;
1515         }
1516         if (*errorp == 0 && data_bufferp) {
1517                 if (data_len) {
1518                         data = hammer_bread_ext(trans->hmp, *data_offsetp,
1519                                                 data_len, errorp, data_bufferp);
1520                 } else {
1521                         data = NULL;
1522                 }
1523         } else {
1524                 data = NULL;
1525         }
1526         return(data);
1527 }
1528
1529 /*
1530  * Sync dirty buffers to the media and clean-up any loose ends.
1531  *
1532  * These functions do not start the flusher going, they simply
1533  * queue everything up to the flusher.
1534  */
1535 static int hammer_sync_scan1(struct mount *mp, struct vnode *vp, void *data);
1536 static int hammer_sync_scan2(struct mount *mp, struct vnode *vp, void *data);
1537
1538 int
1539 hammer_queue_inodes_flusher(hammer_mount_t hmp, int waitfor)
1540 {
1541         struct hammer_sync_info info;
1542
1543         info.error = 0;
1544         info.waitfor = waitfor;
1545         if (waitfor == MNT_WAIT) {
1546                 vmntvnodescan(hmp->mp, VMSC_GETVP|VMSC_ONEPASS,
1547                               hammer_sync_scan1, hammer_sync_scan2, &info);
1548         } else {
1549                 vmntvnodescan(hmp->mp, VMSC_GETVP|VMSC_ONEPASS|VMSC_NOWAIT,
1550                               hammer_sync_scan1, hammer_sync_scan2, &info);
1551         }
1552         return(info.error);
1553 }
1554
1555 /*
1556  * Filesystem sync.  If doing a synchronous sync make a second pass on
1557  * the vnodes in case any were already flushing during the first pass,
1558  * and activate the flusher twice (the second time brings the UNDO FIFO's
1559  * start position up to the end position after the first call).
1560  */
1561 int
1562 hammer_sync_hmp(hammer_mount_t hmp, int waitfor)
1563 {
1564         struct hammer_sync_info info;
1565
1566         info.error = 0;
1567         info.waitfor = MNT_NOWAIT;
1568         vmntvnodescan(hmp->mp, VMSC_GETVP|VMSC_NOWAIT,
1569                       hammer_sync_scan1, hammer_sync_scan2, &info);
1570         if (info.error == 0 && waitfor == MNT_WAIT) {
1571                 info.waitfor = waitfor;
1572                 vmntvnodescan(hmp->mp, VMSC_GETVP,
1573                               hammer_sync_scan1, hammer_sync_scan2, &info);
1574         }
1575         if (waitfor == MNT_WAIT) {
1576                 hammer_flusher_sync(hmp);
1577                 hammer_flusher_sync(hmp);
1578         } else {
1579                 hammer_flusher_async(hmp, NULL);
1580                 hammer_flusher_async(hmp, NULL);
1581         }
1582         return(info.error);
1583 }
1584
1585 static int
1586 hammer_sync_scan1(struct mount *mp, struct vnode *vp, void *data)
1587 {
1588         struct hammer_inode *ip;
1589
1590         ip = VTOI(vp);
1591         if (vp->v_type == VNON || ip == NULL ||
1592             ((ip->flags & HAMMER_INODE_MODMASK) == 0 &&
1593              RB_EMPTY(&vp->v_rbdirty_tree))) {
1594                 return(-1);
1595         }
1596         return(0);
1597 }
1598
1599 static int
1600 hammer_sync_scan2(struct mount *mp, struct vnode *vp, void *data)
1601 {
1602         struct hammer_sync_info *info = data;
1603         struct hammer_inode *ip;
1604         int error;
1605
1606         ip = VTOI(vp);
1607         if (vp->v_type == VNON || vp->v_type == VBAD ||
1608             ((ip->flags & HAMMER_INODE_MODMASK) == 0 &&
1609              RB_EMPTY(&vp->v_rbdirty_tree))) {
1610                 return(0);
1611         }
1612         error = VOP_FSYNC(vp, MNT_NOWAIT, 0);
1613         if (error)
1614                 info->error = error;
1615         return(0);
1616 }
1617