xref: /freebsd/sbin/newfs/newfs.c (revision 5c52a79884070364bfc920fb8e492cfac61ec72f)
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 /*
156  * need to replace the library's bwrite so that sbwrite uses this one
157  */
158 ssize_t
159 bwrite(struct uufsd *disk, ufs2_daddr_t blockno, const void *data, size_t size)
160 {
161 	return pwrite(disk->d_fd, data, size,
162 		(off_t)((part_ofs + blockno) * disk->d_bsize));
163 }
164 
165 int
166 main(int argc, char *argv[])
167 {
168 	struct partition *pp;
169 	struct disklabel *lp;
170 	struct partition oldpartition;
171 	struct stat st;
172 	char *cp, *special;
173 	intmax_t reserved;
174 	int ch, i;
175 	off_t mediasize;
176 	char part_name;		/* partition name, default to full disk */
177 
178 	part_name = 'c';
179 	reserved = 0;
180 	while ((ch = getopt(argc, argv,
181 	    "EJL:NO:RS:T:UXa:b:c:d:e:f:g:h:i:lm:no:r:s:")) != -1)
182 		switch (ch) {
183 		case 'E':
184 			Eflag = 1;
185 			break;
186 		case 'J':
187 			Jflag = 1;
188 			break;
189 		case 'L':
190 			volumelabel = optarg;
191 			i = -1;
192 			while (isalnum(volumelabel[++i]));
193 			if (volumelabel[i] != '\0') {
194 				errx(1, "bad volume label. Valid characters are alphanumerics.");
195 			}
196 			if (strlen(volumelabel) >= MAXVOLLEN) {
197 				errx(1, "bad volume label. Length is longer than %d.",
198 				    MAXVOLLEN);
199 			}
200 			Lflag = 1;
201 			break;
202 		case 'N':
203 			Nflag = 1;
204 			break;
205 		case 'O':
206 			if ((Oflag = atoi(optarg)) < 1 || Oflag > 2)
207 				errx(1, "%s: bad file system format value",
208 				    optarg);
209 			break;
210 		case 'R':
211 			Rflag = 1;
212 			break;
213 		case 'S':
214 			if ((sectorsize = atoi(optarg)) <= 0)
215 				errx(1, "%s: bad sector size", optarg);
216 			break;
217 		case 'T':
218 			disktype = optarg;
219 			break;
220 		case 'U':
221 			Uflag = 1;
222 			break;
223 		case 'X':
224 			Xflag++;
225 			break;
226 		case 'a':
227 			if ((maxcontig = atoi(optarg)) <= 0)
228 				errx(1, "%s: bad maximum contiguous blocks",
229 				    optarg);
230 			break;
231 		case 'b':
232 			if ((bsize = atoi(optarg)) < MINBSIZE)
233 				errx(1, "%s: block size too small, min is %d",
234 				    optarg, MINBSIZE);
235 			if (bsize > MAXBSIZE)
236 				errx(1, "%s: block size too large, max is %d",
237 				    optarg, MAXBSIZE);
238 			break;
239 		case 'c':
240 			if ((maxblkspercg = atoi(optarg)) <= 0)
241 				errx(1, "%s: bad blocks per cylinder group",
242 				    optarg);
243 			break;
244 		case 'd':
245 			if ((maxbsize = atoi(optarg)) < MINBSIZE)
246 				errx(1, "%s: bad extent block size", optarg);
247 			break;
248 		case 'e':
249 			if ((maxbpg = atoi(optarg)) <= 0)
250 			  errx(1, "%s: bad blocks per file in a cylinder group",
251 				    optarg);
252 			break;
253 		case 'f':
254 			if ((fsize = atoi(optarg)) <= 0)
255 				errx(1, "%s: bad fragment size", optarg);
256 			break;
257 		case 'g':
258 			if ((avgfilesize = atoi(optarg)) <= 0)
259 				errx(1, "%s: bad average file size", optarg);
260 			break;
261 		case 'h':
262 			if ((avgfilesperdir = atoi(optarg)) <= 0)
263 			       errx(1, "%s: bad average files per dir", optarg);
264 			break;
265 		case 'i':
266 			if ((density = atoi(optarg)) <= 0)
267 				errx(1, "%s: bad bytes per inode", optarg);
268 			break;
269 		case 'l':
270 			lflag = 1;
271 			break;
272 		case 'm':
273 			if ((minfree = atoi(optarg)) < 0 || minfree > 99)
274 				errx(1, "%s: bad free space %%", optarg);
275 			break;
276 		case 'n':
277 			nflag = 1;
278 			break;
279 		case 'o':
280 			if (strcmp(optarg, "space") == 0)
281 				opt = FS_OPTSPACE;
282 			else if (strcmp(optarg, "time") == 0)
283 				opt = FS_OPTTIME;
284 			else
285 				errx(1,
286 		"%s: unknown optimization preference: use `space' or `time'",
287 				    optarg);
288 			break;
289 		case 'r':
290 			errno = 0;
291 			reserved = strtoimax(optarg, &cp, 0);
292 			if (errno != 0 || cp == optarg ||
293 			    *cp != '\0' || reserved < 0)
294 				errx(1, "%s: bad reserved size", optarg);
295 			break;
296 		case 'p':
297 			is_file = 1;
298 			part_name = optarg[0];
299 			break;
300 
301 		case 's':
302 			errno = 0;
303 			fssize = strtoimax(optarg, &cp, 0);
304 			if (errno != 0 || cp == optarg ||
305 			    *cp != '\0' || fssize < 0)
306 				errx(1, "%s: bad file system size", optarg);
307 			break;
308 		case '?':
309 		default:
310 			usage();
311 		}
312 	argc -= optind;
313 	argv += optind;
314 
315 	if (argc != 1)
316 		usage();
317 
318 	special = argv[0];
319 	if (!special[0])
320 		err(1, "empty file/special name");
321 	cp = strrchr(special, '/');
322 	if (cp == 0) {
323 		/*
324 		 * No path prefix; try prefixing _PATH_DEV.
325 		 */
326 		snprintf(device, sizeof(device), "%s%s", _PATH_DEV, special);
327 		special = device;
328 	}
329 
330 	if (is_file) {
331 		/* bypass ufs_disk_fillout_blank */
332 		bzero( &disk, sizeof(disk));
333 		disk.d_bsize = 1;
334 		disk.d_name = special;
335 		disk.d_fd = open(special, O_RDONLY);
336 		if (disk.d_fd < 0 ||
337 		    (!Nflag && ufs_disk_write(&disk) == -1))
338 			errx(1, "%s: ", special);
339 	} else if (ufs_disk_fillout_blank(&disk, special) == -1 ||
340 	    (!Nflag && ufs_disk_write(&disk) == -1)) {
341 		if (disk.d_error != NULL)
342 			errx(1, "%s: %s", special, disk.d_error);
343 		else
344 			err(1, "%s", special);
345 	}
346 	if (fstat(disk.d_fd, &st) < 0)
347 		err(1, "%s", special);
348 	if ((st.st_mode & S_IFMT) != S_IFCHR) {
349 		warn("%s: not a character-special device", special);
350 		is_file = 1;	/* assume it is a file */
351 		dkname = special;
352 		if (sectorsize == 0)
353 			sectorsize = 512;
354 		mediasize = st.st_size;
355 		/* set fssize from the partition */
356 	} else {
357 	    part_name = special[strlen(special) - 1];
358 	    if ((part_name < 'a' || part_name > 'h') && !isdigit(part_name))
359 		errx(1, "%s: can't figure out file system partition",
360 				special);
361 
362 	    if (sectorsize == 0)
363 		if (ioctl(disk.d_fd, DIOCGSECTORSIZE, &sectorsize) == -1)
364 		    sectorsize = 0;	/* back out on error for safety */
365 	    if (sectorsize && ioctl(disk.d_fd, DIOCGMEDIASIZE, &mediasize) != -1)
366 		getfssize(&fssize, special, mediasize / sectorsize, reserved);
367 	}
368 	pp = NULL;
369 	lp = getdisklabel(special);
370 	if (lp != NULL) {
371 		cp = &part_name;
372 		if (isdigit(*cp))
373 			pp = &lp->d_partitions[RAW_PART];
374 		else
375 			pp = &lp->d_partitions[*cp - 'a'];
376 		oldpartition = *pp;
377 		if (pp->p_size == 0)
378 			errx(1, "%s: `%c' partition is unavailable",
379 			    special, *cp);
380 		if (pp->p_fstype == FS_BOOT)
381 			errx(1, "%s: `%c' partition overlaps boot program",
382 			    special, *cp);
383 		getfssize(&fssize, special, pp->p_size, reserved);
384 		if (sectorsize == 0)
385 			sectorsize = lp->d_secsize;
386 		if (fsize == 0)
387 			fsize = pp->p_fsize;
388 		if (bsize == 0)
389 			bsize = pp->p_frag * pp->p_fsize;
390 		if (is_file)
391 			part_ofs = pp->p_offset;
392 	}
393 	if (sectorsize <= 0)
394 		errx(1, "%s: no default sector size", special);
395 	if (fsize <= 0)
396 		fsize = MAX(DFL_FRAGSIZE, sectorsize);
397 	if (bsize <= 0)
398 		bsize = MIN(DFL_BLKSIZE, 8 * fsize);
399 	if (maxbsize == 0)
400 		maxbsize = bsize;
401 	/*
402 	 * Maxcontig sets the default for the maximum number of blocks
403 	 * that may be allocated sequentially. With file system clustering
404 	 * it is possible to allocate contiguous blocks up to the maximum
405 	 * transfer size permitted by the controller or buffering.
406 	 */
407 	if (maxcontig == 0)
408 		maxcontig = MAX(1, MAXPHYS / bsize);
409 	if (density == 0)
410 		density = NFPI * fsize;
411 	if (minfree < MINFREE && opt != FS_OPTSPACE) {
412 		fprintf(stderr, "Warning: changing optimization to space ");
413 		fprintf(stderr, "because minfree is less than %d%%\n", MINFREE);
414 		opt = FS_OPTSPACE;
415 	}
416 	if (maxbpg == 0)
417 		maxbpg = MAXBLKPG(bsize);
418 	realsectorsize = sectorsize;
419 	if (sectorsize != DEV_BSIZE) {		/* XXX */
420 		int secperblk = sectorsize / DEV_BSIZE;
421 
422 		sectorsize = DEV_BSIZE;
423 		fssize *= secperblk;
424 		if (pp != NULL)
425 			pp->p_size *= secperblk;
426 	}
427 	mkfs(pp, special);
428 	if (!unlabeled) {
429 		if (realsectorsize != DEV_BSIZE)
430 			pp->p_size /= realsectorsize / DEV_BSIZE;
431 		if (!Nflag && bcmp(pp, &oldpartition, sizeof(oldpartition)))
432 			rewritelabel(special, lp);
433 	}
434 	ufs_disk_close(&disk);
435 	exit(0);
436 }
437 
438 void
439 getfssize(intmax_t *fsz, const char *s, intmax_t disksize, intmax_t reserved)
440 {
441 	intmax_t available;
442 
443 	available = disksize - reserved;
444 	if (available <= 0)
445 		errx(1, "%s: reserved not less than device size %jd",
446 		    s, disksize);
447 	if (*fsz == 0)
448 		*fsz = available;
449 	else if (*fsz > available)
450 		errx(1, "%s: maximum file system size is %jd",
451 		    s, available);
452 }
453 
454 struct disklabel *
455 getdisklabel(char *s)
456 {
457 	static struct disklabel lab;
458 	struct disklabel *lp;
459 
460 	if (is_file) {
461 		if (read(disk.d_fd, bootarea, BBSIZE) != BBSIZE)
462 			err(4, "cannot read bootarea");
463 		if (bsd_disklabel_le_dec(
464 		    bootarea + (0 /* labeloffset */ +
465 				1 /* labelsoffset */ * sectorsize),
466 		    &lab, MAXPARTITIONS))
467 			errx(1, "no valid label found");
468 
469 		lp = &lab;
470 		return &lab;
471 	}
472 
473 	if (ioctl(disk.d_fd, DIOCGDINFO, (char *)&lab) != -1)
474 		return (&lab);
475 	unlabeled++;
476 	if (disktype) {
477 		lp = getdiskbyname(disktype);
478 		if (lp != NULL)
479 			return (lp);
480 	}
481 	return (NULL);
482 }
483 
484 void
485 rewritelabel(char *s, struct disklabel *lp)
486 {
487 	if (unlabeled)
488 		return;
489 	lp->d_checksum = 0;
490 	lp->d_checksum = dkcksum(lp);
491 	if (is_file) {
492 		bsd_disklabel_le_enc(bootarea + 0 /* labeloffset */ +
493 			1 /* labelsoffset */ * sectorsize, lp);
494 		lseek(disk.d_fd, 0, SEEK_SET);
495 		if (write(disk.d_fd, bootarea, BBSIZE) != BBSIZE)
496 			errx(1, "cannot write label");
497 		return;
498 	}
499 	if (ioctl(disk.d_fd, DIOCWDINFO, (char *)lp) == -1)
500 		warn("ioctl (WDINFO): %s: can't rewrite disk label", s);
501 }
502 
503 static void
504 usage()
505 {
506 	fprintf(stderr,
507 	    "usage: %s [ -fsoptions ] special-device%s\n",
508 	    getprogname(),
509 	    " [device-type]");
510 	fprintf(stderr, "where fsoptions are:\n");
511 	fprintf(stderr, "\t-E Erase previuos disk content\n");
512 	fprintf(stderr, "\t-J Enable journaling via gjournal\n");
513 	fprintf(stderr, "\t-L volume label to add to superblock\n");
514 	fprintf(stderr,
515 	    "\t-N do not create file system, just print out parameters\n");
516 	fprintf(stderr, "\t-O file system format: 1 => UFS1, 2 => UFS2\n");
517 	fprintf(stderr, "\t-R regression test, supress random factors\n");
518 	fprintf(stderr, "\t-S sector size\n");
519 	fprintf(stderr, "\t-T disktype\n");
520 	fprintf(stderr, "\t-U enable soft updates\n");
521 	fprintf(stderr, "\t-a maximum contiguous blocks\n");
522 	fprintf(stderr, "\t-b block size\n");
523 	fprintf(stderr, "\t-c blocks per cylinders group\n");
524 	fprintf(stderr, "\t-d maximum extent size\n");
525 	fprintf(stderr, "\t-e maximum blocks per file in a cylinder group\n");
526 	fprintf(stderr, "\t-f frag size\n");
527 	fprintf(stderr, "\t-g average file size\n");
528 	fprintf(stderr, "\t-h average files per directory\n");
529 	fprintf(stderr, "\t-i number of bytes per inode\n");
530 	fprintf(stderr, "\t-l enable multilabel MAC\n");
531 	fprintf(stderr, "\t-n do not create .snap directory\n");
532 	fprintf(stderr, "\t-m minimum free space %%\n");
533 	fprintf(stderr, "\t-o optimization preference (`space' or `time')\n");
534 	fprintf(stderr, "\t-p partition name (a..h)\n");
535 	fprintf(stderr, "\t-r reserved sectors at the end of device\n");
536 	fprintf(stderr, "\t-s file system size (sectors)\n");
537 	exit(1);
538 }
539