#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/disklabel.h>
#include <sys/disk.h>
#include <sys/file.h>
#include <sys/mount.h>
#include <sys/statvfs.h>
#include <ufs/lfs/lfs.h>
#include <ufs/lfs/lfs_accessors.h>
#include <disktab.h>
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <util.h>
#include "partutil.h"
static void
usage(void)
{
errx(1, "usage: resize_lfs [-v] [-s new-size] [filesystem]");
}
int
main(int argc, char **argv)
{
char *rdev, *fsname, buf[LFS_SBPAD];
size_t rdevlen;
daddr_t newsize, newnsegs;
int devfd, rootfd;
int ch, i, verbose;
off_t secsize, sboff;
struct disk_geom geo;
struct dkwedge_info dkw;
struct lfs *fs;
struct statvfs vfs;
verbose = 0;
newsize = 0;
while ((ch = getopt(argc, argv, "s:v")) != -1) {
switch(ch) {
case 's':
newsize = strtoll(optarg, NULL, 10);
break;
case 'v':
++verbose;
break;
default:
usage();
}
}
fsname = argv[optind];
if (fsname == NULL)
usage();
if (statvfs(fsname, &vfs) < 0)
err(1, "%s", fsname);
rdevlen = strlen(vfs.f_mntfromname) + 2;
rdev = malloc(rdevlen);
if (getdiskrawname(rdev, rdevlen, vfs.f_mntfromname) == NULL)
err(1, "Could not convert '%s' to raw name", vfs.f_mntfromname);
devfd = open(rdev, O_RDONLY);
if (devfd < 0)
err(1, "open raw device");
if (getdiskinfo(rdev, devfd, NULL, &geo, &dkw) == -1)
err(1, "%s: could not get info", rdev);
secsize = geo.dg_secsize;
if (newsize > dkw.dkw_size)
errx(1, "new size must be <= the partition size");
if (newsize == 0)
newsize = dkw.dkw_size;
rootfd = open(fsname, O_RDONLY);
if (rootfd < 0)
err(1, "open filesystem root");
fs = (struct lfs *)calloc(sizeof(*fs), 1);
for (sboff = LFS_LABELPAD;;) {
pread(devfd, buf, sboff, LFS_SBPAD);
__CTASSERT(sizeof(struct dlfs) == sizeof(struct dlfs64));
memcpy(&fs->lfs_dlfs_u, buf, sizeof(struct dlfs));
if (sboff == LFS_LABELPAD && lfs_fsbtob(fs, 1) > LFS_LABELPAD)
sboff = lfs_fsbtob(fs, (off_t)lfs_sb_getsboff(fs, 0));
else
break;
}
close(devfd);
newnsegs = (newsize * secsize) / lfs_sb_getssize(fs);
if (newnsegs == lfs_sb_getnseg(fs)) {
errx(0, "the filesystem is unchanged.");
}
for (i = lfs_sb_getnseg(fs) - 1; i >= newnsegs; --i) {
char cmd[128];
if (fcntl(rootfd, LFCNINVAL, &i) == 0)
continue;
snprintf(cmd, sizeof(cmd), "/libexec/lfs_cleanerd -q -i %d %s",
i, fsname);
if (system(cmd) != 0)
err(1, "invalidating segment %d", i);
}
if (fcntl(rootfd, LFCNRESIZE, &newnsegs) == -1) {
err(1, "resizing");
}
if (verbose)
printf("Successfully resized %s from %u to %lld segments\n",
fsname, lfs_sb_getnseg(fs), (long long)newnsegs);
return 0;
}