Home | History | Annotate | Line # | Download | only in ffs
ffs_wapbl.c revision 1.36
      1 /*	$NetBSD: ffs_wapbl.c,v 1.36 2016/11/10 20:56:32 jdolecek Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2003,2006,2008 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Wasabi Systems, Inc.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 __KERNEL_RCSID(0, "$NetBSD: ffs_wapbl.c,v 1.36 2016/11/10 20:56:32 jdolecek Exp $");
     34 
     35 #define WAPBL_INTERNAL
     36 
     37 #if defined(_KERNEL_OPT)
     38 #include "opt_ffs.h"
     39 #endif
     40 
     41 #include <sys/param.h>
     42 #include <sys/systm.h>
     43 #include <sys/kernel.h>
     44 #include <sys/vnode.h>
     45 #include <sys/mount.h>
     46 #include <sys/file.h>
     47 #include <sys/disk.h>
     48 #include <sys/ioctl.h>
     49 #include <sys/errno.h>
     50 #include <sys/kauth.h>
     51 #include <sys/wapbl.h>
     52 
     53 #include <ufs/ufs/inode.h>
     54 #include <ufs/ufs/quota.h>
     55 #include <ufs/ufs/ufsmount.h>
     56 #include <ufs/ufs/ufs_bswap.h>
     57 #include <ufs/ufs/ufs_extern.h>
     58 #include <ufs/ufs/ufs_wapbl.h>
     59 
     60 #include <ufs/ffs/fs.h>
     61 #include <ufs/ffs/ffs_extern.h>
     62 
     63 #undef	WAPBL_DEBUG
     64 #ifdef WAPBL_DEBUG
     65 int ffs_wapbl_debug = 1;
     66 #define DPRINTF(fmt, args...)						\
     67 do {									\
     68 	if (ffs_wapbl_debug)						\
     69 		printf("%s:%d "fmt, __func__ , __LINE__, ##args);	\
     70 } while (/* CONSTCOND */0)
     71 #else
     72 #define	DPRINTF(fmt, args...)						\
     73 do {									\
     74 	/* nothing */							\
     75 } while (/* CONSTCOND */0)
     76 #endif
     77 
     78 static int ffs_superblock_layout(struct fs *);
     79 static int wapbl_log_position(struct mount *, struct fs *, struct vnode *,
     80     daddr_t *, size_t *, size_t *, uint64_t *);
     81 static int wapbl_create_infs_log(struct mount *, struct fs *, struct vnode *,
     82     daddr_t *, size_t *, uint64_t *);
     83 static void wapbl_find_log_start(struct mount *, struct vnode *, off_t,
     84     daddr_t *, daddr_t *, size_t *);
     85 static int wapbl_remove_log(struct mount *);
     86 static int wapbl_allocate_log_file(struct mount *, struct vnode *,
     87     daddr_t *, size_t *, uint64_t *);
     88 
     89 /*
     90  * Return the super block layout format - UFS1 or UFS2.
     91  * WAPBL only works with UFS2 layout (which is still available
     92  * with FFSv1).
     93  *
     94  * XXX Should this be in ufs/ffs/fs.h?  Same style of check is
     95  * also used in ffs_alloc.c in a few places.
     96  */
     97 static int
     98 ffs_superblock_layout(struct fs *fs)
     99 {
    100 	if ((fs->fs_magic == FS_UFS1_MAGIC) &&
    101 	    ((fs->fs_old_flags & FS_FLAGS_UPDATED) == 0))
    102 		return 1;
    103 	else
    104 		return 2;
    105 }
    106 
    107 /*
    108  * This function is invoked after a log is replayed to
    109  * disk to perform logical cleanup actions as described by
    110  * the log
    111  */
    112 void
    113 ffs_wapbl_replay_finish(struct mount *mp)
    114 {
    115 	struct wapbl_replay *wr = mp->mnt_wapbl_replay;
    116 	int i;
    117 	int error;
    118 
    119 	if (!wr)
    120 		return;
    121 
    122 	KDASSERT((mp->mnt_flag & MNT_RDONLY) == 0);
    123 
    124 	for (i = 0; i < wr->wr_inodescnt; i++) {
    125 		struct vnode *vp;
    126 		struct inode *ip;
    127 		error = VFS_VGET(mp, wr->wr_inodes[i].wr_inumber, &vp);
    128 		if (error) {
    129 			printf("%s: %s: unable to cleanup inode %" PRIu32 "\n",
    130 			    __func__, VFSTOUFS(mp)->um_fs->fs_fsmnt,
    131 			    wr->wr_inodes[i].wr_inumber);
    132 			continue;
    133 		}
    134 		ip = VTOI(vp);
    135 		KDASSERT(wr->wr_inodes[i].wr_inumber == ip->i_number);
    136 #ifdef WAPBL_DEBUG
    137 		printf("%s%s: %s: cleaning inode %" PRIu64 " size=%" PRIu64
    138 		    " mode=%o nlink=%d\n",
    139 		    __func__, VFSTOUFS(mp)->um_fs->fs_fsmnt,
    140 		    ip->i_number, ip->i_size, ip->i_mode, ip->i_nlink);
    141 #endif
    142 		KASSERT(ip->i_nlink == 0);
    143 
    144 		/*
    145 		 * The journal may have left partially allocated inodes in mode
    146 		 * zero.  This may occur if a crash occurs betweeen the node
    147 		 * allocation in ffs_nodeallocg and when the node is properly
    148 		 * initialized in ufs_makeinode.  If so, just dallocate them.
    149 		 */
    150 		if (ip->i_mode == 0) {
    151 			error = UFS_WAPBL_BEGIN(mp);
    152 			if (error) {
    153 				printf("%s: %s: "
    154 				    "unable to cleanup inode %" PRIu32 "\n",
    155 				    __func__, VFSTOUFS(mp)->um_fs->fs_fsmnt,
    156 				    wr->wr_inodes[i].wr_inumber);
    157 			} else {
    158 				ffs_vfree(vp, ip->i_number,
    159 				    wr->wr_inodes[i].wr_imode);
    160 				UFS_WAPBL_END(mp);
    161 			}
    162 		}
    163 		vput(vp);
    164 	}
    165 	wapbl_replay_stop(wr);
    166 	wapbl_replay_free(wr);
    167 	mp->mnt_wapbl_replay = NULL;
    168 }
    169 
    170 /* Callback for wapbl */
    171 void
    172 ffs_wapbl_sync_metadata(struct mount *mp, struct wapbl_dealloc *fdealloc)
    173 {
    174 	struct ufsmount *ump = VFSTOUFS(mp);
    175 	struct fs *fs = ump->um_fs;
    176 	int error __diagused;
    177 	struct wapbl_dealloc *wd;
    178 
    179 	UFS_WAPBL_JLOCK_ASSERT(mp);
    180 
    181 #ifdef WAPBL_DEBUG_INODES
    182 	ufs_wapbl_verify_inodes(mp, __func__);
    183 #endif
    184 
    185 	for (wd = fdealloc; wd != NULL; wd = TAILQ_NEXT(wd, wd_entries)) {
    186 		/*
    187 		 * blkfree errors are unreported, might silently fail
    188 		 * if it cannot read the cylinder group block
    189 		 */
    190 		ffs_blkfree(fs, ump->um_devvp,
    191 		    FFS_DBTOFSB(fs, wd->wd_blkno), wd->wd_len, -1);
    192 	}
    193 
    194 	if (fs->fs_fmod != 0) {
    195 		fs->fs_fmod = 0;
    196 		fs->fs_time = time_second;
    197 		error = ffs_cgupdate(ump, 0);
    198 		KASSERT(error == 0);
    199 	}
    200 }
    201 
    202 void
    203 ffs_wapbl_abort_sync_metadata(struct mount *mp, struct wapbl_dealloc *fdealloc)
    204 {
    205 	struct ufsmount *ump = VFSTOUFS(mp);
    206 	struct fs *fs = ump->um_fs;
    207 	struct wapbl_dealloc *wd;
    208 
    209 	for (wd = fdealloc; wd != NULL; wd = TAILQ_NEXT(wd, wd_entries)) {
    210 		/*
    211 		 * Since the above blkfree may have failed, this blkalloc might
    212 		 * fail as well, so don't check its error.  Note that if the
    213 		 * blkfree succeeded above, then this shouldn't fail because
    214 		 * the buffer will be locked in the current transaction.
    215 		 */
    216 		ffs_blkalloc_ump(ump, FFS_DBTOFSB(fs, wd->wd_blkno),
    217 		    wd->wd_len);
    218 	}
    219 }
    220 
    221 static int
    222 wapbl_remove_log(struct mount *mp)
    223 {
    224 	struct ufsmount *ump = VFSTOUFS(mp);
    225 	struct fs *fs = ump->um_fs;
    226 	struct vnode *vp;
    227 	struct inode *ip;
    228 	ino_t log_ino;
    229 	int error;
    230 
    231 	/* If super block layout is too old to support WAPBL, return */
    232 	if (ffs_superblock_layout(fs) < 2)
    233 		return 0;
    234 
    235 	/* If all the log locators are 0, just clean up */
    236 	if (fs->fs_journallocs[0] == 0 &&
    237 	    fs->fs_journallocs[1] == 0 &&
    238 	    fs->fs_journallocs[2] == 0 &&
    239 	    fs->fs_journallocs[3] == 0) {
    240 		DPRINTF("empty locators, just clear\n");
    241 		goto done;
    242 	}
    243 
    244 	switch (fs->fs_journal_location) {
    245 	case UFS_WAPBL_JOURNALLOC_NONE:
    246 		/* nothing! */
    247 		DPRINTF("no log\n");
    248 		break;
    249 
    250 	case UFS_WAPBL_JOURNALLOC_IN_FILESYSTEM:
    251 		log_ino = fs->fs_journallocs[UFS_WAPBL_INFS_INO];
    252 		DPRINTF("in-fs log, ino = %" PRId64 "\n",log_ino);
    253 
    254 		/* if no existing log inode, just clear all fields and bail */
    255 		if (log_ino == 0)
    256 			goto done;
    257 		error = VFS_VGET(mp, log_ino, &vp);
    258 		if (error != 0) {
    259 			printf("%s: %s: vget failed %d\n", __func__,
    260 			    fs->fs_fsmnt, error);
    261 			/* clear out log info on error */
    262 			goto done;
    263 		}
    264 		ip = VTOI(vp);
    265 		KASSERT(log_ino == ip->i_number);
    266 		if ((ip->i_flags & SF_LOG) == 0) {
    267 			printf("%s: %s: try to clear non-log inode "
    268 			    "%" PRId64 "\n", __func__, fs->fs_fsmnt, log_ino);
    269 			vput(vp);
    270 			/* clear out log info on error */
    271 			goto done;
    272 		}
    273 
    274 		/*
    275 		 * remove the log inode by setting its link count back
    276 		 * to zero and bail.
    277 		 */
    278 		ip->i_nlink = 0;
    279 		DIP_ASSIGN(ip, nlink, 0);
    280 		vput(vp);
    281 		break;
    282 
    283 	case UFS_WAPBL_JOURNALLOC_END_PARTITION:
    284 		DPRINTF("end-of-partition log\n");
    285 		/* no extra work required */
    286 		break;
    287 
    288 	default:
    289 		printf("%s: %s: unknown journal type %d\n", __func__,
    290 		    fs->fs_fsmnt, fs->fs_journal_location);
    291 		break;
    292 	}
    293 
    294 
    295 done:
    296 	/* Clear out all previous knowledge of journal */
    297 	fs->fs_journal_version = 0;
    298 	fs->fs_journal_location = 0;
    299 	fs->fs_journal_flags = 0;
    300 	fs->fs_journallocs[0] = 0;
    301 	fs->fs_journallocs[1] = 0;
    302 	fs->fs_journallocs[2] = 0;
    303 	fs->fs_journallocs[3] = 0;
    304 	(void) ffs_sbupdate(ump, MNT_WAIT);
    305 
    306 	return 0;
    307 }
    308 
    309 int
    310 ffs_wapbl_start(struct mount *mp)
    311 {
    312 	struct ufsmount *ump = VFSTOUFS(mp);
    313 	struct fs *fs = ump->um_fs;
    314 	struct vnode *devvp = ump->um_devvp;
    315 	daddr_t off;
    316 	size_t count;
    317 	size_t blksize;
    318 	uint64_t extradata;
    319 	int error;
    320 
    321 	if (mp->mnt_wapbl == NULL) {
    322 		if (fs->fs_journal_flags & UFS_WAPBL_FLAGS_CLEAR_LOG) {
    323 			/* Clear out any existing journal file */
    324 			error = wapbl_remove_log(mp);
    325 			if (error != 0)
    326 				return error;
    327 		}
    328 
    329 		if (mp->mnt_flag & MNT_LOG) {
    330 			KDASSERT(fs->fs_ronly == 0);
    331 
    332 			/* WAPBL needs UFS2 format super block */
    333 			if (ffs_superblock_layout(fs) < 2) {
    334 				printf("%s: %s: fs superblock in old format, "
    335 				   "not journaling\n", __func__,
    336 				   VFSTOUFS(mp)->um_fs->fs_fsmnt);
    337 				mp->mnt_flag &= ~MNT_LOG;
    338 				return EINVAL;
    339 			}
    340 
    341 			error = wapbl_log_position(mp, fs, devvp, &off,
    342 			    &count, &blksize, &extradata);
    343 			if (error)
    344 				return error;
    345 
    346 			error = wapbl_start(&mp->mnt_wapbl, mp, devvp, off,
    347 			    count, blksize, mp->mnt_wapbl_replay,
    348 			    ffs_wapbl_sync_metadata,
    349 			    ffs_wapbl_abort_sync_metadata);
    350 			if (error)
    351 				return error;
    352 
    353 			mp->mnt_wapbl_op = &wapbl_ops;
    354 
    355 #ifdef WAPBL_DEBUG
    356 			printf("%s: %s: enabling logging\n", __func__,
    357 			    fs->fs_fsmnt);
    358 #endif
    359 
    360 			if ((fs->fs_flags & FS_DOWAPBL) == 0) {
    361 				fs->fs_flags |= FS_DOWAPBL;
    362 				if ((error = UFS_WAPBL_BEGIN(mp)) != 0)
    363 					goto out;
    364 				error = ffs_sbupdate(ump, MNT_WAIT);
    365 				if (error) {
    366 					UFS_WAPBL_END(mp);
    367 					goto out;
    368 				}
    369 				UFS_WAPBL_END(mp);
    370 				error = wapbl_flush(mp->mnt_wapbl, 1);
    371 				if (error)
    372 					goto out;
    373 			}
    374 		} else if (fs->fs_flags & FS_DOWAPBL) {
    375 			fs->fs_fmod = 1;
    376 			fs->fs_flags &= ~FS_DOWAPBL;
    377 		}
    378 	}
    379 
    380 	/*
    381 	 * It is recommended that you finish replay with logging enabled.
    382 	 * However, even if logging is not enabled, the remaining log
    383 	 * replay should be safely recoverable with an fsck, so perform
    384 	 * it anyway.
    385 	 */
    386 	if ((fs->fs_ronly == 0) && mp->mnt_wapbl_replay) {
    387 		int saveflag = mp->mnt_flag & MNT_RDONLY;
    388 		/*
    389 		 * Make sure MNT_RDONLY is not set so that the inode
    390 		 * cleanup in ufs_inactive will actually do its work.
    391 		 */
    392 		mp->mnt_flag &= ~MNT_RDONLY;
    393 		ffs_wapbl_replay_finish(mp);
    394 		mp->mnt_flag |= saveflag;
    395 		KASSERT(fs->fs_ronly == 0);
    396 	}
    397 
    398 	return 0;
    399 out:
    400 	ffs_wapbl_stop(mp, MNT_FORCE);
    401 	return error;
    402 }
    403 
    404 int
    405 ffs_wapbl_stop(struct mount *mp, int force)
    406 {
    407 	struct ufsmount *ump = VFSTOUFS(mp);
    408 	struct fs *fs = ump->um_fs;
    409 	int error;
    410 
    411 	if (mp->mnt_wapbl) {
    412 		KDASSERT(fs->fs_ronly == 0);
    413 
    414 		/*
    415 		 * Make sure turning off FS_DOWAPBL is only removed
    416 		 * as the only change in the final flush since otherwise
    417 		 * a transaction may reorder writes.
    418 		 */
    419 		error = wapbl_flush(mp->mnt_wapbl, 1);
    420 		if (error && !force)
    421 			return error;
    422 		if (error && force)
    423 			goto forceout;
    424 		error = UFS_WAPBL_BEGIN(mp);
    425 		if (error && !force)
    426 			return error;
    427 		if (error && force)
    428 			goto forceout;
    429 		KASSERT(fs->fs_flags & FS_DOWAPBL);
    430 
    431 		fs->fs_flags &= ~FS_DOWAPBL;
    432 		error = ffs_sbupdate(ump, MNT_WAIT);
    433 		KASSERT(error == 0);	/* XXX a bit drastic! */
    434 		UFS_WAPBL_END(mp);
    435 	forceout:
    436 		error = wapbl_stop(mp->mnt_wapbl, force);
    437 		if (error) {
    438 			KASSERT(!force);
    439 			fs->fs_flags |= FS_DOWAPBL;
    440 			return error;
    441 		}
    442 		fs->fs_flags &= ~FS_DOWAPBL; /* Repeat in case of forced error */
    443 		mp->mnt_wapbl = NULL;
    444 
    445 #ifdef WAPBL_DEBUG
    446 		printf("%s: %s: disabled logging\n", __func__, fs->fs_fsmnt);
    447 #endif
    448 	}
    449 
    450 	return 0;
    451 }
    452 
    453 int
    454 ffs_wapbl_replay_start(struct mount *mp, struct fs *fs, struct vnode *devvp)
    455 {
    456 	int error;
    457 	daddr_t off;
    458 	size_t count;
    459 	size_t blksize;
    460 	uint64_t extradata;
    461 
    462 	/*
    463 	 * WAPBL needs UFS2 format super block, if we got here with a
    464 	 * UFS1 format super block something is amiss...
    465 	 */
    466 	if (ffs_superblock_layout(fs) < 2)
    467 		return EINVAL;
    468 
    469 	error = wapbl_log_position(mp, fs, devvp, &off, &count, &blksize,
    470 	    &extradata);
    471 
    472 	if (error)
    473 		return error;
    474 
    475 	error = wapbl_replay_start(&mp->mnt_wapbl_replay, devvp, off,
    476 		count, blksize);
    477 	if (error)
    478 		return error;
    479 
    480 	mp->mnt_wapbl_op = &wapbl_ops;
    481 
    482 	return 0;
    483 }
    484 
    485 /*
    486  * If the superblock doesn't already have a recorded journal location
    487  * then we allocate the journal in one of two positions:
    488  *
    489  *  - At the end of the partition after the filesystem if there's
    490  *    enough space.  "Enough space" is defined as >= 1MB of journal
    491  *    per 1GB of filesystem or 64MB, whichever is smaller.
    492  *
    493  *  - Inside the filesystem.  We try to allocate a contiguous journal
    494  *    based on the total filesystem size - the target is 1MB of journal
    495  *    per 1GB of filesystem, up to a maximum journal size of 64MB.  As
    496  *    a worst case allowing for fragmentation, we'll allocate a journal
    497  *    1/4 of the desired size but never smaller than 1MB.
    498  *
    499  *    XXX In the future if we allow for non-contiguous journal files we
    500  *    can tighten the above restrictions.
    501  *
    502  * XXX
    503  * These seems like a lot of duplication both here and in some of
    504  * the userland tools (fsck_ffs, dumpfs, tunefs) with similar
    505  * "switch (fs_journal_location)" constructs.  Can we centralise
    506  * this sort of code somehow/somewhere?
    507  */
    508 static int
    509 wapbl_log_position(struct mount *mp, struct fs *fs, struct vnode *devvp,
    510     daddr_t *startp, size_t *countp, size_t *blksizep, uint64_t *extradatap)
    511 {
    512 	struct ufsmount *ump = VFSTOUFS(mp);
    513 	daddr_t logstart, logend, desired_logsize;
    514 	uint64_t numsecs;
    515 	unsigned secsize;
    516 	int error, location;
    517 
    518 	if (fs->fs_journal_version == UFS_WAPBL_VERSION) {
    519 		switch (fs->fs_journal_location) {
    520 		case UFS_WAPBL_JOURNALLOC_END_PARTITION:
    521 			DPRINTF("found existing end-of-partition log\n");
    522 			*startp = fs->fs_journallocs[UFS_WAPBL_EPART_ADDR];
    523 			*countp = fs->fs_journallocs[UFS_WAPBL_EPART_COUNT];
    524 			*blksizep = fs->fs_journallocs[UFS_WAPBL_EPART_BLKSZ];
    525 			DPRINTF(" start = %" PRId64 ", size = %zu, "
    526 			    "blksize = %zu\n", *startp, *countp, *blksizep);
    527 			return 0;
    528 
    529 		case UFS_WAPBL_JOURNALLOC_IN_FILESYSTEM:
    530 			DPRINTF("found existing in-filesystem log\n");
    531 			*startp = fs->fs_journallocs[UFS_WAPBL_INFS_ADDR];
    532 			*countp = fs->fs_journallocs[UFS_WAPBL_INFS_COUNT];
    533 			*blksizep = fs->fs_journallocs[UFS_WAPBL_INFS_BLKSZ];
    534 			DPRINTF(" start = %" PRId64 ", size = %zu, "
    535 			    "blksize = %zu\n", *startp, *countp, *blksizep);
    536 			return 0;
    537 
    538 		default:
    539 			printf("%s: %s: unknown journal type %d\n", __func__,
    540 			    fs->fs_fsmnt, fs->fs_journal_location);
    541 			return EINVAL;
    542 		}
    543 	}
    544 
    545 	desired_logsize =
    546 	    ffs_lfragtosize(fs, fs->fs_size) / UFS_WAPBL_JOURNAL_SCALE;
    547 	DPRINTF("desired log size = %" PRId64 " kB\n", desired_logsize / 1024);
    548 	desired_logsize = max(desired_logsize, UFS_WAPBL_MIN_JOURNAL_SIZE);
    549 	desired_logsize = min(desired_logsize, UFS_WAPBL_MAX_JOURNAL_SIZE);
    550 	DPRINTF("adjusted desired log size = %" PRId64 " kB\n",
    551 	    desired_logsize / 1024);
    552 
    553 	/* Is there space after after filesystem on partition for log? */
    554 	logstart = FFS_FSBTODB(fs, fs->fs_size);
    555 	error = getdisksize(devvp, &numsecs, &secsize);
    556 	if (error)
    557 		return error;
    558 	KDASSERT(secsize != 0);
    559 	logend = btodb(numsecs * secsize);
    560 
    561 	if (dbtob(logend - logstart) >= desired_logsize) {
    562 		DPRINTF("enough space, use end-of-partition log\n");
    563 
    564 		location = UFS_WAPBL_JOURNALLOC_END_PARTITION;
    565 		*blksizep = secsize;
    566 
    567 		*startp = logstart;
    568 		*countp = (logend - logstart);
    569 		*extradatap = 0;
    570 
    571 		/* convert to physical block numbers */
    572 		*startp = dbtob(*startp) / secsize;
    573 		*countp = dbtob(*countp) / secsize;
    574 
    575 		fs->fs_journallocs[UFS_WAPBL_EPART_ADDR] = *startp;
    576 		fs->fs_journallocs[UFS_WAPBL_EPART_COUNT] = *countp;
    577 		fs->fs_journallocs[UFS_WAPBL_EPART_BLKSZ] = *blksizep;
    578 		fs->fs_journallocs[UFS_WAPBL_EPART_UNUSED] = *extradatap;
    579 	} else {
    580 		DPRINTF("end-of-partition has only %" PRId64 " free\n",
    581 		    logend - logstart);
    582 
    583 		location = UFS_WAPBL_JOURNALLOC_IN_FILESYSTEM;
    584 		*blksizep = secsize;
    585 
    586 		error = wapbl_create_infs_log(mp, fs, devvp,
    587 		                  startp, countp, extradatap);
    588 		ffs_sync(mp, MNT_WAIT, FSCRED);
    589 
    590 		/* convert to physical block numbers */
    591 		*startp = dbtob(*startp) / secsize;
    592 		*countp = dbtob(*countp) / secsize;
    593 
    594 		fs->fs_journallocs[UFS_WAPBL_INFS_ADDR] = *startp;
    595 		fs->fs_journallocs[UFS_WAPBL_INFS_COUNT] = *countp;
    596 		fs->fs_journallocs[UFS_WAPBL_INFS_BLKSZ] = *blksizep;
    597 		fs->fs_journallocs[UFS_WAPBL_INFS_INO] = *extradatap;
    598 	}
    599 
    600 	if (error == 0) {
    601 		/* update superblock with log location */
    602 		fs->fs_journal_version = UFS_WAPBL_VERSION;
    603 		fs->fs_journal_location = location;
    604 		fs->fs_journal_flags = 0;
    605 
    606 		error = ffs_sbupdate(ump, MNT_WAIT);
    607 	}
    608 
    609 	return error;
    610 }
    611 
    612 /*
    613  * Try to create a journal log inside the filesystem.
    614  */
    615 static int
    616 wapbl_create_infs_log(struct mount *mp, struct fs *fs, struct vnode *devvp,
    617     daddr_t *startp, size_t *countp, uint64_t *extradatap)
    618 {
    619 	struct vnode *vp, *rvp;
    620 	struct vattr va;
    621 	struct inode *ip;
    622 	int error;
    623 
    624 	if ((error = VFS_ROOT(mp, &rvp)) != 0)
    625 		return error;
    626 
    627 	vattr_null(&va);
    628 	va.va_type = VREG;
    629 	va.va_mode = 0;
    630 
    631 	error = vcache_new(mp, rvp, &va, NOCRED, &vp);
    632 	vput(rvp);
    633 	if (error)
    634 		return error;
    635 
    636 	error = vn_lock(vp, LK_EXCLUSIVE);
    637 	if (error) {
    638 		vrele(vp);
    639 		return error;
    640 	}
    641 
    642 	ip = VTOI(vp);
    643 	ip->i_flags = SF_LOG;
    644 	DIP_ASSIGN(ip, flags, ip->i_flags);
    645 	ip->i_nlink = 1;
    646 	DIP_ASSIGN(ip, nlink, 1);
    647 	ip->i_flag |= IN_ACCESS | IN_CHANGE | IN_UPDATE;
    648 	ffs_update(vp, NULL, NULL, UPDATE_WAIT);
    649 
    650 	if ((error = wapbl_allocate_log_file(mp, vp,
    651 	                 startp, countp, extradatap)) != 0) {
    652 		/*
    653 		 * If we couldn't allocate the space for the log file,
    654 		 * remove the inode by setting its link count back to
    655 		 * zero and bail.
    656 		 */
    657 		ip->i_nlink = 0;
    658 		DIP_ASSIGN(ip, nlink, 0);
    659 		VOP_UNLOCK(vp);
    660 		vgone(vp);
    661 
    662 		return error;
    663 	}
    664 
    665 	/*
    666 	 * Now that we have the place-holder inode for the journal,
    667 	 * we don't need the vnode ever again.
    668 	 */
    669 	VOP_UNLOCK(vp);
    670 	vgone(vp);
    671 
    672 	return 0;
    673 }
    674 
    675 int
    676 wapbl_allocate_log_file(struct mount *mp, struct vnode *vp,
    677     daddr_t *startp, size_t *countp, uint64_t *extradatap)
    678 {
    679 	struct ufsmount *ump = VFSTOUFS(mp);
    680 	struct fs *fs = ump->um_fs;
    681 	daddr_t addr, indir_addr;
    682 	off_t logsize;
    683 	size_t size;
    684 	int error;
    685 
    686 	logsize = 0;
    687 	/* check if there's a suggested log size */
    688 	if (fs->fs_journal_flags & UFS_WAPBL_FLAGS_CREATE_LOG &&
    689 	    fs->fs_journal_location == UFS_WAPBL_JOURNALLOC_IN_FILESYSTEM)
    690 		logsize = fs->fs_journallocs[UFS_WAPBL_INFS_COUNT];
    691 
    692 	if (vp->v_size > 0) {
    693 		printf("%s: %s: file size (%" PRId64 ") non zero\n", __func__,
    694 		    fs->fs_fsmnt, vp->v_size);
    695 		return EEXIST;
    696 	}
    697 	wapbl_find_log_start(mp, vp, logsize, &addr, &indir_addr, &size);
    698 	if (addr == 0) {
    699 		printf("%s: %s: log not allocated, largest extent is "
    700 		    "%" PRId64 "MB\n", __func__, fs->fs_fsmnt,
    701 		    ffs_lblktosize(fs, size) / (1024 * 1024));
    702 		return ENOSPC;
    703 	}
    704 
    705 	logsize = ffs_lblktosize(fs, size);	/* final log size */
    706 
    707 	VTOI(vp)->i_ffs_first_data_blk = addr;
    708 	VTOI(vp)->i_ffs_first_indir_blk = indir_addr;
    709 
    710 	error = GOP_ALLOC(vp, 0, logsize, B_CONTIG, FSCRED);
    711 	if (error) {
    712 		printf("%s: %s: GOP_ALLOC error %d\n", __func__, fs->fs_fsmnt,
    713 		    error);
    714 		return error;
    715 	}
    716 
    717 	*startp     = FFS_FSBTODB(fs, addr);
    718 	*countp     = btodb(logsize);
    719 	*extradatap = VTOI(vp)->i_number;
    720 
    721 	return 0;
    722 }
    723 
    724 /*
    725  * Find a suitable location for the journal in the filesystem.
    726  *
    727  * Our strategy here is to look for a contiguous block of free space
    728  * at least "logfile" MB in size (plus room for any indirect blocks).
    729  * We start at the middle of the filesystem and check each cylinder
    730  * group working outwards.  If "logfile" MB is not available as a
    731  * single contigous chunk, then return the address and size of the
    732  * largest chunk found.
    733  *
    734  * XXX
    735  * At what stage does the search fail?  Is if the largest space we could
    736  * find is less than a quarter the requested space reasonable?  If the
    737  * search fails entirely, return a block address if "0" it indicate this.
    738  */
    739 static void
    740 wapbl_find_log_start(struct mount *mp, struct vnode *vp, off_t logsize,
    741     daddr_t *addr, daddr_t *indir_addr, size_t *size)
    742 {
    743 	struct ufsmount *ump = VFSTOUFS(mp);
    744 	struct fs *fs = ump->um_fs;
    745 	struct vnode *devvp = ump->um_devvp;
    746 	struct cg *cgp;
    747 	struct buf *bp;
    748 	uint8_t *blksfree;
    749 	daddr_t blkno, best_addr, start_addr;
    750 	daddr_t desired_blks, min_desired_blks;
    751 	daddr_t freeblks, best_blks;
    752 	int bpcg, cg, error, fixedsize, indir_blks, n, s;
    753 	const int needswap = UFS_FSNEEDSWAP(fs);
    754 
    755 	if (logsize == 0) {
    756 		fixedsize = 0;	/* We can adjust the size if tight */
    757 		logsize = ffs_lfragtosize(fs, fs->fs_dsize) /
    758 		    UFS_WAPBL_JOURNAL_SCALE;
    759 		DPRINTF("suggested log size = %" PRId64 "\n", logsize);
    760 		logsize = max(logsize, UFS_WAPBL_MIN_JOURNAL_SIZE);
    761 		logsize = min(logsize, UFS_WAPBL_MAX_JOURNAL_SIZE);
    762 		DPRINTF("adjusted log size = %" PRId64 "\n", logsize);
    763 	} else {
    764 		fixedsize = 1;
    765 		DPRINTF("fixed log size = %" PRId64 "\n", logsize);
    766 	}
    767 
    768 	desired_blks = logsize / fs->fs_bsize;
    769 	DPRINTF("desired blocks = %" PRId64 "\n", desired_blks);
    770 
    771 	/* add in number of indirect blocks needed */
    772 	indir_blks = 0;
    773 	if (desired_blks >= UFS_NDADDR) {
    774 		struct indir indirs[UFS_NIADDR + 2];
    775 		int num;
    776 
    777 		error = ufs_getlbns(vp, desired_blks, indirs, &num);
    778 		if (error) {
    779 			printf("%s: %s:  ufs_getlbns failed, error %d!\n",
    780 			    __func__, fs->fs_fsmnt, error);
    781 			goto bad;
    782 		}
    783 
    784 		switch (num) {
    785 		case 2:
    786 			indir_blks = 1;		/* 1st level indirect */
    787 			break;
    788 		case 3:
    789 			indir_blks = 1 +	/* 1st level indirect */
    790 			    1 +			/* 2nd level indirect */
    791 			    indirs[1].in_off + 1; /* extra 1st level indirect */
    792 			break;
    793 		default:
    794 			printf("%s: %s: unexpected numlevels %d from "
    795 			    "ufs_getlbns\n", __func__, fs->fs_fsmnt, num);
    796 			*size = 0;
    797 			goto bad;
    798 		}
    799 		desired_blks += indir_blks;
    800 	}
    801 	DPRINTF("desired blocks = %" PRId64 " (including indirect)\n",
    802 	    desired_blks);
    803 
    804 	/*
    805 	 * If a specific size wasn't requested, allow for a smaller log
    806 	 * if we're really tight for space...
    807 	 */
    808 	min_desired_blks = desired_blks;
    809 	if (!fixedsize)
    810 		min_desired_blks = desired_blks / 4;
    811 
    812 	/* Look at number of blocks per CG.  If it's too small, bail early. */
    813 	bpcg = ffs_fragstoblks(fs, fs->fs_fpg);
    814 	if (min_desired_blks > bpcg) {
    815 		printf("%s: %s: cylinder group size of %" PRId64 " MB "
    816 		    " is not big enough for journal\n", __func__, fs->fs_fsmnt,
    817 		    ffs_lblktosize(fs, bpcg) / (1024 * 1024));
    818 		goto bad;
    819 	}
    820 
    821 	/*
    822 	 * Start with the middle cylinder group, and search outwards in
    823 	 * both directions until we either find the requested log size
    824 	 * or reach the start/end of the file system.  If we reach the
    825 	 * start/end without finding enough space for the full requested
    826 	 * log size, use the largest extent found if it is large enough
    827 	 * to satisfy the our minimum size.
    828 	 *
    829 	 * XXX
    830 	 * Can we just use the cluster contigsum stuff (esp on UFS2)
    831 	 * here to simplify this search code?
    832 	 */
    833 	best_addr = 0;
    834 	best_blks = 0;
    835 	for (cg = fs->fs_ncg / 2, s = 0, n = 1;
    836 	    best_blks < desired_blks && cg >= 0 && cg < fs->fs_ncg;
    837 	    s++, n = -n, cg += n * s) {
    838 		DPRINTF("check cg %d of %d\n", cg, fs->fs_ncg);
    839 		error = bread(devvp, FFS_FSBTODB(fs, cgtod(fs, cg)),
    840 		    fs->fs_cgsize, 0, &bp);
    841 		if (error) {
    842 			continue;
    843 		}
    844 		cgp = (struct cg *)bp->b_data;
    845 		if (!cg_chkmagic(cgp, UFS_FSNEEDSWAP(fs))) {
    846 			brelse(bp, 0);
    847 			continue;
    848 		}
    849 
    850 		blksfree = cg_blksfree(cgp, needswap);
    851 
    852 		for (blkno = 0; blkno < bpcg;) {
    853 			/* look for next free block */
    854 			/* XXX use scanc() and fragtbl[] here? */
    855 			for (; blkno < bpcg - min_desired_blks; blkno++)
    856 				if (ffs_isblock(fs, blksfree, blkno))
    857 					break;
    858 
    859 			/* past end of search space in this CG? */
    860 			if (blkno >= bpcg - min_desired_blks)
    861 				break;
    862 
    863 			/* count how many free blocks in this extent */
    864 			start_addr = blkno;
    865 			for (freeblks = 0; blkno < bpcg; blkno++, freeblks++)
    866 				if (!ffs_isblock(fs, blksfree, blkno))
    867 					break;
    868 
    869 			if (freeblks > best_blks) {
    870 				best_blks = freeblks;
    871 				best_addr = ffs_blkstofrags(fs, start_addr) +
    872 				    cgbase(fs, cg);
    873 
    874 				if (freeblks >= desired_blks) {
    875 					DPRINTF("found len %" PRId64
    876 					    " at offset %" PRId64 " in gc\n",
    877 					    freeblks, start_addr);
    878 					break;
    879 				}
    880 			}
    881 		}
    882 		brelse(bp, 0);
    883 	}
    884 	DPRINTF("best found len = %" PRId64 ", wanted %" PRId64
    885 	    " at addr %" PRId64 "\n", best_blks, desired_blks, best_addr);
    886 
    887 	if (best_blks < min_desired_blks) {
    888 		*addr = 0;
    889 		*indir_addr = 0;
    890 	} else {
    891 		/* put indirect blocks at start, and data blocks after */
    892 		*addr = best_addr + ffs_blkstofrags(fs, indir_blks);
    893 		*indir_addr = best_addr;
    894 	}
    895 	*size = min(desired_blks, best_blks) - indir_blks;
    896 	return;
    897 
    898 bad:
    899 	*addr = 0;
    900 	*indir_addr = 0;
    901 	*size = 0;
    902 	return;
    903 }
    904