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