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