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