1/* $NetBSD: lfs.c,v 1.34 2011/06/21 09:36:46 mrg Exp $ */
2/*-
3 * Copyright (c) 2003 The NetBSD Foundation, Inc.
4 * All rights reserved.
5 *
6 * This code is derived from software contributed to The NetBSD Foundation
7 * by Konrad E. Schroder <perseant@hhhh.org>.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
19 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
20 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
22 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGE.
29 */
30/*
31 * Copyright (c) 1989, 1991, 1993
32 *	The Regents of the University of California.  All rights reserved.
33 * (c) UNIX System Laboratories, Inc.
34 * All or some portions of this file are derived from material licensed
35 * to the University of California by American Telephone and Telegraph
36 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
37 * the permission of UNIX System Laboratories, Inc.
38 *
39 * Redistribution and use in source and binary forms, with or without
40 * modification, are permitted provided that the following conditions
41 * are met:
42 * 1. Redistributions of source code must retain the above copyright
43 *    notice, this list of conditions and the following disclaimer.
44 * 2. Redistributions in binary form must reproduce the above copyright
45 *    notice, this list of conditions and the following disclaimer in the
46 *    documentation and/or other materials provided with the distribution.
47 * 3. Neither the name of the University nor the names of its contributors
48 *    may be used to endorse or promote products derived from this software
49 *    without specific prior written permission.
50 *
51 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
52 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
53 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
54 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
55 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
56 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
57 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
58 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
59 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
60 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
61 * SUCH DAMAGE.
62 *
63 *	@(#)ufs_bmap.c	8.8 (Berkeley) 8/11/95
64 */
65
66
67#include <sys/types.h>
68#include <sys/param.h>
69#include <sys/time.h>
70#include <sys/buf.h>
71#include <sys/mount.h>
72
73#include <ufs/ufs/inode.h>
74#include <ufs/ufs/ufsmount.h>
75#define vnode uvnode
76#include <ufs/lfs/lfs.h>
77#undef vnode
78
79#include <assert.h>
80#include <err.h>
81#include <errno.h>
82#include <stdarg.h>
83#include <stdio.h>
84#include <stdlib.h>
85#include <string.h>
86#include <unistd.h>
87#include <util.h>
88
89#include "bufcache.h"
90#include "vnode.h"
91#include "lfs_user.h"
92#include "segwrite.h"
93#include "kernelops.h"
94
95#define panic call_panic
96
97extern u_int32_t cksum(void *, size_t);
98extern u_int32_t lfs_sb_cksum(struct dlfs *);
99extern void pwarn(const char *, ...);
100
101extern struct uvnodelst vnodelist;
102extern struct uvnodelst getvnodelist[VNODE_HASH_MAX];
103extern int nvnodes;
104
105long dev_bsize = DEV_BSIZE;
106
107static int
108lfs_fragextend(struct uvnode *, int, int, daddr_t, struct ubuf **);
109
110int fsdirty = 0;
111void (*panic_func)(int, const char *, va_list) = my_vpanic;
112
113/*
114 * LFS buffer and uvnode operations
115 */
116
117int
118lfs_vop_strategy(struct ubuf * bp)
119{
120	int count;
121
122	if (bp->b_flags & B_READ) {
123		count = kops.ko_pread(bp->b_vp->v_fd, bp->b_data, bp->b_bcount,
124		    bp->b_blkno * dev_bsize);
125		if (count == bp->b_bcount)
126			bp->b_flags |= B_DONE;
127	} else {
128		count = kops.ko_pwrite(bp->b_vp->v_fd, bp->b_data, bp->b_bcount,
129		    bp->b_blkno * dev_bsize);
130		if (count == 0) {
131			perror("pwrite");
132			return -1;
133		}
134		bp->b_flags &= ~B_DELWRI;
135		reassignbuf(bp, bp->b_vp);
136	}
137	return 0;
138}
139
140int
141lfs_vop_bwrite(struct ubuf * bp)
142{
143	struct lfs *fs;
144
145	fs = bp->b_vp->v_fs;
146	if (!(bp->b_flags & B_DELWRI)) {
147		fs->lfs_avail -= btofsb(fs, bp->b_bcount);
148	}
149	bp->b_flags |= B_DELWRI | B_LOCKED;
150	reassignbuf(bp, bp->b_vp);
151	brelse(bp, 0);
152	return 0;
153}
154
155/*
156 * ufs_bmaparray does the bmap conversion, and if requested returns the
157 * array of logical blocks which must be traversed to get to a block.
158 * Each entry contains the offset into that block that gets you to the
159 * next block and the disk address of the block (if it is assigned).
160 */
161int
162ufs_bmaparray(struct lfs * fs, struct uvnode * vp, daddr_t bn, daddr_t * bnp, struct indir * ap, int *nump)
163{
164	struct inode *ip;
165	struct ubuf *bp;
166	struct indir a[NIADDR + 1], *xap;
167	daddr_t daddr;
168	daddr_t metalbn;
169	int error, num;
170
171	ip = VTOI(vp);
172
173	if (bn >= 0 && bn < NDADDR) {
174		if (nump != NULL)
175			*nump = 0;
176		*bnp = fsbtodb(fs, ip->i_ffs1_db[bn]);
177		if (*bnp == 0)
178			*bnp = -1;
179		return (0);
180	}
181	xap = ap == NULL ? a : ap;
182	if (!nump)
183		nump = &num;
184	if ((error = ufs_getlbns(fs, vp, bn, xap, nump)) != 0)
185		return (error);
186
187	num = *nump;
188
189	/* Get disk address out of indirect block array */
190	daddr = ip->i_ffs1_ib[xap->in_off];
191
192	for (bp = NULL, ++xap; --num; ++xap) {
193		/* Exit the loop if there is no disk address assigned yet and
194		 * the indirect block isn't in the cache, or if we were
195		 * looking for an indirect block and we've found it. */
196
197		metalbn = xap->in_lbn;
198		if ((daddr == 0 && !incore(vp, metalbn)) || metalbn == bn)
199			break;
200		/*
201		 * If we get here, we've either got the block in the cache
202		 * or we have a disk address for it, go fetch it.
203		 */
204		if (bp)
205			brelse(bp, 0);
206
207		xap->in_exists = 1;
208		bp = getblk(vp, metalbn, fs->lfs_bsize);
209
210		if (!(bp->b_flags & (B_DONE | B_DELWRI))) {
211			bp->b_blkno = fsbtodb(fs, daddr);
212			bp->b_flags |= B_READ;
213			VOP_STRATEGY(bp);
214		}
215		daddr = ((ufs_daddr_t *) bp->b_data)[xap->in_off];
216	}
217	if (bp)
218		brelse(bp, 0);
219
220	daddr = fsbtodb(fs, (ufs_daddr_t) daddr);
221	*bnp = daddr == 0 ? -1 : daddr;
222	return (0);
223}
224
225/*
226 * Create an array of logical block number/offset pairs which represent the
227 * path of indirect blocks required to access a data block.  The first "pair"
228 * contains the logical block number of the appropriate single, double or
229 * triple indirect block and the offset into the inode indirect block array.
230 * Note, the logical block number of the inode single/double/triple indirect
231 * block appears twice in the array, once with the offset into the i_ffs1_ib and
232 * once with the offset into the page itself.
233 */
234int
235ufs_getlbns(struct lfs * fs, struct uvnode * vp, daddr_t bn, struct indir * ap, int *nump)
236{
237	daddr_t metalbn, realbn;
238	int64_t blockcnt;
239	int lbc;
240	int i, numlevels, off;
241	int lognindir, indir;
242
243	metalbn = 0;    /* XXXGCC -Wuninitialized [sh3] */
244
245	if (nump)
246		*nump = 0;
247	numlevels = 0;
248	realbn = bn;
249	if (bn < 0)
250		bn = -bn;
251
252	lognindir = -1;
253	for (indir = fs->lfs_nindir; indir; indir >>= 1)
254		++lognindir;
255
256	/* Determine the number of levels of indirection.  After this loop is
257	 * done, blockcnt indicates the number of data blocks possible at the
258	 * given level of indirection, and NIADDR - i is the number of levels
259	 * of indirection needed to locate the requested block. */
260
261	bn -= NDADDR;
262	for (lbc = 0, i = NIADDR;; i--, bn -= blockcnt) {
263		if (i == 0)
264			return (EFBIG);
265
266		lbc += lognindir;
267		blockcnt = (int64_t) 1 << lbc;
268
269		if (bn < blockcnt)
270			break;
271	}
272
273	/* Calculate the address of the first meta-block. */
274	metalbn = -((realbn >= 0 ? realbn : -realbn) - bn + NIADDR - i);
275
276	/* At each iteration, off is the offset into the bap array which is an
277	 * array of disk addresses at the current level of indirection. The
278	 * logical block number and the offset in that block are stored into
279	 * the argument array. */
280	ap->in_lbn = metalbn;
281	ap->in_off = off = NIADDR - i;
282	ap->in_exists = 0;
283	ap++;
284	for (++numlevels; i <= NIADDR; i++) {
285		/* If searching for a meta-data block, quit when found. */
286		if (metalbn == realbn)
287			break;
288
289		lbc -= lognindir;
290		blockcnt = (int64_t) 1 << lbc;
291		off = (bn >> lbc) & (fs->lfs_nindir - 1);
292
293		++numlevels;
294		ap->in_lbn = metalbn;
295		ap->in_off = off;
296		ap->in_exists = 0;
297		++ap;
298
299		metalbn -= -1 + (off << lbc);
300	}
301	if (nump)
302		*nump = numlevels;
303	return (0);
304}
305
306int
307lfs_vop_bmap(struct uvnode * vp, daddr_t lbn, daddr_t * daddrp)
308{
309	return ufs_bmaparray(vp->v_fs, vp, lbn, daddrp, NULL, NULL);
310}
311
312/* Search a block for a specific dinode. */
313struct ufs1_dinode *
314lfs_ifind(struct lfs * fs, ino_t ino, struct ubuf * bp)
315{
316	struct ufs1_dinode *dip = (struct ufs1_dinode *) bp->b_data;
317	struct ufs1_dinode *ldip, *fin;
318
319	fin = dip + INOPB(fs);
320
321	/*
322	 * Read the inode block backwards, since later versions of the
323	 * inode will supercede earlier ones.  Though it is unlikely, it is
324	 * possible that the same inode will appear in the same inode block.
325	 */
326	for (ldip = fin - 1; ldip >= dip; --ldip)
327		if (ldip->di_inumber == ino)
328			return (ldip);
329	return NULL;
330}
331
332/*
333 * lfs_raw_vget makes us a new vnode from the inode at the given disk address.
334 * XXX it currently loses atime information.
335 */
336struct uvnode *
337lfs_raw_vget(struct lfs * fs, ino_t ino, int fd, ufs_daddr_t daddr)
338{
339	struct uvnode *vp;
340	struct inode *ip;
341	struct ufs1_dinode *dip;
342	struct ubuf *bp;
343	int i, hash;
344
345	vp = ecalloc(1, sizeof(*vp));
346	vp->v_fd = fd;
347	vp->v_fs = fs;
348	vp->v_usecount = 0;
349	vp->v_strategy_op = lfs_vop_strategy;
350	vp->v_bwrite_op = lfs_vop_bwrite;
351	vp->v_bmap_op = lfs_vop_bmap;
352	LIST_INIT(&vp->v_cleanblkhd);
353	LIST_INIT(&vp->v_dirtyblkhd);
354
355	ip = ecalloc(1, sizeof(*ip));
356
357	ip->i_din.ffs1_din = ecalloc(1, sizeof(*ip->i_din.ffs1_din));
358
359	/* Initialize the inode -- from lfs_vcreate. */
360	ip->inode_ext.lfs = ecalloc(1, sizeof(*ip->inode_ext.lfs));
361	vp->v_data = ip;
362	/* ip->i_vnode = vp; */
363	ip->i_number = ino;
364	ip->i_lockf = 0;
365	ip->i_lfs_effnblks = 0;
366	ip->i_flag = 0;
367
368	/* Load inode block and find inode */
369	if (daddr > 0) {
370		bread(fs->lfs_devvp, fsbtodb(fs, daddr), fs->lfs_ibsize,
371		    NULL, 0, &bp);
372		bp->b_flags |= B_AGE;
373		dip = lfs_ifind(fs, ino, bp);
374		if (dip == NULL) {
375			brelse(bp, 0);
376			free(ip);
377			free(vp);
378			return NULL;
379		}
380		memcpy(ip->i_din.ffs1_din, dip, sizeof(*dip));
381		brelse(bp, 0);
382	}
383	ip->i_number = ino;
384	/* ip->i_devvp = fs->lfs_devvp; */
385	ip->i_lfs = fs;
386
387	ip->i_lfs_effnblks = ip->i_ffs1_blocks;
388	ip->i_lfs_osize = ip->i_ffs1_size;
389#if 0
390	if (fs->lfs_version > 1) {
391		ip->i_ffs1_atime = ts.tv_sec;
392		ip->i_ffs1_atimensec = ts.tv_nsec;
393	}
394#endif
395
396	memset(ip->i_lfs_fragsize, 0, NDADDR * sizeof(*ip->i_lfs_fragsize));
397	for (i = 0; i < NDADDR; i++)
398		if (ip->i_ffs1_db[i] != 0)
399			ip->i_lfs_fragsize[i] = blksize(fs, ip, i);
400
401	++nvnodes;
402	hash = ((int)(intptr_t)fs + ino) & (VNODE_HASH_MAX - 1);
403	LIST_INSERT_HEAD(&getvnodelist[hash], vp, v_getvnodes);
404	LIST_INSERT_HEAD(&vnodelist, vp, v_mntvnodes);
405
406	return vp;
407}
408
409static struct uvnode *
410lfs_vget(void *vfs, ino_t ino)
411{
412	struct lfs *fs = (struct lfs *)vfs;
413	ufs_daddr_t daddr;
414	struct ubuf *bp;
415	IFILE *ifp;
416
417	LFS_IENTRY(ifp, fs, ino, bp);
418	daddr = ifp->if_daddr;
419	brelse(bp, 0);
420	if (daddr <= 0 || dtosn(fs, daddr) >= fs->lfs_nseg)
421		return NULL;
422	return lfs_raw_vget(fs, ino, fs->lfs_ivnode->v_fd, daddr);
423}
424
425/* Check superblock magic number and checksum */
426static int
427check_sb(struct lfs *fs)
428{
429	u_int32_t checksum;
430
431	if (fs->lfs_magic != LFS_MAGIC) {
432		printf("Superblock magic number (0x%lx) does not match "
433		       "expected 0x%lx\n", (unsigned long) fs->lfs_magic,
434		       (unsigned long) LFS_MAGIC);
435		return 1;
436	}
437	/* checksum */
438	checksum = lfs_sb_cksum(&(fs->lfs_dlfs));
439	if (fs->lfs_cksum != checksum) {
440		printf("Superblock checksum (%lx) does not match computed checksum (%lx)\n",
441		    (unsigned long) fs->lfs_cksum, (unsigned long) checksum);
442		return 1;
443	}
444	return 0;
445}
446
447/* Initialize LFS library; load superblocks and choose which to use. */
448struct lfs *
449lfs_init(int devfd, daddr_t sblkno, daddr_t idaddr, int dummy_read, int debug)
450{
451	struct uvnode *devvp;
452	struct ubuf *bp;
453	int tryalt;
454	struct lfs *fs, *altfs;
455	int error;
456
457	vfs_init();
458
459	devvp = ecalloc(1, sizeof(*devvp));
460	devvp->v_fs = NULL;
461	devvp->v_fd = devfd;
462	devvp->v_strategy_op = raw_vop_strategy;
463	devvp->v_bwrite_op = raw_vop_bwrite;
464	devvp->v_bmap_op = raw_vop_bmap;
465	LIST_INIT(&devvp->v_cleanblkhd);
466	LIST_INIT(&devvp->v_dirtyblkhd);
467
468	tryalt = 0;
469	if (dummy_read) {
470		if (sblkno == 0)
471			sblkno = LFS_LABELPAD / dev_bsize;
472		fs = ecalloc(1, sizeof(*fs));
473		fs->lfs_devvp = devvp;
474	} else {
475		if (sblkno == 0) {
476			sblkno = LFS_LABELPAD / dev_bsize;
477			tryalt = 1;
478		} else if (debug) {
479			printf("No -b flag given, not attempting to verify checkpoint\n");
480		}
481
482		dev_bsize = DEV_BSIZE;
483
484		error = bread(devvp, sblkno, LFS_SBPAD, NOCRED, 0, &bp);
485		fs = ecalloc(1, sizeof(*fs));
486		fs->lfs_dlfs = *((struct dlfs *) bp->b_data);
487		fs->lfs_devvp = devvp;
488		bp->b_flags |= B_INVAL;
489		brelse(bp, 0);
490
491		dev_bsize = fs->lfs_fsize >> fs->lfs_fsbtodb;
492
493		if (tryalt) {
494			error = bread(devvp, fsbtodb(fs, fs->lfs_sboffs[1]),
495		    	LFS_SBPAD, NOCRED, 0, &bp);
496			altfs = ecalloc(1, sizeof(*altfs));
497			altfs->lfs_dlfs = *((struct dlfs *) bp->b_data);
498			altfs->lfs_devvp = devvp;
499			bp->b_flags |= B_INVAL;
500			brelse(bp, 0);
501
502			if (check_sb(fs) || fs->lfs_idaddr <= 0) {
503				if (debug)
504					printf("Primary superblock is no good, using first alternate\n");
505				free(fs);
506				fs = altfs;
507			} else {
508				/* If both superblocks check out, try verification */
509				if (check_sb(altfs)) {
510					if (debug)
511						printf("First alternate superblock is no good, using primary\n");
512					free(altfs);
513				} else {
514					if (lfs_verify(fs, altfs, devvp, debug) == fs) {
515						free(altfs);
516					} else {
517						free(fs);
518						fs = altfs;
519					}
520				}
521			}
522		}
523		if (check_sb(fs)) {
524			free(fs);
525			return NULL;
526		}
527	}
528
529	/* Compatibility */
530	if (fs->lfs_version < 2) {
531		fs->lfs_sumsize = LFS_V1_SUMMARY_SIZE;
532		fs->lfs_ibsize = fs->lfs_bsize;
533		fs->lfs_start = fs->lfs_sboffs[0];
534		fs->lfs_tstamp = fs->lfs_otstamp;
535		fs->lfs_fsbtodb = 0;
536	}
537
538	if (!dummy_read) {
539		fs->lfs_suflags = emalloc(2 * sizeof(u_int32_t *));
540		fs->lfs_suflags[0] = emalloc(fs->lfs_nseg * sizeof(u_int32_t));
541		fs->lfs_suflags[1] = emalloc(fs->lfs_nseg * sizeof(u_int32_t));
542	}
543
544	if (idaddr == 0)
545		idaddr = fs->lfs_idaddr;
546	else
547		fs->lfs_idaddr = idaddr;
548	/* NB: If dummy_read!=0, idaddr==0 here so we get a fake inode. */
549	fs->lfs_ivnode = lfs_raw_vget(fs,
550		(dummy_read ? LFS_IFILE_INUM : fs->lfs_ifile), devvp->v_fd,
551		idaddr);
552	if (fs->lfs_ivnode == NULL)
553		return NULL;
554
555	register_vget((void *)fs, lfs_vget);
556
557	return fs;
558}
559
560/*
561 * Check partial segment validity between fs->lfs_offset and the given goal.
562 *
563 * If goal == 0, just keep on going until the segments stop making sense,
564 * and return the address of the last valid partial segment.
565 *
566 * If goal != 0, return the address of the first partial segment that failed,
567 * or "goal" if we reached it without failure (the partial segment *at* goal
568 * need not be valid).
569 */
570ufs_daddr_t
571try_verify(struct lfs *osb, struct uvnode *devvp, ufs_daddr_t goal, int debug)
572{
573	ufs_daddr_t daddr, odaddr;
574	SEGSUM *sp;
575	int i, bc, hitclean;
576	struct ubuf *bp;
577	ufs_daddr_t nodirop_daddr;
578	u_int64_t serial;
579
580	bc = 0;
581	hitclean = 0;
582	odaddr = -1;
583	daddr = osb->lfs_offset;
584	nodirop_daddr = daddr;
585	serial = osb->lfs_serial;
586	while (daddr != goal) {
587		/*
588		 * Don't mistakenly read a superblock, if there is one here.
589		 */
590		if (sntod(osb, dtosn(osb, daddr)) == daddr) {
591			if (daddr == osb->lfs_start)
592				daddr += btofsb(osb, LFS_LABELPAD);
593			for (i = 0; i < LFS_MAXNUMSB; i++) {
594				if (osb->lfs_sboffs[i] < daddr)
595					break;
596				if (osb->lfs_sboffs[i] == daddr)
597					daddr += btofsb(osb, LFS_SBPAD);
598			}
599		}
600
601		/* Read in summary block */
602		bread(devvp, fsbtodb(osb, daddr), osb->lfs_sumsize,
603		    NULL, 0, &bp);
604		sp = (SEGSUM *)bp->b_data;
605
606		/*
607		 * Check for a valid segment summary belonging to our fs.
608		 */
609		if (sp->ss_magic != SS_MAGIC ||
610		    sp->ss_ident != osb->lfs_ident ||
611		    sp->ss_serial < serial ||	/* XXX strengthen this */
612		    sp->ss_sumsum != cksum(&sp->ss_datasum, osb->lfs_sumsize -
613			sizeof(sp->ss_sumsum))) {
614			brelse(bp, 0);
615			if (debug) {
616				if (sp->ss_magic != SS_MAGIC)
617					pwarn("pseg at 0x%x: "
618					      "wrong magic number\n",
619					      (int)daddr);
620				else if (sp->ss_ident != osb->lfs_ident)
621					pwarn("pseg at 0x%x: "
622					      "expected ident %llx, got %llx\n",
623					      (int)daddr,
624					      (long long)sp->ss_ident,
625					      (long long)osb->lfs_ident);
626				else if (sp->ss_serial >= serial)
627					pwarn("pseg at 0x%x: "
628					      "serial %d < %d\n", (int)daddr,
629					      (int)sp->ss_serial, (int)serial);
630				else
631					pwarn("pseg at 0x%x: "
632					      "summary checksum wrong\n",
633					      (int)daddr);
634			}
635			break;
636		}
637		if (debug && sp->ss_serial != serial)
638			pwarn("warning, serial=%d ss_serial=%d\n",
639				(int)serial, (int)sp->ss_serial);
640		++serial;
641		bc = check_summary(osb, sp, daddr, debug, devvp, NULL);
642		if (bc == 0) {
643			brelse(bp, 0);
644			break;
645		}
646		if (debug)
647			pwarn("summary good: 0x%x/%d\n", (int)daddr,
648			      (int)sp->ss_serial);
649		assert (bc > 0);
650		odaddr = daddr;
651		daddr += btofsb(osb, osb->lfs_sumsize + bc);
652		if (dtosn(osb, odaddr) != dtosn(osb, daddr) ||
653		    dtosn(osb, daddr) != dtosn(osb, daddr +
654			btofsb(osb, osb->lfs_sumsize + osb->lfs_bsize) - 1)) {
655			daddr = sp->ss_next;
656		}
657
658		/*
659		 * Check for the beginning and ending of a sequence of
660		 * dirops.  Writes from the cleaner never involve new
661		 * information, and are always checkpoints; so don't try
662		 * to roll forward through them.  Likewise, psegs written
663		 * by a previous roll-forward attempt are not interesting.
664		 */
665		if (sp->ss_flags & (SS_CLEAN | SS_RFW))
666			hitclean = 1;
667		if (hitclean == 0 && (sp->ss_flags & SS_CONT) == 0)
668			nodirop_daddr = daddr;
669
670		brelse(bp, 0);
671	}
672
673	if (goal == 0)
674		return nodirop_daddr;
675	else
676		return daddr;
677}
678
679/* Use try_verify to check whether the newer superblock is valid. */
680struct lfs *
681lfs_verify(struct lfs *sb0, struct lfs *sb1, struct uvnode *devvp, int debug)
682{
683	ufs_daddr_t daddr;
684	struct lfs *osb, *nsb;
685
686	/*
687	 * Verify the checkpoint of the newer superblock,
688	 * if the timestamp/serial number of the two superblocks is
689	 * different.
690	 */
691
692	osb = NULL;
693	if (debug)
694		pwarn("sb0 %lld, sb1 %lld",
695		      (long long) sb0->lfs_serial,
696		      (long long) sb1->lfs_serial);
697
698	if ((sb0->lfs_version == 1 &&
699		sb0->lfs_otstamp != sb1->lfs_otstamp) ||
700	    (sb0->lfs_version > 1 &&
701		sb0->lfs_serial != sb1->lfs_serial)) {
702		if (sb0->lfs_version == 1) {
703			if (sb0->lfs_otstamp > sb1->lfs_otstamp) {
704				osb = sb1;
705				nsb = sb0;
706			} else {
707				osb = sb0;
708				nsb = sb1;
709			}
710		} else {
711			if (sb0->lfs_serial > sb1->lfs_serial) {
712				osb = sb1;
713				nsb = sb0;
714			} else {
715				osb = sb0;
716				nsb = sb1;
717			}
718		}
719		if (debug) {
720			printf("Attempting to verify newer checkpoint...");
721			fflush(stdout);
722		}
723		daddr = try_verify(osb, devvp, nsb->lfs_offset, debug);
724
725		if (debug)
726			printf("done.\n");
727		if (daddr == nsb->lfs_offset) {
728			pwarn("** Newer checkpoint verified, recovered %lld seconds of data\n",
729			    (long long) nsb->lfs_tstamp - (long long) osb->lfs_tstamp);
730			sbdirty();
731		} else {
732			pwarn("** Newer checkpoint invalid, lost %lld seconds of data\n", (long long) nsb->lfs_tstamp - (long long) osb->lfs_tstamp);
733		}
734		return (daddr == nsb->lfs_offset ? nsb : osb);
735	}
736	/* Nothing to check */
737	return osb;
738}
739
740/* Verify a partial-segment summary; return the number of bytes on disk. */
741int
742check_summary(struct lfs *fs, SEGSUM *sp, ufs_daddr_t pseg_addr, int debug,
743	      struct uvnode *devvp, void (func(ufs_daddr_t, FINFO *)))
744{
745	FINFO *fp;
746	int bc;			/* Bytes in partial segment */
747	int nblocks;
748	ufs_daddr_t seg_addr, daddr;
749	ufs_daddr_t *dp, *idp;
750	struct ubuf *bp;
751	int i, j, k, datac, len;
752	long sn;
753	u_int32_t *datap;
754	u_int32_t ccksum;
755
756	sn = dtosn(fs, pseg_addr);
757	seg_addr = sntod(fs, sn);
758
759	/* We've already checked the sumsum, just do the data bounds and sum */
760
761	/* Count the blocks. */
762	nblocks = howmany(sp->ss_ninos, INOPB(fs));
763	bc = nblocks << (fs->lfs_version > 1 ? fs->lfs_ffshift : fs->lfs_bshift);
764	assert(bc >= 0);
765
766	fp = (FINFO *) (sp + 1);
767	for (i = 0; i < sp->ss_nfinfo; i++) {
768		nblocks += fp->fi_nblocks;
769		bc += fp->fi_lastlength + ((fp->fi_nblocks - 1)
770					   << fs->lfs_bshift);
771		assert(bc >= 0);
772		fp = (FINFO *) (fp->fi_blocks + fp->fi_nblocks);
773		if (((char *)fp) - (char *)sp > fs->lfs_sumsize)
774			return 0;
775	}
776	datap = emalloc(nblocks * sizeof(*datap));
777	datac = 0;
778
779	dp = (ufs_daddr_t *) sp;
780	dp += fs->lfs_sumsize / sizeof(ufs_daddr_t);
781	dp--;
782
783	idp = dp;
784	daddr = pseg_addr + btofsb(fs, fs->lfs_sumsize);
785	fp = (FINFO *) (sp + 1);
786	for (i = 0, j = 0;
787	     i < sp->ss_nfinfo || j < howmany(sp->ss_ninos, INOPB(fs)); i++) {
788		if (i >= sp->ss_nfinfo && *idp != daddr) {
789			pwarn("Not enough inode blocks in pseg at 0x%" PRIx32
790			      ": found %d, wanted %d\n",
791			      pseg_addr, j, howmany(sp->ss_ninos, INOPB(fs)));
792			if (debug)
793				pwarn("*idp=%x, daddr=%" PRIx32 "\n", *idp,
794				      daddr);
795			break;
796		}
797		while (j < howmany(sp->ss_ninos, INOPB(fs)) && *idp == daddr) {
798			bread(devvp, fsbtodb(fs, daddr), fs->lfs_ibsize,
799			    NOCRED, 0, &bp);
800			datap[datac++] = ((u_int32_t *) (bp->b_data))[0];
801			brelse(bp, 0);
802
803			++j;
804			daddr += btofsb(fs, fs->lfs_ibsize);
805			--idp;
806		}
807		if (i < sp->ss_nfinfo) {
808			if (func)
809				func(daddr, fp);
810			for (k = 0; k < fp->fi_nblocks; k++) {
811				len = (k == fp->fi_nblocks - 1 ?
812				       fp->fi_lastlength
813				       : fs->lfs_bsize);
814				bread(devvp, fsbtodb(fs, daddr), len,
815				    NOCRED, 0, &bp);
816				datap[datac++] = ((u_int32_t *) (bp->b_data))[0];
817				brelse(bp, 0);
818				daddr += btofsb(fs, len);
819			}
820			fp = (FINFO *) (fp->fi_blocks + fp->fi_nblocks);
821		}
822	}
823
824	if (datac != nblocks) {
825		pwarn("Partial segment at 0x%llx expected %d blocks counted %d\n",
826		    (long long) pseg_addr, nblocks, datac);
827	}
828	ccksum = cksum(datap, nblocks * sizeof(u_int32_t));
829	/* Check the data checksum */
830	if (ccksum != sp->ss_datasum) {
831		pwarn("Partial segment at 0x%" PRIx32 " data checksum"
832		      " mismatch: given 0x%x, computed 0x%x\n",
833		      pseg_addr, sp->ss_datasum, ccksum);
834		free(datap);
835		return 0;
836	}
837	free(datap);
838	assert(bc >= 0);
839	return bc;
840}
841
842/* print message and exit */
843void
844my_vpanic(int fatal, const char *fmt, va_list ap)
845{
846        (void) vprintf(fmt, ap);
847	exit(8);
848}
849
850void
851call_panic(const char *fmt, ...)
852{
853	va_list ap;
854
855	va_start(ap, fmt);
856        panic_func(1, fmt, ap);
857	va_end(ap);
858}
859
860/* Allocate a new inode. */
861struct uvnode *
862lfs_valloc(struct lfs *fs, ino_t ino)
863{
864	struct ubuf *bp, *cbp;
865	struct ifile *ifp;
866	ino_t new_ino;
867	int error;
868	int new_gen;
869	CLEANERINFO *cip;
870
871	/* Get the head of the freelist. */
872	LFS_GET_HEADFREE(fs, cip, cbp, &new_ino);
873
874	/*
875	 * Remove the inode from the free list and write the new start
876	 * of the free list into the superblock.
877	 */
878	LFS_IENTRY(ifp, fs, new_ino, bp);
879	if (ifp->if_daddr != LFS_UNUSED_DADDR)
880		panic("lfs_valloc: inuse inode %d on the free list", new_ino);
881	LFS_PUT_HEADFREE(fs, cip, cbp, ifp->if_nextfree);
882
883	new_gen = ifp->if_version; /* version was updated by vfree */
884	brelse(bp, 0);
885
886	/* Extend IFILE so that the next lfs_valloc will succeed. */
887	if (fs->lfs_freehd == LFS_UNUSED_INUM) {
888		if ((error = extend_ifile(fs)) != 0) {
889			LFS_PUT_HEADFREE(fs, cip, cbp, new_ino);
890			return NULL;
891		}
892	}
893
894	/* Set superblock modified bit and increment file count. */
895        sbdirty();
896	++fs->lfs_nfiles;
897
898        return lfs_raw_vget(fs, ino, fs->lfs_devvp->v_fd, 0x0);
899}
900
901#ifdef IN_FSCK_LFS
902void reset_maxino(ino_t);
903#endif
904
905/*
906 * Add a new block to the Ifile, to accommodate future file creations.
907 */
908int
909extend_ifile(struct lfs *fs)
910{
911	struct uvnode *vp;
912	struct inode *ip;
913	IFILE *ifp;
914	IFILE_V1 *ifp_v1;
915	struct ubuf *bp, *cbp;
916	daddr_t i, blkno, max;
917	ino_t oldlast;
918	CLEANERINFO *cip;
919
920	vp = fs->lfs_ivnode;
921	ip = VTOI(vp);
922	blkno = lblkno(fs, ip->i_ffs1_size);
923
924	lfs_balloc(vp, ip->i_ffs1_size, fs->lfs_bsize, &bp);
925	ip->i_ffs1_size += fs->lfs_bsize;
926	ip->i_flag |= IN_MODIFIED;
927
928	i = (blkno - fs->lfs_segtabsz - fs->lfs_cleansz) *
929		fs->lfs_ifpb;
930	LFS_GET_HEADFREE(fs, cip, cbp, &oldlast);
931	LFS_PUT_HEADFREE(fs, cip, cbp, i);
932	max = i + fs->lfs_ifpb;
933	fs->lfs_bfree -= btofsb(fs, fs->lfs_bsize);
934
935	if (fs->lfs_version == 1) {
936		for (ifp_v1 = (IFILE_V1 *)bp->b_data; i < max; ++ifp_v1) {
937			ifp_v1->if_version = 1;
938			ifp_v1->if_daddr = LFS_UNUSED_DADDR;
939			ifp_v1->if_nextfree = ++i;
940		}
941		ifp_v1--;
942		ifp_v1->if_nextfree = oldlast;
943	} else {
944		for (ifp = (IFILE *)bp->b_data; i < max; ++ifp) {
945			ifp->if_version = 1;
946			ifp->if_daddr = LFS_UNUSED_DADDR;
947			ifp->if_nextfree = ++i;
948		}
949		ifp--;
950		ifp->if_nextfree = oldlast;
951	}
952	LFS_PUT_TAILFREE(fs, cip, cbp, max - 1);
953
954	LFS_BWRITE_LOG(bp);
955
956#ifdef IN_FSCK_LFS
957	reset_maxino(((ip->i_ffs1_size >> fs->lfs_bshift) - fs->lfs_segtabsz -
958		     fs->lfs_cleansz) * fs->lfs_ifpb);
959#endif
960	return 0;
961}
962
963/*
964 * Allocate a block, and to inode and filesystem block accounting for it
965 * and for any indirect blocks the may need to be created in order for
966 * this block to be created.
967 *
968 * Blocks which have never been accounted for (i.e., which "do not exist")
969 * have disk address 0, which is translated by ufs_bmap to the special value
970 * UNASSIGNED == -1, as in the historical UFS.
971 *
972 * Blocks which have been accounted for but which have not yet been written
973 * to disk are given the new special disk address UNWRITTEN == -2, so that
974 * they can be differentiated from completely new blocks.
975 */
976int
977lfs_balloc(struct uvnode *vp, off_t startoffset, int iosize, struct ubuf **bpp)
978{
979	int offset;
980	daddr_t daddr, idaddr;
981	struct ubuf *ibp, *bp;
982	struct inode *ip;
983	struct lfs *fs;
984	struct indir indirs[NIADDR+2], *idp;
985	daddr_t	lbn, lastblock;
986	int bcount;
987	int error, frags, i, nsize, osize, num;
988
989	ip = VTOI(vp);
990	fs = ip->i_lfs;
991	offset = blkoff(fs, startoffset);
992	lbn = lblkno(fs, startoffset);
993
994	/*
995	 * Three cases: it's a block beyond the end of file, it's a block in
996	 * the file that may or may not have been assigned a disk address or
997	 * we're writing an entire block.
998	 *
999	 * Note, if the daddr is UNWRITTEN, the block already exists in
1000	 * the cache (it was read or written earlier).	If so, make sure
1001	 * we don't count it as a new block or zero out its contents. If
1002	 * it did not, make sure we allocate any necessary indirect
1003	 * blocks.
1004	 *
1005	 * If we are writing a block beyond the end of the file, we need to
1006	 * check if the old last block was a fragment.	If it was, we need
1007	 * to rewrite it.
1008	 */
1009
1010	if (bpp)
1011		*bpp = NULL;
1012
1013	/* Check for block beyond end of file and fragment extension needed. */
1014	lastblock = lblkno(fs, ip->i_ffs1_size);
1015	if (lastblock < NDADDR && lastblock < lbn) {
1016		osize = blksize(fs, ip, lastblock);
1017		if (osize < fs->lfs_bsize && osize > 0) {
1018			if ((error = lfs_fragextend(vp, osize, fs->lfs_bsize,
1019						    lastblock,
1020						    (bpp ? &bp : NULL))))
1021				return (error);
1022			ip->i_ffs1_size = (lastblock + 1) * fs->lfs_bsize;
1023			ip->i_flag |= IN_CHANGE | IN_UPDATE;
1024			if (bpp)
1025				(void) VOP_BWRITE(bp);
1026		}
1027	}
1028
1029	/*
1030	 * If the block we are writing is a direct block, it's the last
1031	 * block in the file, and offset + iosize is less than a full
1032	 * block, we can write one or more fragments.  There are two cases:
1033	 * the block is brand new and we should allocate it the correct
1034	 * size or it already exists and contains some fragments and
1035	 * may need to extend it.
1036	 */
1037	if (lbn < NDADDR && lblkno(fs, ip->i_ffs1_size) <= lbn) {
1038		osize = blksize(fs, ip, lbn);
1039		nsize = fragroundup(fs, offset + iosize);
1040		if (lblktosize(fs, lbn) >= ip->i_ffs1_size) {
1041			/* Brand new block or fragment */
1042			frags = numfrags(fs, nsize);
1043			if (bpp) {
1044				*bpp = bp = getblk(vp, lbn, nsize);
1045				bp->b_blkno = UNWRITTEN;
1046			}
1047			ip->i_lfs_effnblks += frags;
1048			fs->lfs_bfree -= frags;
1049			ip->i_ffs1_db[lbn] = UNWRITTEN;
1050		} else {
1051			if (nsize <= osize) {
1052				/* No need to extend */
1053				if (bpp && (error = bread(vp, lbn, osize,
1054				    NOCRED, 0, &bp)))
1055					return error;
1056			} else {
1057				/* Extend existing block */
1058				if ((error =
1059				     lfs_fragextend(vp, osize, nsize, lbn,
1060						    (bpp ? &bp : NULL))))
1061					return error;
1062			}
1063			if (bpp)
1064				*bpp = bp;
1065		}
1066		return 0;
1067	}
1068
1069	error = ufs_bmaparray(fs, vp, lbn, &daddr, &indirs[0], &num);
1070	if (error)
1071		return (error);
1072
1073	daddr = (daddr_t)((int32_t)daddr); /* XXX ondisk32 */
1074
1075	/*
1076	 * Do byte accounting all at once, so we can gracefully fail *before*
1077	 * we start assigning blocks.
1078	 */
1079        frags = fsbtodb(fs, 1); /* frags = VFSTOUFS(vp->v_mount)->um_seqinc; */
1080	bcount = 0;
1081	if (daddr == UNASSIGNED) {
1082		bcount = frags;
1083	}
1084	for (i = 1; i < num; ++i) {
1085		if (!indirs[i].in_exists) {
1086			bcount += frags;
1087		}
1088	}
1089	fs->lfs_bfree -= bcount;
1090	ip->i_lfs_effnblks += bcount;
1091
1092	if (daddr == UNASSIGNED) {
1093		if (num > 0 && ip->i_ffs1_ib[indirs[0].in_off] == 0) {
1094			ip->i_ffs1_ib[indirs[0].in_off] = UNWRITTEN;
1095		}
1096
1097		/*
1098		 * Create new indirect blocks if necessary
1099		 */
1100		if (num > 1) {
1101			idaddr = ip->i_ffs1_ib[indirs[0].in_off];
1102			for (i = 1; i < num; ++i) {
1103				ibp = getblk(vp, indirs[i].in_lbn,
1104				    fs->lfs_bsize);
1105				if (!indirs[i].in_exists) {
1106					memset(ibp->b_data, 0, ibp->b_bufsize);
1107					ibp->b_blkno = UNWRITTEN;
1108				} else if (!(ibp->b_flags & (B_DELWRI | B_DONE))) {
1109					ibp->b_blkno = fsbtodb(fs, idaddr);
1110					ibp->b_flags |= B_READ;
1111					VOP_STRATEGY(ibp);
1112				}
1113				/*
1114				 * This block exists, but the next one may not.
1115				 * If that is the case mark it UNWRITTEN to
1116                                 * keep the accounting straight.
1117				 */
1118				/* XXX ondisk32 */
1119				if (((int32_t *)ibp->b_data)[indirs[i].in_off] == 0)
1120					((int32_t *)ibp->b_data)[indirs[i].in_off] =
1121						UNWRITTEN;
1122				/* XXX ondisk32 */
1123				idaddr = ((int32_t *)ibp->b_data)[indirs[i].in_off];
1124				if ((error = VOP_BWRITE(ibp)))
1125					return error;
1126			}
1127		}
1128	}
1129
1130
1131	/*
1132	 * Get the existing block from the cache, if requested.
1133	 */
1134	if (bpp)
1135		*bpp = bp = getblk(vp, lbn, blksize(fs, ip, lbn));
1136
1137	/*
1138	 * The block we are writing may be a brand new block
1139	 * in which case we need to do accounting.
1140	 *
1141	 * We can tell a truly new block because ufs_bmaparray will say
1142	 * it is UNASSIGNED.  Once we allocate it we will assign it the
1143	 * disk address UNWRITTEN.
1144	 */
1145	if (daddr == UNASSIGNED) {
1146		if (bpp) {
1147			/* Note the new address */
1148			bp->b_blkno = UNWRITTEN;
1149		}
1150
1151		switch (num) {
1152		    case 0:
1153			ip->i_ffs1_db[lbn] = UNWRITTEN;
1154			break;
1155		    case 1:
1156			ip->i_ffs1_ib[indirs[0].in_off] = UNWRITTEN;
1157			break;
1158		    default:
1159			idp = &indirs[num - 1];
1160			if (bread(vp, idp->in_lbn, fs->lfs_bsize, NOCRED,
1161				  0, &ibp))
1162				panic("lfs_balloc: bread bno %lld",
1163				    (long long)idp->in_lbn);
1164			/* XXX ondisk32 */
1165			((int32_t *)ibp->b_data)[idp->in_off] = UNWRITTEN;
1166			VOP_BWRITE(ibp);
1167		}
1168	} else if (bpp && !(bp->b_flags & (B_DONE|B_DELWRI))) {
1169		/*
1170		 * Not a brand new block, also not in the cache;
1171		 * read it in from disk.
1172		 */
1173		if (iosize == fs->lfs_bsize)
1174			/* Optimization: I/O is unnecessary. */
1175			bp->b_blkno = daddr;
1176		else {
1177			/*
1178			 * We need to read the block to preserve the
1179			 * existing bytes.
1180			 */
1181			bp->b_blkno = daddr;
1182			bp->b_flags |= B_READ;
1183			VOP_STRATEGY(bp);
1184			return 0;
1185		}
1186	}
1187
1188	return (0);
1189}
1190
1191int
1192lfs_fragextend(struct uvnode *vp, int osize, int nsize, daddr_t lbn,
1193               struct ubuf **bpp)
1194{
1195	struct inode *ip;
1196	struct lfs *fs;
1197	int frags;
1198	int error;
1199	size_t obufsize;
1200
1201	ip = VTOI(vp);
1202	fs = ip->i_lfs;
1203	frags = (long)numfrags(fs, nsize - osize);
1204	error = 0;
1205
1206	/*
1207	 * If we are not asked to actually return the block, all we need
1208	 * to do is allocate space for it.  UBC will handle dirtying the
1209	 * appropriate things and making sure it all goes to disk.
1210	 * Don't bother to read in that case.
1211	 */
1212	if (bpp && (error = bread(vp, lbn, osize, NOCRED, 0, bpp))) {
1213		brelse(*bpp, 0);
1214		goto out;
1215	}
1216
1217	fs->lfs_bfree -= frags;
1218	ip->i_lfs_effnblks += frags;
1219	ip->i_flag |= IN_CHANGE | IN_UPDATE;
1220
1221	if (bpp) {
1222		obufsize = (*bpp)->b_bufsize;
1223		(*bpp)->b_data = erealloc((*bpp)->b_data, nsize);
1224		(void)memset((*bpp)->b_data + osize, 0, nsize - osize);
1225	}
1226
1227    out:
1228	return (error);
1229}
1230