xref: /freebsd/sbin/newfs/newfs.c (revision 39beb93c3f8bdbf72a61fda42300b5ebed7390c8)
1 /*
2  * Copyright (c) 2002 Networks Associates Technology, Inc.
3  * All rights reserved.
4  *
5  * This software was developed for the FreeBSD Project by Marshall
6  * Kirk McKusick and Network Associates Laboratories, the Security
7  * Research Division of Network Associates, Inc. under DARPA/SPAWAR
8  * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
9  * research program.
10  *
11  * Copyright (c) 1983, 1989, 1993, 1994
12  *	The Regents of the University of California.  All rights reserved.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  */
38 
39 #if 0
40 #ifndef lint
41 static const char copyright[] =
42 "@(#) Copyright (c) 1983, 1989, 1993, 1994\n\
43 	The Regents of the University of California.  All rights reserved.\n";
44 #endif /* not lint */
45 
46 #ifndef lint
47 static char sccsid[] = "@(#)newfs.c	8.13 (Berkeley) 5/1/95";
48 #endif /* not lint */
49 #endif
50 #include <sys/cdefs.h>
51 __FBSDID("$FreeBSD$");
52 
53 /*
54  * newfs: friendly front end to mkfs
55  */
56 #include <sys/param.h>
57 #include <sys/stat.h>
58 #include <sys/disk.h>
59 #include <sys/disklabel.h>
60 #include <sys/file.h>
61 #include <sys/mount.h>
62 
63 #include <ufs/ufs/dir.h>
64 #include <ufs/ufs/dinode.h>
65 #include <ufs/ffs/fs.h>
66 #include <ufs/ufs/ufsmount.h>
67 
68 #include <ctype.h>
69 #include <err.h>
70 #include <errno.h>
71 #include <inttypes.h>
72 #include <paths.h>
73 #include <stdarg.h>
74 #include <stdio.h>
75 #include <stdlib.h>
76 #include <string.h>
77 #include <syslog.h>
78 #include <unistd.h>
79 
80 #include "newfs.h"
81 
82 /*
83  * The following two constants set the default block and fragment sizes.
84  * Both constants must be a power of 2 and meet the following constraints:
85  *	MINBSIZE <= DESBLKSIZE <= MAXBSIZE
86  *	sectorsize <= DESFRAGSIZE <= DESBLKSIZE
87  *	DESBLKSIZE / DESFRAGSIZE <= 8
88  */
89 #define	DFL_FRAGSIZE	2048
90 #define	DFL_BLKSIZE	16384
91 
92 /*
93  * Cylinder groups may have up to MAXBLKSPERCG blocks. The actual
94  * number used depends upon how much information can be stored
95  * in a cylinder group map which must fit in a single file system
96  * block. The default is to use as many as possible blocks per group.
97  */
98 #define	MAXBLKSPERCG	0x7fffffff	/* desired fs_fpg ("infinity") */
99 
100 /*
101  * MAXBLKPG determines the maximum number of data blocks which are
102  * placed in a single cylinder group. The default is one indirect
103  * block worth of data blocks.
104  */
105 #define MAXBLKPG(bsize)	((bsize) / sizeof(ufs2_daddr_t))
106 
107 /*
108  * Each file system has a number of inodes statically allocated.
109  * We allocate one inode slot per NFPI fragments, expecting this
110  * to be far more than we will ever need.
111  */
112 #define	NFPI		4
113 
114 int	Eflag;			/* Erase previous disk contents */
115 int	Lflag;			/* add a volume label */
116 int	Nflag;			/* run without writing file system */
117 int	Oflag = 2;		/* file system format (1 => UFS1, 2 => UFS2) */
118 int	Rflag;			/* regression test */
119 int	Uflag;			/* enable soft updates for file system */
120 int	Xflag = 0;		/* exit in middle of newfs for testing */
121 int	Jflag;			/* enable gjournal for file system */
122 int	lflag;			/* enable multilabel for file system */
123 int	nflag;			/* do not create .snap directory */
124 intmax_t fssize;		/* file system size */
125 int	sectorsize;		/* bytes/sector */
126 int	realsectorsize;		/* bytes/sector in hardware */
127 int	fsize = 0;		/* fragment size */
128 int	bsize = 0;		/* block size */
129 int	maxbsize = 0;		/* maximum clustering */
130 int	maxblkspercg = MAXBLKSPERCG; /* maximum blocks per cylinder group */
131 int	minfree = MINFREE;	/* free space threshold */
132 int	opt = DEFAULTOPT;	/* optimization preference (space or time) */
133 int	density;		/* number of bytes per inode */
134 int	maxcontig = 0;		/* max contiguous blocks to allocate */
135 int	maxbpg;			/* maximum blocks per file in a cyl group */
136 int	avgfilesize = AVFILESIZ;/* expected average file size */
137 int	avgfilesperdir = AFPDIR;/* expected number of files per directory */
138 u_char	*volumelabel = NULL;	/* volume label for filesystem */
139 struct uufsd disk;		/* libufs disk structure */
140 
141 static char	device[MAXPATHLEN];
142 static u_char   bootarea[BBSIZE];
143 static int	is_file;		/* work on a file, not a device */
144 static char	*dkname;
145 static char	*disktype;
146 static int	unlabeled;
147 
148 static void getfssize(intmax_t *, const char *p, intmax_t, intmax_t);
149 static struct disklabel *getdisklabel(char *s);
150 static void rewritelabel(char *s, struct disklabel *lp);
151 static void usage(void);
152 
153 ufs2_daddr_t part_ofs; /* partition offset in blocks, used with files */
154 
155 int
156 main(int argc, char *argv[])
157 {
158 	struct partition *pp;
159 	struct disklabel *lp;
160 	struct partition oldpartition;
161 	struct stat st;
162 	char *cp, *special;
163 	intmax_t reserved;
164 	int ch, i;
165 	off_t mediasize;
166 	char part_name;		/* partition name, default to full disk */
167 
168 	part_name = 'c';
169 	reserved = 0;
170 	while ((ch = getopt(argc, argv,
171 	    "EJL:NO:RS:T:UXa:b:c:d:e:f:g:h:i:lm:no:r:s:")) != -1)
172 		switch (ch) {
173 		case 'E':
174 			Eflag = 1;
175 			break;
176 		case 'J':
177 			Jflag = 1;
178 			break;
179 		case 'L':
180 			volumelabel = optarg;
181 			i = -1;
182 			while (isalnum(volumelabel[++i]));
183 			if (volumelabel[i] != '\0') {
184 				errx(1, "bad volume label. Valid characters are alphanumerics.");
185 			}
186 			if (strlen(volumelabel) >= MAXVOLLEN) {
187 				errx(1, "bad volume label. Length is longer than %d.",
188 				    MAXVOLLEN);
189 			}
190 			Lflag = 1;
191 			break;
192 		case 'N':
193 			Nflag = 1;
194 			break;
195 		case 'O':
196 			if ((Oflag = atoi(optarg)) < 1 || Oflag > 2)
197 				errx(1, "%s: bad file system format value",
198 				    optarg);
199 			break;
200 		case 'R':
201 			Rflag = 1;
202 			break;
203 		case 'S':
204 			if ((sectorsize = atoi(optarg)) <= 0)
205 				errx(1, "%s: bad sector size", optarg);
206 			break;
207 		case 'T':
208 			disktype = optarg;
209 			break;
210 		case 'U':
211 			Uflag = 1;
212 			break;
213 		case 'X':
214 			Xflag++;
215 			break;
216 		case 'a':
217 			if ((maxcontig = atoi(optarg)) <= 0)
218 				errx(1, "%s: bad maximum contiguous blocks",
219 				    optarg);
220 			break;
221 		case 'b':
222 			if ((bsize = atoi(optarg)) < MINBSIZE)
223 				errx(1, "%s: block size too small, min is %d",
224 				    optarg, MINBSIZE);
225 			if (bsize > MAXBSIZE)
226 				errx(1, "%s: block size too large, max is %d",
227 				    optarg, MAXBSIZE);
228 			break;
229 		case 'c':
230 			if ((maxblkspercg = atoi(optarg)) <= 0)
231 				errx(1, "%s: bad blocks per cylinder group",
232 				    optarg);
233 			break;
234 		case 'd':
235 			if ((maxbsize = atoi(optarg)) < MINBSIZE)
236 				errx(1, "%s: bad extent block size", optarg);
237 			break;
238 		case 'e':
239 			if ((maxbpg = atoi(optarg)) <= 0)
240 			  errx(1, "%s: bad blocks per file in a cylinder group",
241 				    optarg);
242 			break;
243 		case 'f':
244 			if ((fsize = atoi(optarg)) <= 0)
245 				errx(1, "%s: bad fragment size", optarg);
246 			break;
247 		case 'g':
248 			if ((avgfilesize = atoi(optarg)) <= 0)
249 				errx(1, "%s: bad average file size", optarg);
250 			break;
251 		case 'h':
252 			if ((avgfilesperdir = atoi(optarg)) <= 0)
253 			       errx(1, "%s: bad average files per dir", optarg);
254 			break;
255 		case 'i':
256 			if ((density = atoi(optarg)) <= 0)
257 				errx(1, "%s: bad bytes per inode", optarg);
258 			break;
259 		case 'l':
260 			lflag = 1;
261 			break;
262 		case 'm':
263 			if ((minfree = atoi(optarg)) < 0 || minfree > 99)
264 				errx(1, "%s: bad free space %%", optarg);
265 			break;
266 		case 'n':
267 			nflag = 1;
268 			break;
269 		case 'o':
270 			if (strcmp(optarg, "space") == 0)
271 				opt = FS_OPTSPACE;
272 			else if (strcmp(optarg, "time") == 0)
273 				opt = FS_OPTTIME;
274 			else
275 				errx(1,
276 		"%s: unknown optimization preference: use `space' or `time'",
277 				    optarg);
278 			break;
279 		case 'r':
280 			errno = 0;
281 			reserved = strtoimax(optarg, &cp, 0);
282 			if (errno != 0 || cp == optarg ||
283 			    *cp != '\0' || reserved < 0)
284 				errx(1, "%s: bad reserved size", optarg);
285 			break;
286 		case 'p':
287 			is_file = 1;
288 			part_name = optarg[0];
289 			break;
290 
291 		case 's':
292 			errno = 0;
293 			fssize = strtoimax(optarg, &cp, 0);
294 			if (errno != 0 || cp == optarg ||
295 			    *cp != '\0' || fssize < 0)
296 				errx(1, "%s: bad file system size", optarg);
297 			break;
298 		case '?':
299 		default:
300 			usage();
301 		}
302 	argc -= optind;
303 	argv += optind;
304 
305 	if (argc != 1)
306 		usage();
307 
308 	special = argv[0];
309 	if (!special[0])
310 		err(1, "empty file/special name");
311 	cp = strrchr(special, '/');
312 	if (cp == 0) {
313 		/*
314 		 * No path prefix; try prefixing _PATH_DEV.
315 		 */
316 		snprintf(device, sizeof(device), "%s%s", _PATH_DEV, special);
317 		special = device;
318 	}
319 
320 	if (is_file) {
321 		/* bypass ufs_disk_fillout_blank */
322 		bzero( &disk, sizeof(disk));
323 		disk.d_bsize = 1;
324 		disk.d_name = special;
325 		disk.d_fd = open(special, O_RDONLY);
326 		if (disk.d_fd < 0 ||
327 		    (!Nflag && ufs_disk_write(&disk) == -1))
328 			errx(1, "%s: ", special);
329 	} else if (ufs_disk_fillout_blank(&disk, special) == -1 ||
330 	    (!Nflag && ufs_disk_write(&disk) == -1)) {
331 		if (disk.d_error != NULL)
332 			errx(1, "%s: %s", special, disk.d_error);
333 		else
334 			err(1, "%s", special);
335 	}
336 	if (fstat(disk.d_fd, &st) < 0)
337 		err(1, "%s", special);
338 	if ((st.st_mode & S_IFMT) != S_IFCHR) {
339 		warn("%s: not a character-special device", special);
340 		is_file = 1;	/* assume it is a file */
341 		dkname = special;
342 		if (sectorsize == 0)
343 			sectorsize = 512;
344 		mediasize = st.st_size;
345 		/* set fssize from the partition */
346 	} else {
347 	    if (sectorsize == 0)
348 		if (ioctl(disk.d_fd, DIOCGSECTORSIZE, &sectorsize) == -1)
349 		    sectorsize = 0;	/* back out on error for safety */
350 	    if (sectorsize && ioctl(disk.d_fd, DIOCGMEDIASIZE, &mediasize) != -1)
351 		getfssize(&fssize, special, mediasize / sectorsize, reserved);
352 	}
353 	pp = NULL;
354 	lp = getdisklabel(special);
355 	if (lp != NULL) {
356 		if (!is_file) /* already set for files */
357 			part_name = special[strlen(special) - 1];
358 		if ((part_name < 'a' || part_name - 'a' >= MAXPARTITIONS) &&
359 				!isdigit(part_name))
360 			errx(1, "%s: can't figure out file system partition",
361 					special);
362 		cp = &part_name;
363 		if (isdigit(*cp))
364 			pp = &lp->d_partitions[RAW_PART];
365 		else
366 			pp = &lp->d_partitions[*cp - 'a'];
367 		oldpartition = *pp;
368 		if (pp->p_size == 0)
369 			errx(1, "%s: `%c' partition is unavailable",
370 			    special, *cp);
371 		if (pp->p_fstype == FS_BOOT)
372 			errx(1, "%s: `%c' partition overlaps boot program",
373 			    special, *cp);
374 		getfssize(&fssize, special, pp->p_size, reserved);
375 		if (sectorsize == 0)
376 			sectorsize = lp->d_secsize;
377 		if (fsize == 0)
378 			fsize = pp->p_fsize;
379 		if (bsize == 0)
380 			bsize = pp->p_frag * pp->p_fsize;
381 		if (is_file)
382 			part_ofs = pp->p_offset;
383 	}
384 	if (sectorsize <= 0)
385 		errx(1, "%s: no default sector size", special);
386 	if (fsize <= 0)
387 		fsize = MAX(DFL_FRAGSIZE, sectorsize);
388 	if (bsize <= 0)
389 		bsize = MIN(DFL_BLKSIZE, 8 * fsize);
390 	if (maxbsize == 0)
391 		maxbsize = bsize;
392 	/*
393 	 * Maxcontig sets the default for the maximum number of blocks
394 	 * that may be allocated sequentially. With file system clustering
395 	 * it is possible to allocate contiguous blocks up to the maximum
396 	 * transfer size permitted by the controller or buffering.
397 	 */
398 	if (maxcontig == 0)
399 		maxcontig = MAX(1, MAXPHYS / bsize);
400 	if (density == 0)
401 		density = NFPI * fsize;
402 	if (minfree < MINFREE && opt != FS_OPTSPACE) {
403 		fprintf(stderr, "Warning: changing optimization to space ");
404 		fprintf(stderr, "because minfree is less than %d%%\n", MINFREE);
405 		opt = FS_OPTSPACE;
406 	}
407 	if (maxbpg == 0)
408 		maxbpg = MAXBLKPG(bsize);
409 	realsectorsize = sectorsize;
410 	if (sectorsize != DEV_BSIZE) {		/* XXX */
411 		int secperblk = sectorsize / DEV_BSIZE;
412 
413 		sectorsize = DEV_BSIZE;
414 		fssize *= secperblk;
415 		if (pp != NULL)
416 			pp->p_size *= secperblk;
417 	}
418 	mkfs(pp, special);
419 	if (!unlabeled) {
420 		if (realsectorsize != DEV_BSIZE)
421 			pp->p_size /= realsectorsize / DEV_BSIZE;
422 		if (!Nflag && bcmp(pp, &oldpartition, sizeof(oldpartition)))
423 			rewritelabel(special, lp);
424 	}
425 	ufs_disk_close(&disk);
426 	exit(0);
427 }
428 
429 void
430 getfssize(intmax_t *fsz, const char *s, intmax_t disksize, intmax_t reserved)
431 {
432 	intmax_t available;
433 
434 	available = disksize - reserved;
435 	if (available <= 0)
436 		errx(1, "%s: reserved not less than device size %jd",
437 		    s, disksize);
438 	if (*fsz == 0)
439 		*fsz = available;
440 	else if (*fsz > available)
441 		errx(1, "%s: maximum file system size is %jd",
442 		    s, available);
443 }
444 
445 struct disklabel *
446 getdisklabel(char *s)
447 {
448 	static struct disklabel lab;
449 	struct disklabel *lp;
450 
451 	if (is_file) {
452 		if (read(disk.d_fd, bootarea, BBSIZE) != BBSIZE)
453 			err(4, "cannot read bootarea");
454 		if (bsd_disklabel_le_dec(
455 		    bootarea + (0 /* labeloffset */ +
456 				1 /* labelsoffset */ * sectorsize),
457 		    &lab, MAXPARTITIONS))
458 			errx(1, "no valid label found");
459 
460 		lp = &lab;
461 		return &lab;
462 	}
463 
464 	if (ioctl(disk.d_fd, DIOCGDINFO, (char *)&lab) != -1)
465 		return (&lab);
466 	unlabeled++;
467 	if (disktype) {
468 		lp = getdiskbyname(disktype);
469 		if (lp != NULL)
470 			return (lp);
471 	}
472 	return (NULL);
473 }
474 
475 void
476 rewritelabel(char *s, struct disklabel *lp)
477 {
478 	if (unlabeled)
479 		return;
480 	lp->d_checksum = 0;
481 	lp->d_checksum = dkcksum(lp);
482 	if (is_file) {
483 		bsd_disklabel_le_enc(bootarea + 0 /* labeloffset */ +
484 			1 /* labelsoffset */ * sectorsize, lp);
485 		lseek(disk.d_fd, 0, SEEK_SET);
486 		if (write(disk.d_fd, bootarea, BBSIZE) != BBSIZE)
487 			errx(1, "cannot write label");
488 		return;
489 	}
490 	if (ioctl(disk.d_fd, DIOCWDINFO, (char *)lp) == -1)
491 		warn("ioctl (WDINFO): %s: can't rewrite disk label", s);
492 }
493 
494 static void
495 usage()
496 {
497 	fprintf(stderr,
498 	    "usage: %s [ -fsoptions ] special-device%s\n",
499 	    getprogname(),
500 	    " [device-type]");
501 	fprintf(stderr, "where fsoptions are:\n");
502 	fprintf(stderr, "\t-E Erase previuos disk content\n");
503 	fprintf(stderr, "\t-J Enable journaling via gjournal\n");
504 	fprintf(stderr, "\t-L volume label to add to superblock\n");
505 	fprintf(stderr,
506 	    "\t-N do not create file system, just print out parameters\n");
507 	fprintf(stderr, "\t-O file system format: 1 => UFS1, 2 => UFS2\n");
508 	fprintf(stderr, "\t-R regression test, supress random factors\n");
509 	fprintf(stderr, "\t-S sector size\n");
510 	fprintf(stderr, "\t-T disktype\n");
511 	fprintf(stderr, "\t-U enable soft updates\n");
512 	fprintf(stderr, "\t-a maximum contiguous blocks\n");
513 	fprintf(stderr, "\t-b block size\n");
514 	fprintf(stderr, "\t-c blocks per cylinders group\n");
515 	fprintf(stderr, "\t-d maximum extent size\n");
516 	fprintf(stderr, "\t-e maximum blocks per file in a cylinder group\n");
517 	fprintf(stderr, "\t-f frag size\n");
518 	fprintf(stderr, "\t-g average file size\n");
519 	fprintf(stderr, "\t-h average files per directory\n");
520 	fprintf(stderr, "\t-i number of bytes per inode\n");
521 	fprintf(stderr, "\t-l enable multilabel MAC\n");
522 	fprintf(stderr, "\t-n do not create .snap directory\n");
523 	fprintf(stderr, "\t-m minimum free space %%\n");
524 	fprintf(stderr, "\t-o optimization preference (`space' or `time')\n");
525 	fprintf(stderr, "\t-p partition name (a..h)\n");
526 	fprintf(stderr, "\t-r reserved sectors at the end of device\n");
527 	fprintf(stderr, "\t-s file system size (sectors)\n");
528 	exit(1);
529 }
530