Home | History | Annotate | Line # | Download | only in ffs
ffs_wapbl.c revision 1.38
      1 /*	$NetBSD: ffs_wapbl.c,v 1.38 2017/03/10 22:43:03 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.38 2017/03/10 22:43:03 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 			/*
    342 			 * Make sure we don't carry over any delayed write
    343 			 * buffers when updating to log.
    344 			 */
    345 			if (mp->mnt_flag & MNT_UPDATE)
    346 				ffs_sync(mp, MNT_WAIT, FSCRED);
    347 
    348 			error = wapbl_log_position(mp, fs, devvp, &off,
    349 			    &count, &blksize, &extradata);
    350 			if (error)
    351 				return error;
    352 
    353 			error = wapbl_start(&mp->mnt_wapbl, mp, devvp, off,
    354 			    count, blksize, mp->mnt_wapbl_replay,
    355 			    ffs_wapbl_sync_metadata,
    356 			    ffs_wapbl_abort_sync_metadata);
    357 			if (error)
    358 				return error;
    359 
    360 			mp->mnt_wapbl_op = &wapbl_ops;
    361 
    362 #ifdef WAPBL_DEBUG
    363 			printf("%s: %s: enabling logging\n", __func__,
    364 			    fs->fs_fsmnt);
    365 #endif
    366 
    367 			if ((fs->fs_flags & FS_DOWAPBL) == 0) {
    368 				fs->fs_flags |= FS_DOWAPBL;
    369 				if ((error = UFS_WAPBL_BEGIN(mp)) != 0)
    370 					goto out;
    371 				error = ffs_sbupdate(ump, MNT_WAIT);
    372 				if (error) {
    373 					UFS_WAPBL_END(mp);
    374 					goto out;
    375 				}
    376 				UFS_WAPBL_END(mp);
    377 				error = wapbl_flush(mp->mnt_wapbl, 1);
    378 				if (error)
    379 					goto out;
    380 			}
    381 
    382 			/*
    383 			 * XXX discard interferes with block deallocation
    384 			 * registration and hence log consistency
    385 			 */
    386 			if (mp->mnt_flag & MNT_DISCARD) {
    387 				CLR(mp->mnt_flag, MNT_DISCARD);
    388 				printf("%s: %s: disabling discard to preserve log consistency\n", __func__,
    389 				    fs->fs_fsmnt);
    390 
    391 				if (ump->um_discarddata != NULL) {
    392 		                	ffs_discard_finish(ump->um_discarddata,
    393 					    0);
    394 	                		ump->um_discarddata = NULL;
    395 				}
    396 			}
    397 
    398 		} else if (fs->fs_flags & FS_DOWAPBL) {
    399 			fs->fs_fmod = 1;
    400 			fs->fs_flags &= ~FS_DOWAPBL;
    401 		}
    402 	}
    403 
    404 	/*
    405 	 * It is recommended that you finish replay with logging enabled.
    406 	 * However, even if logging is not enabled, the remaining log
    407 	 * replay should be safely recoverable with an fsck, so perform
    408 	 * it anyway.
    409 	 */
    410 	if ((fs->fs_ronly == 0) && mp->mnt_wapbl_replay) {
    411 		int saveflag = mp->mnt_flag & MNT_RDONLY;
    412 		/*
    413 		 * Make sure MNT_RDONLY is not set so that the inode
    414 		 * cleanup in ufs_inactive will actually do its work.
    415 		 */
    416 		mp->mnt_flag &= ~MNT_RDONLY;
    417 		ffs_wapbl_replay_finish(mp);
    418 		mp->mnt_flag |= saveflag;
    419 		KASSERT(fs->fs_ronly == 0);
    420 	}
    421 
    422 	return 0;
    423 out:
    424 	ffs_wapbl_stop(mp, MNT_FORCE);
    425 	return error;
    426 }
    427 
    428 int
    429 ffs_wapbl_stop(struct mount *mp, int force)
    430 {
    431 	struct ufsmount *ump = VFSTOUFS(mp);
    432 	struct fs *fs = ump->um_fs;
    433 	int error;
    434 
    435 	if (mp->mnt_wapbl) {
    436 		KDASSERT(fs->fs_ronly == 0);
    437 
    438 		/*
    439 		 * Make sure turning off FS_DOWAPBL is only removed
    440 		 * as the only change in the final flush since otherwise
    441 		 * a transaction may reorder writes.
    442 		 */
    443 		error = wapbl_flush(mp->mnt_wapbl, 1);
    444 		if (error && !force)
    445 			return error;
    446 		if (error && force)
    447 			goto forceout;
    448 		error = UFS_WAPBL_BEGIN(mp);
    449 		if (error && !force)
    450 			return error;
    451 		if (error && force)
    452 			goto forceout;
    453 		KASSERT(fs->fs_flags & FS_DOWAPBL);
    454 
    455 		fs->fs_flags &= ~FS_DOWAPBL;
    456 		error = ffs_sbupdate(ump, MNT_WAIT);
    457 		KASSERT(error == 0);	/* XXX a bit drastic! */
    458 		UFS_WAPBL_END(mp);
    459 	forceout:
    460 		error = wapbl_stop(mp->mnt_wapbl, force);
    461 		if (error) {
    462 			KASSERT(!force);
    463 			fs->fs_flags |= FS_DOWAPBL;
    464 			return error;
    465 		}
    466 		fs->fs_flags &= ~FS_DOWAPBL; /* Repeat in case of forced error */
    467 		mp->mnt_wapbl = NULL;
    468 
    469 #ifdef WAPBL_DEBUG
    470 		printf("%s: %s: disabled logging\n", __func__, fs->fs_fsmnt);
    471 #endif
    472 	}
    473 
    474 	return 0;
    475 }
    476 
    477 int
    478 ffs_wapbl_replay_start(struct mount *mp, struct fs *fs, struct vnode *devvp)
    479 {
    480 	int error;
    481 	daddr_t off;
    482 	size_t count;
    483 	size_t blksize;
    484 	uint64_t extradata;
    485 
    486 	/*
    487 	 * WAPBL needs UFS2 format super block, if we got here with a
    488 	 * UFS1 format super block something is amiss...
    489 	 */
    490 	if (ffs_superblock_layout(fs) < 2)
    491 		return EINVAL;
    492 
    493 	error = wapbl_log_position(mp, fs, devvp, &off, &count, &blksize,
    494 	    &extradata);
    495 
    496 	if (error)
    497 		return error;
    498 
    499 	error = wapbl_replay_start(&mp->mnt_wapbl_replay, devvp, off,
    500 		count, blksize);
    501 	if (error)
    502 		return error;
    503 
    504 	mp->mnt_wapbl_op = &wapbl_ops;
    505 
    506 	return 0;
    507 }
    508 
    509 /*
    510  * If the superblock doesn't already have a recorded journal location
    511  * then we allocate the journal in one of two positions:
    512  *
    513  *  - At the end of the partition after the filesystem if there's
    514  *    enough space.  "Enough space" is defined as >= 1MB of journal
    515  *    per 1GB of filesystem or 64MB, whichever is smaller.
    516  *
    517  *  - Inside the filesystem.  We try to allocate a contiguous journal
    518  *    based on the total filesystem size - the target is 1MB of journal
    519  *    per 1GB of filesystem, up to a maximum journal size of 64MB.  As
    520  *    a worst case allowing for fragmentation, we'll allocate a journal
    521  *    1/4 of the desired size but never smaller than 1MB.
    522  *
    523  *    XXX In the future if we allow for non-contiguous journal files we
    524  *    can tighten the above restrictions.
    525  *
    526  * XXX
    527  * These seems like a lot of duplication both here and in some of
    528  * the userland tools (fsck_ffs, dumpfs, tunefs) with similar
    529  * "switch (fs_journal_location)" constructs.  Can we centralise
    530  * this sort of code somehow/somewhere?
    531  */
    532 static int
    533 wapbl_log_position(struct mount *mp, struct fs *fs, struct vnode *devvp,
    534     daddr_t *startp, size_t *countp, size_t *blksizep, uint64_t *extradatap)
    535 {
    536 	struct ufsmount *ump = VFSTOUFS(mp);
    537 	daddr_t logstart, logend, desired_logsize;
    538 	uint64_t numsecs;
    539 	unsigned secsize;
    540 	int error, location;
    541 
    542 	if (fs->fs_journal_version == UFS_WAPBL_VERSION) {
    543 		switch (fs->fs_journal_location) {
    544 		case UFS_WAPBL_JOURNALLOC_END_PARTITION:
    545 			DPRINTF("found existing end-of-partition log\n");
    546 			*startp = fs->fs_journallocs[UFS_WAPBL_EPART_ADDR];
    547 			*countp = fs->fs_journallocs[UFS_WAPBL_EPART_COUNT];
    548 			*blksizep = fs->fs_journallocs[UFS_WAPBL_EPART_BLKSZ];
    549 			DPRINTF(" start = %" PRId64 ", size = %zu, "
    550 			    "blksize = %zu\n", *startp, *countp, *blksizep);
    551 			return 0;
    552 
    553 		case UFS_WAPBL_JOURNALLOC_IN_FILESYSTEM:
    554 			DPRINTF("found existing in-filesystem log\n");
    555 			*startp = fs->fs_journallocs[UFS_WAPBL_INFS_ADDR];
    556 			*countp = fs->fs_journallocs[UFS_WAPBL_INFS_COUNT];
    557 			*blksizep = fs->fs_journallocs[UFS_WAPBL_INFS_BLKSZ];
    558 			DPRINTF(" start = %" PRId64 ", size = %zu, "
    559 			    "blksize = %zu\n", *startp, *countp, *blksizep);
    560 			return 0;
    561 
    562 		default:
    563 			printf("%s: %s: unknown journal type %d\n", __func__,
    564 			    fs->fs_fsmnt, fs->fs_journal_location);
    565 			return EINVAL;
    566 		}
    567 	}
    568 
    569 	desired_logsize =
    570 	    ffs_lfragtosize(fs, fs->fs_size) / UFS_WAPBL_JOURNAL_SCALE;
    571 	DPRINTF("desired log size = %" PRId64 " kB\n", desired_logsize / 1024);
    572 	desired_logsize = max(desired_logsize, UFS_WAPBL_MIN_JOURNAL_SIZE);
    573 	desired_logsize = min(desired_logsize, UFS_WAPBL_MAX_JOURNAL_SIZE);
    574 	DPRINTF("adjusted desired log size = %" PRId64 " kB\n",
    575 	    desired_logsize / 1024);
    576 
    577 	/* Is there space after after filesystem on partition for log? */
    578 	logstart = FFS_FSBTODB(fs, fs->fs_size);
    579 	error = getdisksize(devvp, &numsecs, &secsize);
    580 	if (error)
    581 		return error;
    582 	KDASSERT(secsize != 0);
    583 	logend = btodb(numsecs * secsize);
    584 
    585 	if (dbtob(logend - logstart) >= desired_logsize) {
    586 		DPRINTF("enough space, use end-of-partition log\n");
    587 
    588 		location = UFS_WAPBL_JOURNALLOC_END_PARTITION;
    589 		*blksizep = secsize;
    590 
    591 		*startp = logstart;
    592 		*countp = (logend - logstart);
    593 		*extradatap = 0;
    594 
    595 		/* convert to physical block numbers */
    596 		*startp = dbtob(*startp) / secsize;
    597 		*countp = dbtob(*countp) / secsize;
    598 
    599 		fs->fs_journallocs[UFS_WAPBL_EPART_ADDR] = *startp;
    600 		fs->fs_journallocs[UFS_WAPBL_EPART_COUNT] = *countp;
    601 		fs->fs_journallocs[UFS_WAPBL_EPART_BLKSZ] = *blksizep;
    602 		fs->fs_journallocs[UFS_WAPBL_EPART_UNUSED] = *extradatap;
    603 	} else {
    604 		DPRINTF("end-of-partition has only %" PRId64 " free\n",
    605 		    logend - logstart);
    606 
    607 		location = UFS_WAPBL_JOURNALLOC_IN_FILESYSTEM;
    608 		*blksizep = secsize;
    609 
    610 		error = wapbl_create_infs_log(mp, fs, devvp,
    611 		                  startp, countp, extradatap);
    612 		ffs_sync(mp, MNT_WAIT, FSCRED);
    613 
    614 		/* convert to physical block numbers */
    615 		*startp = dbtob(*startp) / secsize;
    616 		*countp = dbtob(*countp) / secsize;
    617 
    618 		fs->fs_journallocs[UFS_WAPBL_INFS_ADDR] = *startp;
    619 		fs->fs_journallocs[UFS_WAPBL_INFS_COUNT] = *countp;
    620 		fs->fs_journallocs[UFS_WAPBL_INFS_BLKSZ] = *blksizep;
    621 		fs->fs_journallocs[UFS_WAPBL_INFS_INO] = *extradatap;
    622 	}
    623 
    624 	if (error == 0) {
    625 		/* update superblock with log location */
    626 		fs->fs_journal_version = UFS_WAPBL_VERSION;
    627 		fs->fs_journal_location = location;
    628 		fs->fs_journal_flags = 0;
    629 
    630 		error = ffs_sbupdate(ump, MNT_WAIT);
    631 	}
    632 
    633 	return error;
    634 }
    635 
    636 /*
    637  * Try to create a journal log inside the filesystem.
    638  */
    639 static int
    640 wapbl_create_infs_log(struct mount *mp, struct fs *fs, struct vnode *devvp,
    641     daddr_t *startp, size_t *countp, uint64_t *extradatap)
    642 {
    643 	struct vnode *vp, *rvp;
    644 	struct vattr va;
    645 	struct inode *ip;
    646 	int error;
    647 
    648 	if ((error = VFS_ROOT(mp, &rvp)) != 0)
    649 		return error;
    650 
    651 	vattr_null(&va);
    652 	va.va_type = VREG;
    653 	va.va_mode = 0;
    654 
    655 	error = vcache_new(mp, rvp, &va, NOCRED, &vp);
    656 	vput(rvp);
    657 	if (error)
    658 		return error;
    659 
    660 	error = vn_lock(vp, LK_EXCLUSIVE);
    661 	if (error) {
    662 		vrele(vp);
    663 		return error;
    664 	}
    665 
    666 	ip = VTOI(vp);
    667 	ip->i_flags = SF_LOG;
    668 	DIP_ASSIGN(ip, flags, ip->i_flags);
    669 	ip->i_nlink = 1;
    670 	DIP_ASSIGN(ip, nlink, 1);
    671 	ip->i_flag |= IN_ACCESS | IN_CHANGE | IN_UPDATE;
    672 	ffs_update(vp, NULL, NULL, UPDATE_WAIT);
    673 
    674 	if ((error = wapbl_allocate_log_file(mp, vp,
    675 	                 startp, countp, extradatap)) != 0) {
    676 		/*
    677 		 * If we couldn't allocate the space for the log file,
    678 		 * remove the inode by setting its link count back to
    679 		 * zero and bail.
    680 		 */
    681 		ip->i_nlink = 0;
    682 		DIP_ASSIGN(ip, nlink, 0);
    683 		VOP_UNLOCK(vp);
    684 		vgone(vp);
    685 
    686 		return error;
    687 	}
    688 
    689 	/*
    690 	 * Now that we have the place-holder inode for the journal,
    691 	 * we don't need the vnode ever again.
    692 	 */
    693 	VOP_UNLOCK(vp);
    694 	vgone(vp);
    695 
    696 	return 0;
    697 }
    698 
    699 int
    700 wapbl_allocate_log_file(struct mount *mp, struct vnode *vp,
    701     daddr_t *startp, size_t *countp, uint64_t *extradatap)
    702 {
    703 	struct ufsmount *ump = VFSTOUFS(mp);
    704 	struct fs *fs = ump->um_fs;
    705 	daddr_t addr, indir_addr;
    706 	off_t logsize;
    707 	size_t size;
    708 	int error;
    709 
    710 	logsize = 0;
    711 	/* check if there's a suggested log size */
    712 	if (fs->fs_journal_flags & UFS_WAPBL_FLAGS_CREATE_LOG &&
    713 	    fs->fs_journal_location == UFS_WAPBL_JOURNALLOC_IN_FILESYSTEM)
    714 		logsize = fs->fs_journallocs[UFS_WAPBL_INFS_COUNT];
    715 
    716 	if (vp->v_size > 0) {
    717 		printf("%s: %s: file size (%" PRId64 ") non zero\n", __func__,
    718 		    fs->fs_fsmnt, vp->v_size);
    719 		return EEXIST;
    720 	}
    721 	wapbl_find_log_start(mp, vp, logsize, &addr, &indir_addr, &size);
    722 	if (addr == 0) {
    723 		printf("%s: %s: log not allocated, largest extent is "
    724 		    "%" PRId64 "MB\n", __func__, fs->fs_fsmnt,
    725 		    ffs_lblktosize(fs, size) / (1024 * 1024));
    726 		return ENOSPC;
    727 	}
    728 
    729 	logsize = ffs_lblktosize(fs, size);	/* final log size */
    730 
    731 	VTOI(vp)->i_ffs_first_data_blk = addr;
    732 	VTOI(vp)->i_ffs_first_indir_blk = indir_addr;
    733 
    734 	error = GOP_ALLOC(vp, 0, logsize, B_CONTIG, FSCRED);
    735 	if (error) {
    736 		printf("%s: %s: GOP_ALLOC error %d\n", __func__, fs->fs_fsmnt,
    737 		    error);
    738 		return error;
    739 	}
    740 
    741 	*startp     = FFS_FSBTODB(fs, addr);
    742 	*countp     = btodb(logsize);
    743 	*extradatap = VTOI(vp)->i_number;
    744 
    745 	return 0;
    746 }
    747 
    748 /*
    749  * Find a suitable location for the journal in the filesystem.
    750  *
    751  * Our strategy here is to look for a contiguous block of free space
    752  * at least "logfile" MB in size (plus room for any indirect blocks).
    753  * We start at the middle of the filesystem and check each cylinder
    754  * group working outwards.  If "logfile" MB is not available as a
    755  * single contigous chunk, then return the address and size of the
    756  * largest chunk found.
    757  *
    758  * XXX
    759  * At what stage does the search fail?  Is if the largest space we could
    760  * find is less than a quarter the requested space reasonable?  If the
    761  * search fails entirely, return a block address if "0" it indicate this.
    762  */
    763 static void
    764 wapbl_find_log_start(struct mount *mp, struct vnode *vp, off_t logsize,
    765     daddr_t *addr, daddr_t *indir_addr, size_t *size)
    766 {
    767 	struct ufsmount *ump = VFSTOUFS(mp);
    768 	struct fs *fs = ump->um_fs;
    769 	struct vnode *devvp = ump->um_devvp;
    770 	struct cg *cgp;
    771 	struct buf *bp;
    772 	uint8_t *blksfree;
    773 	daddr_t blkno, best_addr, start_addr;
    774 	daddr_t desired_blks, min_desired_blks;
    775 	daddr_t freeblks, best_blks;
    776 	int bpcg, cg, error, fixedsize, indir_blks, n, s;
    777 	const int needswap = UFS_FSNEEDSWAP(fs);
    778 
    779 	if (logsize == 0) {
    780 		fixedsize = 0;	/* We can adjust the size if tight */
    781 		logsize = ffs_lfragtosize(fs, fs->fs_dsize) /
    782 		    UFS_WAPBL_JOURNAL_SCALE;
    783 		DPRINTF("suggested log size = %" PRId64 "\n", logsize);
    784 		logsize = max(logsize, UFS_WAPBL_MIN_JOURNAL_SIZE);
    785 		logsize = min(logsize, UFS_WAPBL_MAX_JOURNAL_SIZE);
    786 		DPRINTF("adjusted log size = %" PRId64 "\n", logsize);
    787 	} else {
    788 		fixedsize = 1;
    789 		DPRINTF("fixed log size = %" PRId64 "\n", logsize);
    790 	}
    791 
    792 	desired_blks = logsize / fs->fs_bsize;
    793 	DPRINTF("desired blocks = %" PRId64 "\n", desired_blks);
    794 
    795 	/* add in number of indirect blocks needed */
    796 	indir_blks = 0;
    797 	if (desired_blks >= UFS_NDADDR) {
    798 		struct indir indirs[UFS_NIADDR + 2];
    799 		int num;
    800 
    801 		error = ufs_getlbns(vp, desired_blks, indirs, &num);
    802 		if (error) {
    803 			printf("%s: %s:  ufs_getlbns failed, error %d!\n",
    804 			    __func__, fs->fs_fsmnt, error);
    805 			goto bad;
    806 		}
    807 
    808 		switch (num) {
    809 		case 2:
    810 			indir_blks = 1;		/* 1st level indirect */
    811 			break;
    812 		case 3:
    813 			indir_blks = 1 +	/* 1st level indirect */
    814 			    1 +			/* 2nd level indirect */
    815 			    indirs[1].in_off + 1; /* extra 1st level indirect */
    816 			break;
    817 		default:
    818 			printf("%s: %s: unexpected numlevels %d from "
    819 			    "ufs_getlbns\n", __func__, fs->fs_fsmnt, num);
    820 			*size = 0;
    821 			goto bad;
    822 		}
    823 		desired_blks += indir_blks;
    824 	}
    825 	DPRINTF("desired blocks = %" PRId64 " (including indirect)\n",
    826 	    desired_blks);
    827 
    828 	/*
    829 	 * If a specific size wasn't requested, allow for a smaller log
    830 	 * if we're really tight for space...
    831 	 */
    832 	min_desired_blks = desired_blks;
    833 	if (!fixedsize)
    834 		min_desired_blks = desired_blks / 4;
    835 
    836 	/* Look at number of blocks per CG.  If it's too small, bail early. */
    837 	bpcg = ffs_fragstoblks(fs, fs->fs_fpg);
    838 	if (min_desired_blks > bpcg) {
    839 		printf("%s: %s: cylinder group size of %" PRId64 " MB "
    840 		    " is not big enough for journal\n", __func__, fs->fs_fsmnt,
    841 		    ffs_lblktosize(fs, bpcg) / (1024 * 1024));
    842 		goto bad;
    843 	}
    844 
    845 	/*
    846 	 * Start with the middle cylinder group, and search outwards in
    847 	 * both directions until we either find the requested log size
    848 	 * or reach the start/end of the file system.  If we reach the
    849 	 * start/end without finding enough space for the full requested
    850 	 * log size, use the largest extent found if it is large enough
    851 	 * to satisfy the our minimum size.
    852 	 *
    853 	 * XXX
    854 	 * Can we just use the cluster contigsum stuff (esp on UFS2)
    855 	 * here to simplify this search code?
    856 	 */
    857 	best_addr = 0;
    858 	best_blks = 0;
    859 	for (cg = fs->fs_ncg / 2, s = 0, n = 1;
    860 	    best_blks < desired_blks && cg >= 0 && cg < fs->fs_ncg;
    861 	    s++, n = -n, cg += n * s) {
    862 		DPRINTF("check cg %d of %d\n", cg, fs->fs_ncg);
    863 		error = bread(devvp, FFS_FSBTODB(fs, cgtod(fs, cg)),
    864 		    fs->fs_cgsize, 0, &bp);
    865 		if (error) {
    866 			continue;
    867 		}
    868 		cgp = (struct cg *)bp->b_data;
    869 		if (!cg_chkmagic(cgp, UFS_FSNEEDSWAP(fs))) {
    870 			brelse(bp, 0);
    871 			continue;
    872 		}
    873 
    874 		blksfree = cg_blksfree(cgp, needswap);
    875 
    876 		for (blkno = 0; blkno < bpcg;) {
    877 			/* look for next free block */
    878 			/* XXX use scanc() and fragtbl[] here? */
    879 			for (; blkno < bpcg - min_desired_blks; blkno++)
    880 				if (ffs_isblock(fs, blksfree, blkno))
    881 					break;
    882 
    883 			/* past end of search space in this CG? */
    884 			if (blkno >= bpcg - min_desired_blks)
    885 				break;
    886 
    887 			/* count how many free blocks in this extent */
    888 			start_addr = blkno;
    889 			for (freeblks = 0; blkno < bpcg; blkno++, freeblks++)
    890 				if (!ffs_isblock(fs, blksfree, blkno))
    891 					break;
    892 
    893 			if (freeblks > best_blks) {
    894 				best_blks = freeblks;
    895 				best_addr = ffs_blkstofrags(fs, start_addr) +
    896 				    cgbase(fs, cg);
    897 
    898 				if (freeblks >= desired_blks) {
    899 					DPRINTF("found len %" PRId64
    900 					    " at offset %" PRId64 " in gc\n",
    901 					    freeblks, start_addr);
    902 					break;
    903 				}
    904 			}
    905 		}
    906 		brelse(bp, 0);
    907 	}
    908 	DPRINTF("best found len = %" PRId64 ", wanted %" PRId64
    909 	    " at addr %" PRId64 "\n", best_blks, desired_blks, best_addr);
    910 
    911 	if (best_blks < min_desired_blks) {
    912 		*addr = 0;
    913 		*indir_addr = 0;
    914 	} else {
    915 		/* put indirect blocks at start, and data blocks after */
    916 		*addr = best_addr + ffs_blkstofrags(fs, indir_blks);
    917 		*indir_addr = best_addr;
    918 	}
    919 	*size = min(desired_blks, best_blks) - indir_blks;
    920 	return;
    921 
    922 bad:
    923 	*addr = 0;
    924 	*indir_addr = 0;
    925 	*size = 0;
    926 	return;
    927 }
    928