xref: /netbsd-src/sys/ufs/lfs/lfs_segment.c (revision 1f2744e6e4915c9da2a3f980279398c4cf7d5e6d)
1 /*	$NetBSD: lfs_segment.c,v 1.3 1994/08/21 03:15:32 cgd Exp $	*/
2 
3 /*
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  *	@(#)lfs_segment.c	8.5 (Berkeley) 1/4/94
36  */
37 
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/namei.h>
41 #include <sys/kernel.h>
42 #include <sys/resourcevar.h>
43 #include <sys/file.h>
44 #include <sys/stat.h>
45 #include <sys/buf.h>
46 #include <sys/proc.h>
47 #include <sys/conf.h>
48 #include <sys/vnode.h>
49 #include <sys/malloc.h>
50 #include <sys/mount.h>
51 
52 #include <miscfs/specfs/specdev.h>
53 #include <miscfs/fifofs/fifo.h>
54 
55 #include <ufs/ufs/quota.h>
56 #include <ufs/ufs/inode.h>
57 #include <ufs/ufs/dir.h>
58 #include <ufs/ufs/ufsmount.h>
59 #include <ufs/ufs/ufs_extern.h>
60 
61 #include <ufs/lfs/lfs.h>
62 #include <ufs/lfs/lfs_extern.h>
63 
64 extern int count_lock_queue __P((void));
65 
66 #define MAX_ACTIVE	10
67 /*
68  * Determine if it's OK to start a partial in this segment, or if we need
69  * to go on to a new segment.
70  */
71 #define	LFS_PARTIAL_FITS(fs) \
72 	((fs)->lfs_dbpseg - ((fs)->lfs_offset - (fs)->lfs_curseg) > \
73 	1 << (fs)->lfs_fsbtodb)
74 
75 void	 lfs_callback __P((struct buf *));
76 void	 lfs_gather __P((struct lfs *, struct segment *,
77 	     struct vnode *, int (*) __P((struct lfs *, struct buf *))));
78 int	 lfs_gatherblock __P((struct segment *, struct buf *, int *));
79 void	 lfs_iset __P((struct inode *, daddr_t, time_t));
80 int	 lfs_match_data __P((struct lfs *, struct buf *));
81 int	 lfs_match_dindir __P((struct lfs *, struct buf *));
82 int	 lfs_match_indir __P((struct lfs *, struct buf *));
83 int	 lfs_match_tindir __P((struct lfs *, struct buf *));
84 void	 lfs_newseg __P((struct lfs *));
85 void	 lfs_shellsort __P((struct buf **, daddr_t *, register int));
86 void	 lfs_supercallback __P((struct buf *));
87 void	 lfs_updatemeta __P((struct segment *));
88 int	 lfs_vref __P((struct vnode *));
89 void	 lfs_vunref __P((struct vnode *));
90 void	 lfs_writefile __P((struct lfs *, struct segment *, struct vnode *));
91 int	 lfs_writeinode __P((struct lfs *, struct segment *, struct inode *));
92 int	 lfs_writeseg __P((struct lfs *, struct segment *));
93 void	 lfs_writesuper __P((struct lfs *));
94 void	 lfs_writevnodes __P((struct lfs *fs, struct mount *mp,
95 	    struct segment *sp, int dirops));
96 
97 int	lfs_allclean_wakeup;		/* Cleaner wakeup address. */
98 
99 /* Statistics Counters */
100 #define DOSTATS
101 struct lfs_stats lfs_stats;
102 
103 /* op values to lfs_writevnodes */
104 #define	VN_REG	0
105 #define	VN_DIROP	1
106 #define	VN_EMPTY	2
107 
108 /*
109  * Ifile and meta data blocks are not marked busy, so segment writes MUST be
110  * single threaded.  Currently, there are two paths into lfs_segwrite, sync()
111  * and getnewbuf().  They both mark the file system busy.  Lfs_vflush()
112  * explicitly marks the file system busy.  So lfs_segwrite is safe.  I think.
113  */
114 
115 int
116 lfs_vflush(vp)
117 	struct vnode *vp;
118 {
119 	struct inode *ip;
120 	struct lfs *fs;
121 	struct segment *sp;
122 
123 	fs = VFSTOUFS(vp->v_mount)->um_lfs;
124 	if (fs->lfs_nactive > MAX_ACTIVE)
125 		return(lfs_segwrite(vp->v_mount, SEGM_SYNC|SEGM_CKP));
126 	lfs_seglock(fs, SEGM_SYNC);
127 	sp = fs->lfs_sp;
128 
129 
130 	ip = VTOI(vp);
131 	if (vp->v_dirtyblkhd.lh_first == NULL)
132 		lfs_writevnodes(fs, vp->v_mount, sp, VN_EMPTY);
133 
134 	do {
135 		do {
136 			if (vp->v_dirtyblkhd.lh_first != NULL)
137 				lfs_writefile(fs, sp, vp);
138 		} while (lfs_writeinode(fs, sp, ip));
139 
140 	} while (lfs_writeseg(fs, sp) && ip->i_number == LFS_IFILE_INUM);
141 
142 #ifdef DOSTATS
143 	++lfs_stats.nwrites;
144 	if (sp->seg_flags & SEGM_SYNC)
145 		++lfs_stats.nsync_writes;
146 	if (sp->seg_flags & SEGM_CKP)
147 		++lfs_stats.ncheckpoints;
148 #endif
149 	lfs_segunlock(fs);
150 	return (0);
151 }
152 
153 void
154 lfs_writevnodes(fs, mp, sp, op)
155 	struct lfs *fs;
156 	struct mount *mp;
157 	struct segment *sp;
158 	int op;
159 {
160 	struct inode *ip;
161 	struct vnode *vp;
162 
163 loop:
164 	for (vp = mp->mnt_vnodelist.lh_first;
165 	     vp != NULL;
166 	     vp = vp->v_mntvnodes.le_next) {
167 		/*
168 		 * If the vnode that we are about to sync is no longer
169 		 * associated with this mount point, start over.
170 		 */
171 		if (vp->v_mount != mp)
172 			goto loop;
173 
174 		/* XXX ignore dirops for now
175 		if (op == VN_DIROP && !(vp->v_flag & VDIROP) ||
176 		    op != VN_DIROP && (vp->v_flag & VDIROP))
177 			continue;
178 		*/
179 
180 		if (op == VN_EMPTY && vp->v_dirtyblkhd.lh_first)
181 			continue;
182 
183 		if (vp->v_type == VNON)
184 			continue;
185 
186 		if (lfs_vref(vp))
187 			continue;
188 
189 		/*
190 		 * Write the inode/file if dirty and it's not the
191 		 * the IFILE.
192 		 */
193 		ip = VTOI(vp);
194 		if ((ip->i_flag &
195 		    (IN_ACCESS | IN_CHANGE | IN_MODIFIED | IN_UPDATE) ||
196 		    vp->v_dirtyblkhd.lh_first != NULL) &&
197 		    ip->i_number != LFS_IFILE_INUM) {
198 			if (vp->v_dirtyblkhd.lh_first != NULL)
199 				lfs_writefile(fs, sp, vp);
200 			(void) lfs_writeinode(fs, sp, ip);
201 		}
202 		vp->v_flag &= ~VDIROP;
203 		lfs_vunref(vp);
204 	}
205 }
206 
207 int
208 lfs_segwrite(mp, flags)
209 	struct mount *mp;
210 	int flags;			/* Do a checkpoint. */
211 {
212 	struct buf *bp;
213 	struct inode *ip;
214 	struct lfs *fs;
215 	struct segment *sp;
216 	struct vnode *vp;
217 	SEGUSE *segusep;
218 	daddr_t ibno;
219 	CLEANERINFO *cip;
220 	int clean, do_ckp, error, i;
221 
222 	fs = VFSTOUFS(mp)->um_lfs;
223 
224  	/*
225  	 * If we have fewer than 2 clean segments, wait until cleaner
226 	 * writes.
227  	 */
228 	do {
229 		LFS_CLEANERINFO(cip, fs, bp);
230 		clean = cip->clean;
231 		brelse(bp);
232 		if (clean <= 2) {
233 			printf ("segs clean: %d\n", clean);
234 			wakeup(&lfs_allclean_wakeup);
235 			if (error = tsleep(&fs->lfs_avail, PRIBIO + 1,
236 			    "lfs writer", 0))
237 				return (error);
238 		}
239 	} while (clean <= 2 );
240 
241 	/*
242 	 * Allocate a segment structure and enough space to hold pointers to
243 	 * the maximum possible number of buffers which can be described in a
244 	 * single summary block.
245 	 */
246 	do_ckp = flags & SEGM_CKP || fs->lfs_nactive > MAX_ACTIVE;
247 	lfs_seglock(fs, flags | (do_ckp ? SEGM_CKP : 0));
248 	sp = fs->lfs_sp;
249 
250 	lfs_writevnodes(fs, mp, sp, VN_REG);
251 
252 	/* XXX ignore ordering of dirops for now */
253 	/* XXX
254 	fs->lfs_writer = 1;
255 	if (fs->lfs_dirops && (error =
256 	    tsleep(&fs->lfs_writer, PRIBIO + 1, "lfs writer", 0))) {
257 		free(sp->bpp, M_SEGMENT);
258 		free(sp, M_SEGMENT);
259 		fs->lfs_writer = 0;
260 		return (error);
261 	}
262 
263 	lfs_writevnodes(fs, mp, sp, VN_DIROP);
264 	*/
265 
266 	/*
267 	 * If we are doing a checkpoint, mark everything since the
268 	 * last checkpoint as no longer ACTIVE.
269 	 */
270 	if (do_ckp)
271 		for (ibno = fs->lfs_cleansz + fs->lfs_segtabsz;
272 		     --ibno >= fs->lfs_cleansz; ) {
273 			if (bread(fs->lfs_ivnode, ibno, fs->lfs_bsize,
274 			    NOCRED, &bp))
275 
276 				panic("lfs: ifile read");
277 			segusep = (SEGUSE *)bp->b_data;
278 			for (i = fs->lfs_sepb; i--; segusep++)
279 				segusep->su_flags &= ~SEGUSE_ACTIVE;
280 
281 			error = VOP_BWRITE(bp);
282 		}
283 
284 	if (do_ckp || fs->lfs_doifile) {
285 redo:
286 		vp = fs->lfs_ivnode;
287 		while (vget(vp, 1));
288 		ip = VTOI(vp);
289 		if (vp->v_dirtyblkhd.lh_first != NULL)
290 			lfs_writefile(fs, sp, vp);
291 		(void)lfs_writeinode(fs, sp, ip);
292 		vput(vp);
293 		if (lfs_writeseg(fs, sp) && do_ckp)
294 			goto redo;
295 	} else
296 		(void) lfs_writeseg(fs, sp);
297 
298 	/*
299 	 * If the I/O count is non-zero, sleep until it reaches zero.  At the
300 	 * moment, the user's process hangs around so we can sleep.
301 	 */
302 	/* XXX ignore dirops for now
303 	fs->lfs_writer = 0;
304 	fs->lfs_doifile = 0;
305 	wakeup(&fs->lfs_dirops);
306 	*/
307 
308 #ifdef DOSTATS
309 	++lfs_stats.nwrites;
310 	if (sp->seg_flags & SEGM_SYNC)
311 		++lfs_stats.nsync_writes;
312 	if (sp->seg_flags & SEGM_CKP)
313 		++lfs_stats.ncheckpoints;
314 #endif
315 	lfs_segunlock(fs);
316 	return (0);
317 }
318 
319 /*
320  * Write the dirty blocks associated with a vnode.
321  */
322 void
323 lfs_writefile(fs, sp, vp)
324 	struct lfs *fs;
325 	struct segment *sp;
326 	struct vnode *vp;
327 {
328 	struct buf *bp;
329 	struct finfo *fip;
330 	IFILE *ifp;
331 
332 	if (sp->seg_bytes_left < fs->lfs_bsize ||
333 	    sp->sum_bytes_left < sizeof(struct finfo))
334 		(void) lfs_writeseg(fs, sp);
335 
336 	sp->sum_bytes_left -= sizeof(struct finfo) - sizeof(daddr_t);
337 	++((SEGSUM *)(sp->segsum))->ss_nfinfo;
338 
339 	fip = sp->fip;
340 	fip->fi_nblocks = 0;
341 	fip->fi_ino = VTOI(vp)->i_number;
342 	LFS_IENTRY(ifp, fs, fip->fi_ino, bp);
343 	fip->fi_version = ifp->if_version;
344 	brelse(bp);
345 
346 	/*
347 	 * It may not be necessary to write the meta-data blocks at this point,
348 	 * as the roll-forward recovery code should be able to reconstruct the
349 	 * list.
350 	 */
351 	lfs_gather(fs, sp, vp, lfs_match_data);
352 	lfs_gather(fs, sp, vp, lfs_match_indir);
353 	lfs_gather(fs, sp, vp, lfs_match_dindir);
354 #ifdef TRIPLE
355 	lfs_gather(fs, sp, vp, lfs_match_tindir);
356 #endif
357 
358 	fip = sp->fip;
359 	if (fip->fi_nblocks != 0) {
360 		sp->fip =
361 		    (struct finfo *)((caddr_t)fip + sizeof(struct finfo) +
362 		    sizeof(daddr_t) * (fip->fi_nblocks - 1));
363 		sp->start_lbp = &sp->fip->fi_blocks[0];
364 	} else {
365 		sp->sum_bytes_left += sizeof(struct finfo) - sizeof(daddr_t);
366 		--((SEGSUM *)(sp->segsum))->ss_nfinfo;
367 	}
368 }
369 
370 int
371 lfs_writeinode(fs, sp, ip)
372 	struct lfs *fs;
373 	struct segment *sp;
374 	struct inode *ip;
375 {
376 	struct buf *bp, *ibp;
377 	IFILE *ifp;
378 	SEGUSE *sup;
379 	daddr_t daddr;
380 	ino_t ino;
381 	int error, i, ndx;
382 	int redo_ifile = 0;
383 
384 	if (!(ip->i_flag & (IN_ACCESS | IN_CHANGE | IN_MODIFIED | IN_UPDATE)))
385 		return(0);
386 
387 	/* Allocate a new inode block if necessary. */
388 	if (sp->ibp == NULL) {
389 		/* Allocate a new segment if necessary. */
390 		if (sp->seg_bytes_left < fs->lfs_bsize ||
391 		    sp->sum_bytes_left < sizeof(daddr_t))
392 			(void) lfs_writeseg(fs, sp);
393 
394 		/* Get next inode block. */
395 		daddr = fs->lfs_offset;
396 		fs->lfs_offset += fsbtodb(fs, 1);
397 		sp->ibp = *sp->cbpp++ =
398 		    lfs_newbuf(VTOI(fs->lfs_ivnode)->i_devvp, daddr,
399 		    fs->lfs_bsize);
400 		/* Zero out inode numbers */
401 		for (i = 0; i < INOPB(fs); ++i)
402 			((struct dinode *)sp->ibp->b_data)[i].di_inumber = 0;
403 		++sp->start_bpp;
404 		fs->lfs_avail -= fsbtodb(fs, 1);
405 		/* Set remaining space counters. */
406 		sp->seg_bytes_left -= fs->lfs_bsize;
407 		sp->sum_bytes_left -= sizeof(daddr_t);
408 		ndx = LFS_SUMMARY_SIZE / sizeof(daddr_t) -
409 		    sp->ninodes / INOPB(fs) - 1;
410 		((daddr_t *)(sp->segsum))[ndx] = daddr;
411 	}
412 
413 	/* Update the inode times and copy the inode onto the inode page. */
414 	if (ip->i_flag & IN_MODIFIED)
415 		--fs->lfs_uinodes;
416 	ITIMES(ip, &time, &time);
417 	ip->i_flag &= ~(IN_ACCESS | IN_CHANGE | IN_MODIFIED | IN_UPDATE);
418 	bp = sp->ibp;
419 	((struct dinode *)bp->b_data)[sp->ninodes % INOPB(fs)] = ip->i_din;
420 	/* Increment inode count in segment summary block. */
421 	++((SEGSUM *)(sp->segsum))->ss_ninos;
422 
423 	/* If this page is full, set flag to allocate a new page. */
424 	if (++sp->ninodes % INOPB(fs) == 0)
425 		sp->ibp = NULL;
426 
427 	/*
428 	 * If updating the ifile, update the super-block.  Update the disk
429 	 * address and access times for this inode in the ifile.
430 	 */
431 	ino = ip->i_number;
432 	if (ino == LFS_IFILE_INUM) {
433 		daddr = fs->lfs_idaddr;
434 		fs->lfs_idaddr = bp->b_blkno;
435 	} else {
436 		LFS_IENTRY(ifp, fs, ino, ibp);
437 		daddr = ifp->if_daddr;
438 		ifp->if_daddr = bp->b_blkno;
439 		error = VOP_BWRITE(ibp);
440 	}
441 
442 	/*
443 	 * No need to update segment usage if there was no former inode address
444 	 * or if the last inode address is in the current partial segment.
445 	 */
446 	if (daddr != LFS_UNUSED_DADDR &&
447 	    !(daddr >= fs->lfs_lastpseg && daddr <= bp->b_blkno)) {
448 		LFS_SEGENTRY(sup, fs, datosn(fs, daddr), bp);
449 #ifdef DIAGNOSTIC
450 		if (sup->su_nbytes < sizeof(struct dinode)) {
451 			/* XXX -- Change to a panic. */
452 			printf("lfs: negative bytes (segment %d)\n",
453 			    datosn(fs, daddr));
454 			panic("negative bytes");
455 		}
456 #endif
457 		sup->su_nbytes -= sizeof(struct dinode);
458 		redo_ifile =
459 		    (ino == LFS_IFILE_INUM && !(bp->b_flags & B_GATHERED));
460 		error = VOP_BWRITE(bp);
461 	}
462 	return (redo_ifile);
463 }
464 
465 int
466 lfs_gatherblock(sp, bp, sptr)
467 	struct segment *sp;
468 	struct buf *bp;
469 	int *sptr;
470 {
471 	struct lfs *fs;
472 	int version;
473 
474 	/*
475 	 * If full, finish this segment.  We may be doing I/O, so
476 	 * release and reacquire the splbio().
477 	 */
478 #ifdef DIAGNOSTIC
479 	if (sp->vp == NULL)
480 		panic ("lfs_gatherblock: Null vp in segment");
481 #endif
482 	fs = sp->fs;
483 	if (sp->sum_bytes_left < sizeof(daddr_t) ||
484 	    sp->seg_bytes_left < fs->lfs_bsize) {
485 		if (sptr)
486 			splx(*sptr);
487 		lfs_updatemeta(sp);
488 
489 		version = sp->fip->fi_version;
490 		(void) lfs_writeseg(fs, sp);
491 
492 		sp->fip->fi_version = version;
493 		sp->fip->fi_ino = VTOI(sp->vp)->i_number;
494 		/* Add the current file to the segment summary. */
495 		++((SEGSUM *)(sp->segsum))->ss_nfinfo;
496 		sp->sum_bytes_left -=
497 		    sizeof(struct finfo) - sizeof(daddr_t);
498 
499 		if (sptr)
500 			*sptr = splbio();
501 		return(1);
502 	}
503 
504 	/* Insert into the buffer list, update the FINFO block. */
505 	bp->b_flags |= B_GATHERED;
506 	*sp->cbpp++ = bp;
507 	sp->fip->fi_blocks[sp->fip->fi_nblocks++] = bp->b_lblkno;
508 
509 	sp->sum_bytes_left -= sizeof(daddr_t);
510 	sp->seg_bytes_left -= fs->lfs_bsize;
511 	return(0);
512 }
513 
514 void
515 lfs_gather(fs, sp, vp, match)
516 	struct lfs *fs;
517 	struct segment *sp;
518 	struct vnode *vp;
519 	int (*match) __P((struct lfs *, struct buf *));
520 {
521 	struct buf *bp;
522 	int s;
523 
524 	sp->vp = vp;
525 	s = splbio();
526 loop:	for (bp = vp->v_dirtyblkhd.lh_first; bp; bp = bp->b_vnbufs.le_next) {
527 		if (bp->b_flags & B_BUSY || !match(fs, bp) ||
528 		    bp->b_flags & B_GATHERED)
529 			continue;
530 #ifdef DIAGNOSTIC
531 		if (!(bp->b_flags & B_DELWRI))
532 			panic("lfs_gather: bp not B_DELWRI");
533 		if (!(bp->b_flags & B_LOCKED))
534 			panic("lfs_gather: bp not B_LOCKED");
535 #endif
536 		if (lfs_gatherblock(sp, bp, &s))
537 			goto loop;
538 	}
539 	splx(s);
540 	lfs_updatemeta(sp);
541 	sp->vp = NULL;
542 }
543 
544 
545 /*
546  * Update the metadata that points to the blocks listed in the FINFO
547  * array.
548  */
549 void
550 lfs_updatemeta(sp)
551 	struct segment *sp;
552 {
553 	SEGUSE *sup;
554 	struct buf *bp;
555 	struct lfs *fs;
556 	struct vnode *vp;
557 	struct indir a[NIADDR + 2], *ap;
558 	struct inode *ip;
559 	daddr_t daddr, lbn, off;
560 	int db_per_fsb, error, i, nblocks, num;
561 
562 	vp = sp->vp;
563 	nblocks = &sp->fip->fi_blocks[sp->fip->fi_nblocks] - sp->start_lbp;
564 	if (vp == NULL || nblocks == 0)
565 		return;
566 
567 	/* Sort the blocks. */
568 	if (!(sp->seg_flags & SEGM_CLEAN))
569 		lfs_shellsort(sp->start_bpp, sp->start_lbp, nblocks);
570 
571 	/*
572 	 * Assign disk addresses, and update references to the logical
573 	 * block and the segment usage information.
574 	 */
575 	fs = sp->fs;
576 	db_per_fsb = fsbtodb(fs, 1);
577 	for (i = nblocks; i--; ++sp->start_bpp) {
578 		lbn = *sp->start_lbp++;
579 		(*sp->start_bpp)->b_blkno = off = fs->lfs_offset;
580 		fs->lfs_offset += db_per_fsb;
581 
582 		if (error = ufs_bmaparray(vp, lbn, &daddr, a, &num, NULL))
583 			panic("lfs_updatemeta: ufs_bmaparray %d", error);
584 		ip = VTOI(vp);
585 		switch (num) {
586 		case 0:
587 			ip->i_db[lbn] = off;
588 			break;
589 		case 1:
590 			ip->i_ib[a[0].in_off] = off;
591 			break;
592 		default:
593 			ap = &a[num - 1];
594 			if (bread(vp, ap->in_lbn, fs->lfs_bsize, NOCRED, &bp))
595 				panic("lfs_updatemeta: bread bno %d",
596 				    ap->in_lbn);
597 			/*
598 			 * Bread may create a new indirect block which needs
599 			 * to get counted for the inode.
600 			 */
601 			if (bp->b_blkno == -1 && !(bp->b_flags & B_CACHE)) {
602 printf ("Updatemeta allocating indirect block: shouldn't happen\n");
603 				ip->i_blocks += btodb(fs->lfs_bsize);
604 				fs->lfs_bfree -= btodb(fs->lfs_bsize);
605 			}
606 			((daddr_t *)bp->b_data)[ap->in_off] = off;
607 			VOP_BWRITE(bp);
608 		}
609 
610 		/* Update segment usage information. */
611 		if (daddr != UNASSIGNED &&
612 		    !(daddr >= fs->lfs_lastpseg && daddr <= off)) {
613 			LFS_SEGENTRY(sup, fs, datosn(fs, daddr), bp);
614 #ifdef DIAGNOSTIC
615 			if (sup->su_nbytes < fs->lfs_bsize) {
616 				/* XXX -- Change to a panic. */
617 				printf("lfs: negative bytes (segment %d)\n",
618 				    datosn(fs, daddr));
619 				panic ("Negative Bytes");
620 			}
621 #endif
622 			sup->su_nbytes -= fs->lfs_bsize;
623 			error = VOP_BWRITE(bp);
624 		}
625 	}
626 }
627 
628 /*
629  * Start a new segment.
630  */
631 int
632 lfs_initseg(fs)
633 	struct lfs *fs;
634 {
635 	struct segment *sp;
636 	SEGUSE *sup;
637 	SEGSUM *ssp;
638 	struct buf *bp;
639 	int repeat;
640 
641 	sp = fs->lfs_sp;
642 
643 	repeat = 0;
644 	/* Advance to the next segment. */
645 	if (!LFS_PARTIAL_FITS(fs)) {
646 		/* Wake up any cleaning procs waiting on this file system. */
647 		wakeup(&lfs_allclean_wakeup);
648 
649 		lfs_newseg(fs);
650 		repeat = 1;
651 		fs->lfs_offset = fs->lfs_curseg;
652 		sp->seg_number = datosn(fs, fs->lfs_curseg);
653 		sp->seg_bytes_left = fs->lfs_dbpseg * DEV_BSIZE;
654 
655 		/*
656 		 * If the segment contains a superblock, update the offset
657 		 * and summary address to skip over it.
658 		 */
659 		LFS_SEGENTRY(sup, fs, sp->seg_number, bp);
660 		if (sup->su_flags & SEGUSE_SUPERBLOCK) {
661 			fs->lfs_offset += LFS_SBPAD / DEV_BSIZE;
662 			sp->seg_bytes_left -= LFS_SBPAD;
663 		}
664 		brelse(bp);
665 	} else {
666 		sp->seg_number = datosn(fs, fs->lfs_curseg);
667 		sp->seg_bytes_left = (fs->lfs_dbpseg -
668 		    (fs->lfs_offset - fs->lfs_curseg)) * DEV_BSIZE;
669 	}
670 	fs->lfs_lastpseg = fs->lfs_offset;
671 
672 	sp->fs = fs;
673 	sp->ibp = NULL;
674 	sp->ninodes = 0;
675 
676 	/* Get a new buffer for SEGSUM and enter it into the buffer list. */
677 	sp->cbpp = sp->bpp;
678 	*sp->cbpp = lfs_newbuf(VTOI(fs->lfs_ivnode)->i_devvp, fs->lfs_offset,
679 	     LFS_SUMMARY_SIZE);
680 	sp->segsum = (*sp->cbpp)->b_data;
681 	bzero(sp->segsum, LFS_SUMMARY_SIZE);
682 	sp->start_bpp = ++sp->cbpp;
683 	fs->lfs_offset += LFS_SUMMARY_SIZE / DEV_BSIZE;
684 
685 	/* Set point to SEGSUM, initialize it. */
686 	ssp = sp->segsum;
687 	ssp->ss_next = fs->lfs_nextseg;
688 	ssp->ss_nfinfo = ssp->ss_ninos = 0;
689 
690 	/* Set pointer to first FINFO, initialize it. */
691 	sp->fip = (struct finfo *)((caddr_t)sp->segsum + sizeof(SEGSUM));
692 	sp->fip->fi_nblocks = 0;
693 	sp->start_lbp = &sp->fip->fi_blocks[0];
694 
695 	sp->seg_bytes_left -= LFS_SUMMARY_SIZE;
696 	sp->sum_bytes_left = LFS_SUMMARY_SIZE - sizeof(SEGSUM);
697 
698 	return(repeat);
699 }
700 
701 /*
702  * Return the next segment to write.
703  */
704 void
705 lfs_newseg(fs)
706 	struct lfs *fs;
707 {
708 	CLEANERINFO *cip;
709 	SEGUSE *sup;
710 	struct buf *bp;
711 	int curseg, isdirty, sn;
712 
713         LFS_SEGENTRY(sup, fs, datosn(fs, fs->lfs_nextseg), bp);
714         sup->su_flags |= SEGUSE_DIRTY | SEGUSE_ACTIVE;
715 	sup->su_nbytes = 0;
716 	sup->su_nsums = 0;
717 	sup->su_ninos = 0;
718         (void) VOP_BWRITE(bp);
719 
720 	LFS_CLEANERINFO(cip, fs, bp);
721 	--cip->clean;
722 	++cip->dirty;
723 	(void) VOP_BWRITE(bp);
724 
725 	fs->lfs_lastseg = fs->lfs_curseg;
726 	fs->lfs_curseg = fs->lfs_nextseg;
727 	for (sn = curseg = datosn(fs, fs->lfs_curseg);;) {
728 		sn = (sn + 1) % fs->lfs_nseg;
729 		if (sn == curseg)
730 			panic("lfs_nextseg: no clean segments");
731 		LFS_SEGENTRY(sup, fs, sn, bp);
732 		isdirty = sup->su_flags & SEGUSE_DIRTY;
733 		brelse(bp);
734 		if (!isdirty)
735 			break;
736 	}
737 
738 	++fs->lfs_nactive;
739 	fs->lfs_nextseg = sntoda(fs, sn);
740 #ifdef DOSTATS
741 	++lfs_stats.segsused;
742 #endif
743 }
744 
745 int
746 lfs_writeseg(fs, sp)
747 	struct lfs *fs;
748 	struct segment *sp;
749 {
750 	extern int locked_queue_count;
751 	struct buf **bpp, *bp, *cbp;
752 	SEGUSE *sup;
753 	SEGSUM *ssp;
754 	dev_t i_dev;
755 	size_t size;
756 	u_long *datap, *dp;
757 	int ch_per_blk, do_again, i, nblocks, num, s;
758 	int (*strategy)__P((struct vop_strategy_args *));
759 	struct vop_strategy_args vop_strategy_a;
760 	u_short ninos;
761 	char *p;
762 
763 	/*
764 	 * If there are no buffers other than the segment summary to write
765 	 * and it is not a checkpoint, don't do anything.  On a checkpoint,
766 	 * even if there aren't any buffers, you need to write the superblock.
767 	 */
768 	if ((nblocks = sp->cbpp - sp->bpp) == 1)
769 		return (0);
770 
771 	ssp = (SEGSUM *)sp->segsum;
772 
773 	/* Update the segment usage information. */
774 	LFS_SEGENTRY(sup, fs, sp->seg_number, bp);
775 	ninos = (ssp->ss_ninos + INOPB(fs) - 1) / INOPB(fs);
776 	sup->su_nbytes += nblocks - 1 - ninos << fs->lfs_bshift;
777 	sup->su_nbytes += ssp->ss_ninos * sizeof(struct dinode);
778 	sup->su_nbytes += LFS_SUMMARY_SIZE;
779 	sup->su_lastmod = time.tv_sec;
780 	sup->su_ninos += ninos;
781 	++sup->su_nsums;
782 	do_again = !(bp->b_flags & B_GATHERED);
783 	(void)VOP_BWRITE(bp);
784 	/*
785 	 * Compute checksum across data and then across summary; the first
786 	 * block (the summary block) is skipped.  Set the create time here
787 	 * so that it's guaranteed to be later than the inode mod times.
788 	 *
789 	 * XXX
790 	 * Fix this to do it inline, instead of malloc/copy.
791 	 */
792 	datap = dp = malloc(nblocks * sizeof(u_long), M_SEGMENT, M_WAITOK);
793 	for (bpp = sp->bpp, i = nblocks - 1; i--;) {
794 		if ((*++bpp)->b_flags & B_INVAL) {
795 			if (copyin((*bpp)->b_saveaddr, dp++, sizeof(u_long)))
796 				panic("lfs_writeseg: copyin failed");
797 		} else
798 			*dp++ = ((u_long *)(*bpp)->b_data)[0];
799 	}
800 	ssp->ss_create = time.tv_sec;
801 	ssp->ss_datasum = cksum(datap, (nblocks - 1) * sizeof(u_long));
802 	ssp->ss_sumsum =
803 	    cksum(&ssp->ss_datasum, LFS_SUMMARY_SIZE - sizeof(ssp->ss_sumsum));
804 	free(datap, M_SEGMENT);
805 #ifdef DIAGNOSTIC
806 	if (fs->lfs_bfree < fsbtodb(fs, ninos) + LFS_SUMMARY_SIZE / DEV_BSIZE)
807 		panic("lfs_writeseg: No diskspace for summary");
808 #endif
809 	fs->lfs_bfree -= (fsbtodb(fs, ninos) + LFS_SUMMARY_SIZE / DEV_BSIZE);
810 
811 	i_dev = VTOI(fs->lfs_ivnode)->i_dev;
812 	strategy = VTOI(fs->lfs_ivnode)->i_devvp->v_op[VOFFSET(vop_strategy)];
813 
814 	/*
815 	 * When we simply write the blocks we lose a rotation for every block
816 	 * written.  To avoid this problem, we allocate memory in chunks, copy
817 	 * the buffers into the chunk and write the chunk.  MAXPHYS is the
818 	 * largest size I/O devices can handle.
819 	 * When the data is copied to the chunk, turn off the the B_LOCKED bit
820 	 * and brelse the buffer (which will move them to the LRU list).  Add
821 	 * the B_CALL flag to the buffer header so we can count I/O's for the
822 	 * checkpoints and so we can release the allocated memory.
823 	 *
824 	 * XXX
825 	 * This should be removed if the new virtual memory system allows us to
826 	 * easily make the buffers contiguous in kernel memory and if that's
827 	 * fast enough.
828 	 */
829 	ch_per_blk = MAXPHYS / fs->lfs_bsize;
830 	for (bpp = sp->bpp, i = nblocks; i;) {
831 		num = ch_per_blk;
832 		if (num > i)
833 			num = i;
834 		i -= num;
835 		size = num * fs->lfs_bsize;
836 
837 		cbp = lfs_newbuf(VTOI(fs->lfs_ivnode)->i_devvp,
838 		    (*bpp)->b_blkno, size);
839 		cbp->b_dev = i_dev;
840 		cbp->b_flags |= B_ASYNC | B_BUSY;
841 
842 		s = splbio();
843 		++fs->lfs_iocount;
844 		for (p = cbp->b_data; num--;) {
845 			bp = *bpp++;
846 			/*
847 			 * Fake buffers from the cleaner are marked as B_INVAL.
848 			 * We need to copy the data from user space rather than
849 			 * from the buffer indicated.
850 			 * XXX == what do I do on an error?
851 			 */
852 			if (bp->b_flags & B_INVAL) {
853 				if (copyin(bp->b_saveaddr, p, bp->b_bcount))
854 					panic("lfs_writeseg: copyin failed");
855 			} else
856 				bcopy(bp->b_data, p, bp->b_bcount);
857 			p += bp->b_bcount;
858 			if (bp->b_flags & B_LOCKED)
859 				--locked_queue_count;
860 			bp->b_flags &= ~(B_ERROR | B_READ | B_DELWRI |
861 			     B_LOCKED | B_GATHERED);
862 			if (bp->b_flags & B_CALL) {
863 				/* if B_CALL, it was created with newbuf */
864 				brelvp(bp);
865 				if (!(bp->b_flags & B_INVAL))
866 					free(bp->b_data, M_SEGMENT);
867 				free(bp, M_SEGMENT);
868 			} else {
869 				bremfree(bp);
870 				bp->b_flags |= B_DONE;
871 				reassignbuf(bp, bp->b_vp);
872 				brelse(bp);
873 			}
874 		}
875 		++cbp->b_vp->v_numoutput;
876 		splx(s);
877 		cbp->b_bcount = p - (char *)cbp->b_data;
878 		/*
879 		 * XXXX This is a gross and disgusting hack.  Since these
880 		 * buffers are physically addressed, they hang off the
881 		 * device vnode (devvp).  As a result, they have no way
882 		 * of getting to the LFS superblock or lfs structure to
883 		 * keep track of the number of I/O's pending.  So, I am
884 		 * going to stuff the fs into the saveaddr field of
885 		 * the buffer (yuk).
886 		 */
887 		cbp->b_saveaddr = (caddr_t)fs;
888 		vop_strategy_a.a_desc = VDESC(vop_strategy);
889 		vop_strategy_a.a_bp = cbp;
890 		(strategy)(&vop_strategy_a);
891 	}
892 	/*
893 	 * XXX
894 	 * Vinvalbuf can move locked buffers off the locked queue
895 	 * and we have no way of knowing about this.  So, after
896 	 * doing a big write, we recalculate how many bufers are
897 	 * really still left on the locked queue.
898 	 */
899 	locked_queue_count = count_lock_queue();
900 	wakeup(&locked_queue_count);
901 #ifdef DOSTATS
902 	++lfs_stats.psegwrites;
903 	lfs_stats.blocktot += nblocks - 1;
904 	if (fs->lfs_sp->seg_flags & SEGM_SYNC)
905 		++lfs_stats.psyncwrites;
906 	if (fs->lfs_sp->seg_flags & SEGM_CLEAN) {
907 		++lfs_stats.pcleanwrites;
908 		lfs_stats.cleanblocks += nblocks - 1;
909 	}
910 #endif
911 	return (lfs_initseg(fs) || do_again);
912 }
913 
914 void
915 lfs_writesuper(fs)
916 	struct lfs *fs;
917 {
918 	struct buf *bp;
919 	dev_t i_dev;
920 	int (*strategy) __P((struct vop_strategy_args *));
921 	int s;
922 	struct vop_strategy_args vop_strategy_a;
923 
924 	i_dev = VTOI(fs->lfs_ivnode)->i_dev;
925 	strategy = VTOI(fs->lfs_ivnode)->i_devvp->v_op[VOFFSET(vop_strategy)];
926 
927 	/* Checksum the superblock and copy it into a buffer. */
928 	fs->lfs_cksum = cksum(fs, sizeof(struct lfs) - sizeof(fs->lfs_cksum));
929 	bp = lfs_newbuf(VTOI(fs->lfs_ivnode)->i_devvp, fs->lfs_sboffs[0],
930 	    LFS_SBPAD);
931 	*(struct lfs *)bp->b_data = *fs;
932 
933 	/* XXX Toggle between first two superblocks; for now just write first */
934 	bp->b_dev = i_dev;
935 	bp->b_flags |= B_BUSY | B_CALL | B_ASYNC;
936 	bp->b_flags &= ~(B_DONE | B_ERROR | B_READ | B_DELWRI);
937 	bp->b_iodone = lfs_supercallback;
938 	vop_strategy_a.a_desc = VDESC(vop_strategy);
939 	vop_strategy_a.a_bp = bp;
940 	s = splbio();
941 	++bp->b_vp->v_numoutput;
942 	splx(s);
943 	(strategy)(&vop_strategy_a);
944 }
945 
946 /*
947  * Logical block number match routines used when traversing the dirty block
948  * chain.
949  */
950 int
951 lfs_match_data(fs, bp)
952 	struct lfs *fs;
953 	struct buf *bp;
954 {
955 	return (bp->b_lblkno >= 0);
956 }
957 
958 int
959 lfs_match_indir(fs, bp)
960 	struct lfs *fs;
961 	struct buf *bp;
962 {
963 	int lbn;
964 
965 	lbn = bp->b_lblkno;
966 	return (lbn < 0 && (-lbn - NDADDR) % NINDIR(fs) == 0);
967 }
968 
969 int
970 lfs_match_dindir(fs, bp)
971 	struct lfs *fs;
972 	struct buf *bp;
973 {
974 	int lbn;
975 
976 	lbn = bp->b_lblkno;
977 	return (lbn < 0 && (-lbn - NDADDR) % NINDIR(fs) == 1);
978 }
979 
980 int
981 lfs_match_tindir(fs, bp)
982 	struct lfs *fs;
983 	struct buf *bp;
984 {
985 	int lbn;
986 
987 	lbn = bp->b_lblkno;
988 	return (lbn < 0 && (-lbn - NDADDR) % NINDIR(fs) == 2);
989 }
990 
991 /*
992  * Allocate a new buffer header.
993  */
994 struct buf *
995 lfs_newbuf(vp, daddr, size)
996 	struct vnode *vp;
997 	daddr_t daddr;
998 	size_t size;
999 {
1000 	struct buf *bp;
1001 	size_t nbytes;
1002 
1003 	nbytes = roundup(size, DEV_BSIZE);
1004 	bp = malloc(sizeof(struct buf), M_SEGMENT, M_WAITOK);
1005 	bzero(bp, sizeof(struct buf));
1006 	if (nbytes)
1007 		bp->b_data = malloc(nbytes, M_SEGMENT, M_WAITOK);
1008 	bgetvp(vp, bp);
1009 	bp->b_bufsize = size;
1010 	bp->b_bcount = size;
1011 	bp->b_lblkno = daddr;
1012 	bp->b_blkno = daddr;
1013 	bp->b_error = 0;
1014 	bp->b_resid = 0;
1015 	bp->b_iodone = lfs_callback;
1016 	bp->b_flags |= B_BUSY | B_CALL | B_NOCACHE;
1017 	return (bp);
1018 }
1019 
1020 void
1021 lfs_callback(bp)
1022 	struct buf *bp;
1023 {
1024 	struct lfs *fs;
1025 
1026 	fs = (struct lfs *)bp->b_saveaddr;
1027 #ifdef DIAGNOSTIC
1028 	if (fs->lfs_iocount == 0)
1029 		panic("lfs_callback: zero iocount\n");
1030 #endif
1031 	if (--fs->lfs_iocount == 0)
1032 		wakeup(&fs->lfs_iocount);
1033 
1034 	brelvp(bp);
1035 	free(bp->b_data, M_SEGMENT);
1036 	free(bp, M_SEGMENT);
1037 }
1038 
1039 void
1040 lfs_supercallback(bp)
1041 	struct buf *bp;
1042 {
1043 	brelvp(bp);
1044 	free(bp->b_data, M_SEGMENT);
1045 	free(bp, M_SEGMENT);
1046 }
1047 
1048 /*
1049  * Shellsort (diminishing increment sort) from Data Structures and
1050  * Algorithms, Aho, Hopcraft and Ullman, 1983 Edition, page 290;
1051  * see also Knuth Vol. 3, page 84.  The increments are selected from
1052  * formula (8), page 95.  Roughly O(N^3/2).
1053  */
1054 /*
1055  * This is our own private copy of shellsort because we want to sort
1056  * two parallel arrays (the array of buffer pointers and the array of
1057  * logical block numbers) simultaneously.  Note that we cast the array
1058  * of logical block numbers to a unsigned in this routine so that the
1059  * negative block numbers (meta data blocks) sort AFTER the data blocks.
1060  */
1061 void
1062 lfs_shellsort(bp_array, lb_array, nmemb)
1063 	struct buf **bp_array;
1064 	daddr_t *lb_array;
1065 	register int nmemb;
1066 {
1067 	static int __rsshell_increments[] = { 4, 1, 0 };
1068 	register int incr, *incrp, t1, t2;
1069 	struct buf *bp_temp;
1070 	u_long lb_temp;
1071 
1072 	for (incrp = __rsshell_increments; incr = *incrp++;)
1073 		for (t1 = incr; t1 < nmemb; ++t1)
1074 			for (t2 = t1 - incr; t2 >= 0;)
1075 				if (lb_array[t2] > lb_array[t2 + incr]) {
1076 					lb_temp = lb_array[t2];
1077 					lb_array[t2] = lb_array[t2 + incr];
1078 					lb_array[t2 + incr] = lb_temp;
1079 					bp_temp = bp_array[t2];
1080 					bp_array[t2] = bp_array[t2 + incr];
1081 					bp_array[t2 + incr] = bp_temp;
1082 					t2 -= incr;
1083 				} else
1084 					break;
1085 }
1086 
1087 /*
1088  * Check VXLOCK.  Return 1 if the vnode is locked.  Otherwise, vget it.
1089  */
1090 lfs_vref(vp)
1091 	register struct vnode *vp;
1092 {
1093 
1094 	if (vp->v_flag & VXLOCK)
1095 		return(1);
1096 	return (vget(vp, 0));
1097 }
1098 
1099 void
1100 lfs_vunref(vp)
1101 	register struct vnode *vp;
1102 {
1103 	extern int lfs_no_inactive;
1104 
1105 	/*
1106 	 * This is vrele except that we do not want to VOP_INACTIVE
1107 	 * this vnode. Rather than inline vrele here, we use a global
1108 	 * flag to tell lfs_inactive not to run. Yes, its gross.
1109 	 */
1110 	lfs_no_inactive = 1;
1111 	vrele(vp);
1112 	lfs_no_inactive = 0;
1113 }
1114