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