Home | History | Annotate | Line # | Download | only in quotacheck
quotacheck.c revision 1.42
      1 /*	$NetBSD: quotacheck.c,v 1.42 2011/03/06 23:07:23 christos Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1980, 1990, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Robert Elz at The University of Melbourne.
      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  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 #ifndef lint
     37 __COPYRIGHT("@(#) Copyright (c) 1980, 1990, 1993\
     38  The Regents of the University of California.  All rights reserved.");
     39 #endif /* not lint */
     40 
     41 #ifndef lint
     42 #if 0
     43 static char sccsid[] = "@(#)quotacheck.c	8.6 (Berkeley) 4/28/95";
     44 #else
     45 __RCSID("$NetBSD: quotacheck.c,v 1.42 2011/03/06 23:07:23 christos Exp $");
     46 #endif
     47 #endif /* not lint */
     48 
     49 /*
     50  * Fix up / report on disk quotas & usage
     51  */
     52 #include <sys/param.h>
     53 #include <sys/stat.h>
     54 #include <sys/queue.h>
     55 #include <sys/statvfs.h>
     56 
     57 #include <ufs/ufs/dinode.h>
     58 #include <ufs/ufs/quota1.h>
     59 #include <ufs/ufs/ufs_bswap.h>
     60 #include <ufs/ffs/fs.h>
     61 #include <ufs/ffs/ffs_extern.h>
     62 
     63 #include <err.h>
     64 #include <fcntl.h>
     65 #include <fstab.h>
     66 #include <pwd.h>
     67 #include <grp.h>
     68 #include <errno.h>
     69 #include <unistd.h>
     70 #include <stdio.h>
     71 #include <stdlib.h>
     72 #include <string.h>
     73 
     74 #include "fsutil.h"
     75 #include "quotautil.h"
     76 
     77 #ifndef FS_UFS1_MAGIC
     78 # define FS_UFS1_MAGIC		FS_MAGIC /* 0x011954 */
     79 # define FS_UFS1_MAGIC_SWAPPED	0x54190100 /* bswap32(0x011954) */
     80 # define DINODE1_SIZE		sizeof(struct dinode)
     81 # define DINODE2_SIZE		0
     82 #else
     83 # define HAVE_UFSv2	1
     84 #endif
     85 
     86 #ifndef SBLOCKSIZE
     87 # define SBLOCKSIZE	SBSIZE
     88 #endif
     89 #ifndef SBLOCKSEARCH
     90 # define SBLOCKSEARCH	{ SBSIZE, -1 }
     91 #endif
     92 
     93 static const char *quotagroup = QUOTAGROUP;
     94 
     95 static union {
     96 	struct	fs	sblk;
     97 	char	dummy[MAXBSIZE];
     98 } un;
     99 #define	sblock	un.sblk
    100 static long dev_bsize;
    101 static long maxino;
    102 
    103 struct quotaname {
    104 	long	flags;
    105 	char	grpqfname[MAXPATHLEN + 1];
    106 	char	usrqfname[MAXPATHLEN + 1];
    107 };
    108 #define	HASUSR	1
    109 #define	HASGRP	2
    110 
    111 struct fileusage {
    112 	struct	fileusage *fu_next;
    113 	u_long	fu_curinodes;
    114 	u_long	fu_curblocks;
    115 	uint32_t fu_id;		/* uid_t, gid_t */
    116 	char	fu_name[1];
    117 	/* actually bigger */
    118 };
    119 #define FUHASH 1024	/* must be power of two */
    120 static struct fileusage *fuhead[MAXQUOTAS][FUHASH];
    121 
    122 
    123 union comb_dinode {
    124 #ifdef HAVE_UFSv2
    125 	struct ufs1_dinode dp1;
    126 	struct ufs2_dinode dp2;
    127 #else
    128 	struct dinode dp1;
    129 #endif
    130 };
    131 #ifdef HAVE_UFSv2
    132 #define DIP(dp, field) \
    133 	(is_ufs2 ? (dp)->dp2.di_##field : (dp)->dp1.di_##field)
    134 #else
    135 #define DIP(dp, field) (dp)->dp1.di_##field
    136 #endif
    137 
    138 
    139 static int	aflag;		/* all file systems */
    140 static int	gflag;		/* check group quotas */
    141 static int	uflag;		/* check user quotas */
    142 static int	vflag;		/* verbose */
    143 static int	qflag;		/* quick but untidy mode */
    144 static int	fi;		/* open disk file descriptor */
    145 static uint32_t highid[MAXQUOTAS];/* highest addid()'ed identifier per type */
    146 static int needswap;	/* FS is in swapped order */
    147 static int got_siginfo = 0; /* got a siginfo signal */
    148 static int is_ufs2;
    149 
    150 
    151 static void usage(void) __attribute__((__noreturn__));
    152 static void *needchk(struct fstab *);
    153 static int chkquota(const char *, const char *, const char *, void *, pid_t *);
    154 static int update(const char *, const char *, int);
    155 static uint32_t skipforward(uint32_t, uint32_t, FILE *);
    156 static int oneof(const char *, char *[], int);
    157 static int getquotagid(void);
    158 static struct fileusage *lookup(uint32_t, int);
    159 static struct fileusage *addid(uint32_t, int, const char *);
    160 static uint32_t subsequent(uint32_t, int) ;
    161 static union comb_dinode *getnextinode(ino_t);
    162 static void setinodebuf(ino_t);
    163 static void freeinodebuf(void);
    164 static void bread(daddr_t, char *, long);
    165 static void infohandler(int sig);
    166 static void swap_dinode1(union comb_dinode *, int);
    167 #ifdef HAVE_UFSv2
    168 static void swap_dinode2(union comb_dinode *, int);
    169 #endif
    170 
    171 int
    172 main(int argc, char *argv[])
    173 {
    174 	struct fstab *fs;
    175 	struct passwd *pw;
    176 	struct group *gr;
    177 	struct quotaname *auxdata;
    178 	int i, argnum, maxrun, errs;
    179 	long done = 0;
    180 	int flags = CHECK_PREEN;
    181 	const char *name;
    182 	int ch;
    183 
    184 	errs = maxrun = 0;
    185 	while ((ch = getopt(argc, argv, "aguvqdl:")) != -1) {
    186 		switch(ch) {
    187 		case 'a':
    188 			aflag++;
    189 			break;
    190 		case 'd':
    191 			flags |= CHECK_DEBUG;
    192 			break;
    193 		case 'g':
    194 			gflag++;
    195 			break;
    196 		case 'u':
    197 			uflag++;
    198 			break;
    199 		case 'q':
    200 			qflag++;
    201 			break;
    202 		case 'v':
    203 			vflag++;
    204 			break;
    205 		case 'l':
    206 			maxrun = atoi(optarg);
    207 			break;
    208 		default:
    209 			usage();
    210 		}
    211 	}
    212 	argc -= optind;
    213 	argv += optind;
    214 	if ((argc == 0 && !aflag) || (argc > 0 && aflag) || (!aflag && maxrun))
    215 		usage();
    216 	if (!gflag && !uflag) {
    217 		gflag++;
    218 		uflag++;
    219 	}
    220 
    221 	/* If -a, we do not want to pay the cost of processing every
    222 	 * group and password entry if there are no filesystems with quotas
    223 	 */
    224 	if (aflag) {
    225 		i = 0;
    226 		while ((fs = getfsent()) != NULL) {
    227 			if (needchk(fs))
    228 				i=1;
    229 		}
    230 		endfsent();
    231 		if (!i)	/* No filesystems with quotas */
    232 			exit(0);
    233 	}
    234 
    235 	if (gflag) {
    236 		setgrent();
    237 		while ((gr = getgrent()) != 0)
    238 			(void) addid((uint32_t)gr->gr_gid, GRPQUOTA, gr->gr_name);
    239 		endgrent();
    240 	}
    241 	if (uflag) {
    242 		setpwent();
    243 		while ((pw = getpwent()) != 0)
    244 			(void) addid((uint32_t)pw->pw_uid, USRQUOTA, pw->pw_name);
    245 		endpwent();
    246 	}
    247 	if (aflag)
    248 		exit(checkfstab(flags, maxrun, needchk, chkquota));
    249 	if (setfsent() == 0)
    250 		err(1, "%s: can't open", FSTAB);
    251 	while ((fs = getfsent()) != NULL) {
    252 		if (((argnum = oneof(fs->fs_file, argv, argc)) >= 0 ||
    253 		    (argnum = oneof(fs->fs_spec, argv, argc)) >= 0) &&
    254 		    (auxdata = needchk(fs)) &&
    255 		    (name = blockcheck(fs->fs_spec))) {
    256 			done |= 1 << argnum;
    257 			errs += chkquota(fs->fs_type, name, fs->fs_file,
    258 			    auxdata, NULL);
    259 		}
    260 	}
    261 	endfsent();
    262 	for (i = 0; i < argc; i++)
    263 		if ((done & (1 << i)) == 0)
    264 			fprintf(stderr, "%s not found in %s\n",
    265 				argv[i], FSTAB);
    266 	exit(errs);
    267 }
    268 
    269 static void
    270 usage()
    271 {
    272 
    273 	(void)fprintf(stderr,
    274 	    "usage:\t%s -a [-gquv] [-l maxparallel]\n\t%s [-gquv] filesys ...\n", getprogname(),
    275 	    getprogname());
    276 	exit(1);
    277 }
    278 
    279 static void *
    280 needchk(fs)
    281 	struct fstab *fs;
    282 {
    283 	struct quotaname *qnp;
    284 	char qfnp[MAXPATHLEN];
    285 
    286 	if (strcmp(fs->fs_vfstype, "ffs") ||
    287 	    strcmp(fs->fs_type, FSTAB_RW))
    288 		return (NULL);
    289 	if ((qnp = malloc(sizeof(*qnp))) == NULL)
    290 		err(1, "%s", strerror(errno));
    291 	qnp->flags = 0;
    292 	if (gflag && hasquota(qfnp, sizeof(qfnp), fs, GRPQUOTA)) {
    293 		strlcpy(qnp->grpqfname, qfnp, sizeof(qnp->grpqfname));
    294 		qnp->flags |= HASGRP;
    295 	}
    296 	if (uflag && hasquota(qfnp, sizeof(qfnp), fs, USRQUOTA)) {
    297 		strlcpy(qnp->usrqfname, qfnp, sizeof(qnp->usrqfname));
    298 		qnp->flags |= HASUSR;
    299 	}
    300 	if (qnp->flags)
    301 		return (qnp);
    302 	free(qnp);
    303 	return (NULL);
    304 }
    305 
    306 off_t sblock_try[] = SBLOCKSEARCH;
    307 
    308 /*
    309  * Scan the specified filesystem to check quota(s) present on it.
    310  */
    311 static int
    312 chkquota(type, fsname, mntpt, v, pid)
    313 	const char *type, *fsname, *mntpt;
    314 	void *v;
    315 	pid_t *pid;
    316 {
    317 	struct quotaname *qnp = v;
    318 	struct fileusage *fup;
    319 	union comb_dinode *dp;
    320 	int cg, i, mode, errs = 0, inosused;
    321 	ino_t ino;
    322 	struct cg *cgp;
    323 	char msgbuf[4096];
    324 
    325 	if (pid != NULL) {
    326 		fflush(stdout);
    327 		switch ((*pid = fork())) {
    328 		default:
    329 			return 0;
    330 		case 0:
    331 			break;
    332 		case -1:
    333 			err(1, "Cannot fork");
    334 		}
    335 		setvbuf(stdout, msgbuf, _IOFBF, sizeof msgbuf);
    336 	}
    337 
    338 	if ((fi = open(fsname, O_RDONLY, 0)) < 0) {
    339 		warn("Cannot open %s", fsname);
    340 		if (pid != NULL)
    341 			exit(1);
    342 		return 1;
    343 	}
    344 	if (vflag) {
    345 		(void)printf("*** Checking ");
    346 		if (qnp->flags & HASUSR)
    347 			(void)printf("%s%s", qfextension[USRQUOTA],
    348 			    (qnp->flags & HASGRP) ? " and " : "");
    349 		if (qnp->flags & HASGRP)
    350 			(void)printf("%s", qfextension[GRPQUOTA]);
    351 		(void)printf(" quotas for %s (%s)\n", fsname, mntpt);
    352 		fflush(stdout);
    353 	}
    354 	signal(SIGINFO, infohandler);
    355 	sync();
    356 	dev_bsize = 1;
    357 
    358 	for (i = 0; ; i++) {
    359 		if (sblock_try[i] == -1) {
    360 			warnx("%s: superblock not found", fsname);
    361 			if (pid != NULL)
    362 				exit(1);
    363 			return 1;
    364 		}
    365 		bread(sblock_try[i], (char *)&sblock, SBLOCKSIZE);
    366 		switch (sblock.fs_magic) {
    367 #ifdef HAVE_UFSv2
    368 		case FS_UFS2_MAGIC:
    369 			is_ufs2 = 1;
    370 			/*FALLTHROUGH*/
    371 #endif
    372 		case FS_UFS1_MAGIC:
    373 			break;
    374 #ifdef HAVE_UFSv2
    375 		case FS_UFS2_MAGIC_SWAPPED:
    376 			is_ufs2 = 1;
    377 			/*FALLTHROUGH*/
    378 #endif
    379 		case FS_UFS1_MAGIC_SWAPPED:
    380 			needswap = 1;
    381 			ffs_sb_swap(&sblock, &sblock);
    382 			break;
    383 		default:
    384 			continue;
    385 		}
    386 
    387 #ifdef HAVE_UFSv2
    388 		if (is_ufs2 || sblock.fs_old_flags & FS_FLAGS_UPDATED) {
    389 			if (sblock.fs_sblockloc != sblock_try[i])
    390 				continue;
    391 		} else {
    392 			if (sblock_try[i] == SBLOCK_UFS2)
    393 				continue;
    394 		}
    395 #endif
    396 		break;
    397 	}
    398 
    399 	cgp = malloc(sblock.fs_cgsize);
    400 	if (cgp == NULL) {
    401 		warn("%s: can't allocate %d bytes of cg space", fsname,
    402 		    sblock.fs_cgsize);
    403 		if (pid != NULL)
    404 			exit(1);
    405 		return 1;
    406 	}
    407 
    408 	dev_bsize = sblock.fs_fsize / fsbtodb(&sblock, 1);
    409 	maxino = sblock.fs_ncg * sblock.fs_ipg;
    410 	for (cg = 0; cg < sblock.fs_ncg; cg++) {
    411 		ino = cg * sblock.fs_ipg;
    412 		setinodebuf(ino);
    413 #ifdef HAVE_UFSv2
    414 		if (sblock.fs_magic == FS_UFS2_MAGIC) {
    415 			bread(fsbtodb(&sblock, cgtod(&sblock, cg)), (char *)cgp,
    416 			    sblock.fs_cgsize);
    417 			if (needswap)
    418 				ffs_cg_swap(cgp, cgp, &sblock);
    419 			inosused = cgp->cg_initediblk;
    420 		} else
    421 #endif
    422 			inosused = sblock.fs_ipg;
    423 		for (i = 0; i < inosused; i++, ino++) {
    424 			if (got_siginfo) {
    425 				fprintf(stderr,
    426 				    "%s: cyl group %d of %d (%d%%)\n",
    427 				    fsname, cg, sblock.fs_ncg,
    428 				    cg * 100 / sblock.fs_ncg);
    429 				got_siginfo = 0;
    430 			}
    431 			if (ino < ROOTINO)
    432 				continue;
    433 			if ((dp = getnextinode(ino)) == NULL)
    434 				continue;
    435 			if ((mode = DIP(dp, mode) & IFMT) == 0)
    436 				continue;
    437 			if (qnp->flags & HASGRP) {
    438 				fup = addid(DIP(dp, gid), GRPQUOTA,
    439 				    (char *)0);
    440 				fup->fu_curinodes++;
    441 				if (mode == IFREG || mode == IFDIR ||
    442 				    mode == IFLNK)
    443 					fup->fu_curblocks += DIP(dp, blocks);
    444 			}
    445 			if (qnp->flags & HASUSR) {
    446 				fup = addid(DIP(dp, uid), USRQUOTA,
    447 				    (char *)0);
    448 				fup->fu_curinodes++;
    449 				if (mode == IFREG || mode == IFDIR ||
    450 				    mode == IFLNK)
    451 					fup->fu_curblocks += DIP(dp, blocks);
    452 			}
    453 		}
    454 	}
    455 	freeinodebuf();
    456 	free(cgp);
    457 	if (qnp->flags & HASUSR)
    458 		errs += update(mntpt, qnp->usrqfname, USRQUOTA);
    459 	if (qnp->flags & HASGRP)
    460 		errs += update(mntpt, qnp->grpqfname, GRPQUOTA);
    461 	close(fi);
    462 	if (pid != NULL)
    463 		exit(errs);
    464 	return errs;
    465 }
    466 
    467 /*
    468  * Update a specified quota file.
    469  */
    470 static int
    471 update(fsname, quotafile, type)
    472 	const char *fsname, *quotafile;
    473 	int type;
    474 {
    475 	struct fileusage *fup;
    476 	FILE *qfi, *qfo;
    477 	uint32_t id, lastid, nextid;
    478 	int need_seek;
    479 	struct dqblk dqbuf;
    480 	static struct dqblk zerodqbuf;
    481 	static struct fileusage zerofileusage;
    482 	struct statvfs *fst;
    483 	int nfst, i;
    484 
    485 	nfst = getmntinfo(&fst, MNT_WAIT);
    486 	if (nfst == 0)
    487 		errx(1, "no filesystems mounted!");
    488 
    489 	for (i = 0; i < nfst; i++) {
    490 		if (strncmp(fst[i].f_fstypename, "ffs",
    491 		    sizeof(fst[i].f_fstypename)) == 0 &&
    492 		    strncmp(fst[i].f_mntonname, fsname,
    493 		    sizeof(fst[i].f_mntonname)) == 0 &&
    494 		    (fst[i].f_flag & ST_QUOTA) != 0) {
    495 			warnx("filesystem %s has quotas already turned on",
    496 			    fsname);
    497 		}
    498 	}
    499 
    500 	if ((qfo = fopen(quotafile, "r+")) == NULL) {
    501 		if (errno == ENOENT)
    502 			qfo = fopen(quotafile, "w+");
    503 		if (qfo) {
    504 			(void) fprintf(stderr,
    505 			    "quotacheck: creating quota file %s\n", quotafile);
    506 #define	MODE	(S_IRUSR|S_IWUSR|S_IRGRP)
    507 			(void) fchown(fileno(qfo), getuid(), getquotagid());
    508 			(void) fchmod(fileno(qfo), MODE);
    509 		} else {
    510 			(void) fprintf(stderr,
    511 			    "quotacheck: %s: %s\n", quotafile, strerror(errno));
    512 			return (1);
    513 		}
    514 	}
    515 	if ((qfi = fopen(quotafile, "r")) == NULL) {
    516 		(void) fprintf(stderr,
    517 		    "quotacheck: %s: %s\n", quotafile, strerror(errno));
    518 		(void) fclose(qfo);
    519 		return (1);
    520 	}
    521 	need_seek = 1;
    522 	for (lastid = highid[type], id = 0; id <= lastid; id = nextid) {
    523 		if (fread((char *)&dqbuf, sizeof(struct dqblk), 1, qfi) == 0)
    524 			dqbuf = zerodqbuf;
    525 		if ((fup = lookup(id, type)) == 0)
    526 			fup = &zerofileusage;
    527 
    528 		nextid = subsequent(id, type);
    529 		if (nextid > 0 && nextid != id + 1) /* watch out for id == UINT32_MAX */
    530 			nextid = skipforward(id, nextid, qfi);
    531 
    532 		if (got_siginfo) {
    533 			/* XXX this could try to show percentage through the ID list */
    534 			fprintf(stderr,
    535 			    "%s: updating %s quotas for id=%" PRIu32 " (%s)\n", fsname,
    536 			    qfextension[type < MAXQUOTAS ? type : MAXQUOTAS],
    537 			    id, fup->fu_name);
    538 			got_siginfo = 0;
    539 		}
    540 		if (dqbuf.dqb_curinodes == fup->fu_curinodes &&
    541 		    dqbuf.dqb_curblocks == fup->fu_curblocks) {
    542 			fup->fu_curinodes = 0;	/* reset usage  */
    543 			fup->fu_curblocks = 0;	/* for next filesystem */
    544 
    545 			need_seek = 1;
    546 			if (id == UINT32_MAX || nextid == 0) {	/* infinite loop avoidance (OR do as "nextid < id"?) */
    547 				break;
    548 			}
    549 			continue;
    550 		}
    551 		if (vflag) {
    552 			if (aflag)
    553 				printf("%s: ", fsname);
    554 			printf("%-8s fixed:", fup->fu_name);
    555 			if (dqbuf.dqb_curinodes != fup->fu_curinodes)
    556 				(void)printf("\tinodes %d -> %ld",
    557 					dqbuf.dqb_curinodes, fup->fu_curinodes);
    558 			if (dqbuf.dqb_curblocks != fup->fu_curblocks)
    559 				(void)printf("\tblocks %d -> %ld",
    560 					dqbuf.dqb_curblocks, fup->fu_curblocks);
    561 			(void)printf("\n");
    562 		}
    563 		/*
    564 		 * Reset time limit if have a soft limit and were
    565 		 * previously under it, but are now over it.
    566 		 */
    567 		if (dqbuf.dqb_bsoftlimit &&
    568 		    dqbuf.dqb_curblocks < dqbuf.dqb_bsoftlimit &&
    569 		    fup->fu_curblocks >= dqbuf.dqb_bsoftlimit)
    570 			dqbuf.dqb_btime = 0;
    571 		if (dqbuf.dqb_isoftlimit &&
    572 		    dqbuf.dqb_curinodes < dqbuf.dqb_isoftlimit &&
    573 		    fup->fu_curinodes >= dqbuf.dqb_isoftlimit)
    574 			dqbuf.dqb_itime = 0;
    575 		dqbuf.dqb_curinodes = fup->fu_curinodes;
    576 		dqbuf.dqb_curblocks = fup->fu_curblocks;
    577 
    578 		if (need_seek) {
    579 			(void) fseeko(qfo, (off_t)id * sizeof(struct dqblk),
    580 			    SEEK_SET);
    581 			need_seek = nextid != id + 1;
    582 		}
    583 		(void) fwrite((char *)&dqbuf, sizeof(struct dqblk), 1, qfo);
    584 
    585 		fup->fu_curinodes = 0;
    586 		fup->fu_curblocks = 0;
    587 		if (id == UINT32_MAX || nextid == 0) {	/* infinite loop avoidance (OR do as "nextid < id"?) */
    588 			break;
    589 		}
    590 	}
    591 	(void) fclose(qfi);
    592 	(void) fflush(qfo);
    593 	if (highid[type] != UINT32_MAX)
    594 		(void) ftruncate(fileno(qfo),
    595 		    (off_t)((highid[type] + 1) * sizeof(struct dqblk)));
    596 	(void) fclose(qfo);
    597 	return (0);
    598 }
    599 
    600 uint32_t
    601 skipforward(cur, to, qfi)
    602 	uint32_t cur, to;
    603 	FILE *qfi;
    604 {
    605 	struct dqblk dqbuf;
    606 
    607 	if (qflag) {
    608 		(void) fseeko(qfi, (off_t)to * sizeof(struct dqblk), SEEK_SET);
    609 		return (to);
    610 	}
    611 
    612 	while (++cur < to) {
    613 		/*
    614 		 * if EOF occurs, nothing left to read, we're done
    615 		 */
    616 		if (fread((char *)&dqbuf, sizeof(struct dqblk), 1, qfi) == 0)
    617 			return (to);
    618 
    619 		/*
    620 		 * If we find an entry that shows usage, before the next
    621 		 * id that has actual usage, we have to stop here, so the
    622 		 * incorrect entry can be corrected in the file
    623 		 */
    624 		if (dqbuf.dqb_curinodes != 0 || dqbuf.dqb_curblocks != 0) {
    625 			(void)fseek(qfi, -(long)sizeof(struct dqblk), SEEK_CUR);
    626 			return (cur);
    627 		}
    628 	}
    629 	return (to);
    630 }
    631 
    632 /*
    633  * Check to see if target appears in list of size cnt.
    634  */
    635 static int
    636 oneof(target, list, cnt)
    637 	const char *target;
    638 	char *list[];
    639 	int cnt;
    640 {
    641 	int i;
    642 
    643 	for (i = 0; i < cnt; i++)
    644 		if (strcmp(target, list[i]) == 0)
    645 			return (i);
    646 	return (-1);
    647 }
    648 
    649 /*
    650  * Determine the group identifier for quota files.
    651  */
    652 static int
    653 getquotagid(void)
    654 {
    655 	struct group *gr;
    656 
    657 	if ((gr = getgrnam(quotagroup)) != NULL)
    658 		return gr->gr_gid;
    659 	return -1;
    660 }
    661 
    662 /*
    663  * Routines to manage the file usage table.
    664  *
    665  * Lookup an id of a specific type.
    666  */
    667 static struct fileusage *
    668 lookup(uint32_t id, int type)
    669 {
    670 	struct fileusage *fup;
    671 
    672 	for (fup = fuhead[type][id & (FUHASH-1)]; fup != 0; fup = fup->fu_next)
    673 		if (fup->fu_id == id)
    674 			return fup;
    675 	return NULL;
    676 }
    677 
    678 /*
    679  * Add a new file usage id if it does not already exist.
    680  */
    681 static struct fileusage *
    682 addid(uint32_t id, int type, const char *name)
    683 {
    684 	struct fileusage *fup, **fhp;
    685 	size_t len;
    686 
    687 	if ((fup = lookup(id, type)) != NULL)
    688 		return fup;
    689 	if (name)
    690 		len = strlen(name);
    691 	else
    692 		len = 10;
    693 	if ((fup = calloc(1, sizeof(*fup) + len)) == NULL)
    694 		err(1, "%s", strerror(errno));
    695 	fhp = &fuhead[type][id & (FUHASH - 1)];
    696 	fup->fu_next = *fhp;
    697 	*fhp = fup;
    698 	fup->fu_id = id;
    699 	if (id > highid[type])
    700 		highid[type] = id;
    701 	if (name)
    702 		memmove(fup->fu_name, name, len + 1);
    703 	else
    704 		(void)snprintf(fup->fu_name, len + 1, "%" PRIu32, id);
    705 	return fup;
    706 }
    707 
    708 static uint32_t
    709 subsequent(uint32_t id, int type)
    710 {
    711 	struct fileusage *fup, **iup, **cup;
    712 	uint32_t next, offset;
    713 
    714 	next = highid[type] + 1;
    715 	offset = 0;
    716 	cup = iup = &fuhead[type][id & (FUHASH-1)];
    717 	do {
    718 		++offset;
    719 		if (++cup >= &fuhead[type][FUHASH])
    720 			cup = &fuhead[type][0];
    721 		for (fup = *cup; fup != 0; fup = fup->fu_next) {
    722 			if (fup->fu_id > id && fup->fu_id <= id + offset)
    723 				return (fup->fu_id);
    724 			if (fup->fu_id > id && fup->fu_id < next)
    725 				next = fup->fu_id;
    726 		}
    727 	} while (cup != iup);
    728 
    729 	return next;
    730 }
    731 
    732 /*
    733  * Special purpose version of ginode used to optimize first pass
    734  * over all the inodes in numerical order.
    735  */
    736 static ino_t nextino, lastinum, lastvalidinum;
    737 static long readcnt, readpercg, fullcnt, inobufsize, partialcnt, partialsize;
    738 static union comb_dinode *inodebuf;
    739 #define INOBUFSIZE	56*1024	/* size of buffer to read inodes */
    740 
    741 static union comb_dinode *
    742 getnextinode(ino_t inumber)
    743 {
    744 	long size;
    745 	daddr_t dblk;
    746 	static union comb_dinode *dp;
    747 	union comb_dinode *ret;
    748 
    749 	if (inumber != nextino++ || inumber > lastvalidinum) {
    750 		errx(1, "bad inode number %llu to nextinode",
    751 		    (unsigned long long)inumber);
    752 	}
    753 
    754 	if (inumber >= lastinum) {
    755 		readcnt++;
    756 		dblk = fsbtodb(&sblock, ino_to_fsba(&sblock, lastinum));
    757 		if (readcnt % readpercg == 0) {
    758 			size = partialsize;
    759 			lastinum += partialcnt;
    760 		} else {
    761 			size = inobufsize;
    762 			lastinum += fullcnt;
    763 		}
    764 		(void)bread(dblk, (caddr_t)inodebuf, size);
    765 		if (needswap) {
    766 #ifdef HAVE_UFSv2
    767 			if (is_ufs2)
    768 				swap_dinode2(inodebuf, lastinum - inumber);
    769 			else
    770 #endif
    771 				swap_dinode1(inodebuf, lastinum - inumber);
    772 		}
    773 		dp = (union comb_dinode *)inodebuf;
    774 	}
    775 	ret = dp;
    776 	dp = (union comb_dinode *)
    777 	    ((char *)dp + (is_ufs2 ? DINODE2_SIZE : DINODE1_SIZE));
    778 	return ret;
    779 }
    780 
    781 static void
    782 setinodebuf(ino_t inum)
    783 {
    784 
    785 	if (inum % sblock.fs_ipg != 0)
    786 		errx(1, "bad inode number %llu to setinodebuf",
    787 		    (unsigned long long)inum);
    788 
    789 	lastvalidinum = inum + sblock.fs_ipg - 1;
    790 	nextino = inum;
    791 	lastinum = inum;
    792 	readcnt = 0;
    793 	if (inodebuf != NULL)
    794 		return;
    795 	inobufsize = blkroundup(&sblock, INOBUFSIZE);
    796 	fullcnt = inobufsize / (is_ufs2 ? DINODE2_SIZE : DINODE1_SIZE);
    797 	readpercg = sblock.fs_ipg / fullcnt;
    798 	partialcnt = sblock.fs_ipg % fullcnt;
    799 	partialsize = partialcnt * (is_ufs2 ? DINODE2_SIZE : DINODE1_SIZE);
    800 	if (partialcnt != 0) {
    801 		readpercg++;
    802 	} else {
    803 		partialcnt = fullcnt;
    804 		partialsize = inobufsize;
    805 	}
    806 	if (inodebuf == NULL &&
    807 	    (inodebuf = malloc((unsigned)inobufsize)) == NULL)
    808 		errx(1, "Cannot allocate space for inode buffer");
    809 	while (nextino < ROOTINO)
    810 		getnextinode(nextino);
    811 }
    812 
    813 static void
    814 freeinodebuf(void)
    815 {
    816 
    817 	free(inodebuf);
    818 	inodebuf = NULL;
    819 }
    820 
    821 
    822 #ifdef HAVE_UFSv2
    823 static void
    824 swap_dinode1(union comb_dinode *dp, int n)
    825 {
    826 	int i;
    827 	struct ufs1_dinode *dp1;
    828 
    829 	dp1 = (struct ufs1_dinode *)&dp->dp1;
    830 	for (i = 0; i < n; i++, dp1++)
    831 		ffs_dinode1_swap(dp1, dp1);
    832 }
    833 
    834 static void
    835 swap_dinode2(union comb_dinode *dp, int n)
    836 {
    837 	int i;
    838 	struct ufs2_dinode *dp2;
    839 
    840 	dp2 = (struct ufs2_dinode *)&dp->dp2;
    841 	for (i = 0; i < n; i++, dp2++)
    842 		ffs_dinode2_swap(dp2, dp2);
    843 }
    844 
    845 #else
    846 
    847 static void
    848 swap_dinode1(union comb_dinode *dp, int n)
    849 {
    850 	int i;
    851 	struct dinode *dp1;
    852 
    853 	dp1 = (struct dinode *) &dp->dp1;
    854 	for (i = 0; i < n; i++, dp1++)
    855 		ffs_dinode_swap(dp1, dp1);
    856 }
    857 
    858 #endif
    859 
    860 /*
    861  * Read specified disk blocks.
    862  */
    863 static void
    864 bread(daddr_t bno, char *buf, long cnt)
    865 {
    866 
    867 	if (lseek(fi, (off_t)bno * dev_bsize, SEEK_SET) < 0 ||
    868 	    read(fi, buf, cnt) != cnt)
    869 		err(1, "block %lld", (long long)bno);
    870 }
    871 
    872 static void
    873 infohandler(int sig)
    874 {
    875 	got_siginfo = 1;
    876 }
    877