xref: /freebsd/sbin/newfs/newfs.c (revision e796cc77c586c2955b2f3940dbf4991b31e8d289)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2002 Networks Associates Technology, Inc.
5  * All rights reserved.
6  *
7  * This software was developed for the FreeBSD Project by Marshall
8  * Kirk McKusick and Network Associates Laboratories, the Security
9  * Research Division of Network Associates, Inc. under DARPA/SPAWAR
10  * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
11  * research program.
12  *
13  * Copyright (c) 1983, 1989, 1993, 1994
14  *	The Regents of the University of California.  All rights reserved.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  * 3. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  */
40 
41 #if 0
42 #ifndef lint
43 static const char copyright[] =
44 "@(#) Copyright (c) 1983, 1989, 1993, 1994\n\
45 	The Regents of the University of California.  All rights reserved.\n";
46 #endif /* not lint */
47 
48 #ifndef lint
49 static char sccsid[] = "@(#)newfs.c	8.13 (Berkeley) 5/1/95";
50 #endif /* not lint */
51 #endif
52 #include <sys/cdefs.h>
53 __FBSDID("$FreeBSD$");
54 
55 /*
56  * newfs: friendly front end to mkfs
57  */
58 #include <sys/param.h>
59 #include <sys/stat.h>
60 #include <sys/disk.h>
61 #include <sys/disklabel.h>
62 #include <sys/file.h>
63 #include <sys/mount.h>
64 
65 #include <ufs/ufs/dir.h>
66 #include <ufs/ufs/dinode.h>
67 #include <ufs/ffs/fs.h>
68 #include <ufs/ufs/ufsmount.h>
69 
70 #include <ctype.h>
71 #include <err.h>
72 #include <errno.h>
73 #include <inttypes.h>
74 #include <paths.h>
75 #include <stdarg.h>
76 #include <stdio.h>
77 #include <stdlib.h>
78 #include <string.h>
79 #include <syslog.h>
80 #include <unistd.h>
81 
82 #include <libutil.h>
83 
84 #include "newfs.h"
85 
86 int	Eflag;			/* Erase previous disk contents */
87 int	Lflag;			/* add a volume label */
88 int	Nflag;			/* run without writing file system */
89 int	Oflag = 2;		/* file system format (1 => UFS1, 2 => UFS2) */
90 int	Rflag;			/* regression test */
91 int	Uflag;			/* enable soft updates for file system */
92 int	jflag;			/* enable soft updates journaling for filesys */
93 int	Xflag = 0;		/* exit in middle of newfs for testing */
94 int	Jflag;			/* enable gjournal for file system */
95 int	lflag;			/* enable multilabel for file system */
96 int	nflag;			/* do not create .snap directory */
97 int	tflag;			/* enable TRIM */
98 intmax_t fssize;		/* file system size */
99 off_t	mediasize;		/* device size */
100 int	sectorsize;		/* bytes/sector */
101 int	realsectorsize;		/* bytes/sector in hardware */
102 int	fsize = 0;		/* fragment size */
103 int	bsize = 0;		/* block size */
104 int	maxbsize = 0;		/* maximum clustering */
105 int	maxblkspercg = MAXBLKSPERCG; /* maximum blocks per cylinder group */
106 int	minfree = MINFREE;	/* free space threshold */
107 int	metaspace;		/* space held for metadata blocks */
108 int	opt = DEFAULTOPT;	/* optimization preference (space or time) */
109 int	density;		/* number of bytes per inode */
110 int	maxcontig = 0;		/* max contiguous blocks to allocate */
111 int	maxbpg;			/* maximum blocks per file in a cyl group */
112 int	avgfilesize = AVFILESIZ;/* expected average file size */
113 int	avgfilesperdir = AFPDIR;/* expected number of files per directory */
114 u_char	*volumelabel = NULL;	/* volume label for filesystem */
115 struct uufsd disk;		/* libufs disk structure */
116 
117 static char	device[MAXPATHLEN];
118 static u_char   bootarea[BBSIZE];
119 static int	is_file;		/* work on a file, not a device */
120 static char	*dkname;
121 static char	*disktype;
122 
123 static void getfssize(intmax_t *, const char *p, intmax_t, intmax_t);
124 static struct disklabel *getdisklabel(char *s);
125 static void usage(void);
126 static int expand_number_int(const char *buf, int *num);
127 
128 ufs2_daddr_t part_ofs; /* partition offset in blocks, used with files */
129 
130 int
131 main(int argc, char *argv[])
132 {
133 	struct partition *pp;
134 	struct disklabel *lp;
135 	struct stat st;
136 	char *cp, *special;
137 	intmax_t reserved;
138 	int ch, i, rval;
139 	char part_name;		/* partition name, default to full disk */
140 
141 	part_name = 'c';
142 	reserved = 0;
143 	while ((ch = getopt(argc, argv,
144 	    "EJL:NO:RS:T:UXa:b:c:d:e:f:g:h:i:jk:lm:no:p:r:s:t")) != -1)
145 		switch (ch) {
146 		case 'E':
147 			Eflag = 1;
148 			break;
149 		case 'J':
150 			Jflag = 1;
151 			break;
152 		case 'L':
153 			volumelabel = optarg;
154 			i = -1;
155 			while (isalnum(volumelabel[++i]) ||
156 			    volumelabel[i] == '_');
157 			if (volumelabel[i] != '\0') {
158 				errx(1, "bad volume label. Valid characters are alphanumerics.");
159 			}
160 			if (strlen(volumelabel) >= MAXVOLLEN) {
161 				errx(1, "bad volume label. Length is longer than %d.",
162 				    MAXVOLLEN);
163 			}
164 			Lflag = 1;
165 			break;
166 		case 'N':
167 			Nflag = 1;
168 			break;
169 		case 'O':
170 			if ((Oflag = atoi(optarg)) < 1 || Oflag > 2)
171 				errx(1, "%s: bad file system format value",
172 				    optarg);
173 			break;
174 		case 'R':
175 			Rflag = 1;
176 			break;
177 		case 'S':
178 			rval = expand_number_int(optarg, &sectorsize);
179 			if (rval < 0 || sectorsize <= 0)
180 				errx(1, "%s: bad sector size", optarg);
181 			break;
182 		case 'T':
183 			disktype = optarg;
184 			break;
185 		case 'j':
186 			jflag = 1;
187 			/* fall through to enable soft updates */
188 		case 'U':
189 			Uflag = 1;
190 			break;
191 		case 'X':
192 			Xflag++;
193 			break;
194 		case 'a':
195 			rval = expand_number_int(optarg, &maxcontig);
196 			if (rval < 0 || maxcontig <= 0)
197 				errx(1, "%s: bad maximum contiguous blocks",
198 				    optarg);
199 			break;
200 		case 'b':
201 			rval = expand_number_int(optarg, &bsize);
202 			if (rval < 0)
203 				 errx(1, "%s: bad block size",
204                                     optarg);
205 			if (bsize < MINBSIZE)
206 				errx(1, "%s: block size too small, min is %d",
207 				    optarg, MINBSIZE);
208 			if (bsize > MAXBSIZE)
209 				errx(1, "%s: block size too large, max is %d",
210 				    optarg, MAXBSIZE);
211 			break;
212 		case 'c':
213 			rval = expand_number_int(optarg, &maxblkspercg);
214 			if (rval < 0 || maxblkspercg <= 0)
215 				errx(1, "%s: bad blocks per cylinder group",
216 				    optarg);
217 			break;
218 		case 'd':
219 			rval = expand_number_int(optarg, &maxbsize);
220 			if (rval < 0 || maxbsize < MINBSIZE)
221 				errx(1, "%s: bad extent block size", optarg);
222 			break;
223 		case 'e':
224 			rval = expand_number_int(optarg, &maxbpg);
225 			if (rval < 0 || maxbpg <= 0)
226 			  errx(1, "%s: bad blocks per file in a cylinder group",
227 				    optarg);
228 			break;
229 		case 'f':
230 			rval = expand_number_int(optarg, &fsize);
231 			if (rval < 0 || fsize <= 0)
232 				errx(1, "%s: bad fragment size", optarg);
233 			break;
234 		case 'g':
235 			rval = expand_number_int(optarg, &avgfilesize);
236 			if (rval < 0 || avgfilesize <= 0)
237 				errx(1, "%s: bad average file size", optarg);
238 			break;
239 		case 'h':
240 			rval = expand_number_int(optarg, &avgfilesperdir);
241 			if (rval < 0 || avgfilesperdir <= 0)
242 			       errx(1, "%s: bad average files per dir", optarg);
243 			break;
244 		case 'i':
245 			rval = expand_number_int(optarg, &density);
246 			if (rval < 0 || density <= 0)
247 				errx(1, "%s: bad bytes per inode", optarg);
248 			break;
249 		case 'l':
250 			lflag = 1;
251 			break;
252 		case 'k':
253 			if ((metaspace = atoi(optarg)) < 0)
254 				errx(1, "%s: bad metadata space %%", optarg);
255 			if (metaspace == 0)
256 				/* force to stay zero in mkfs */
257 				metaspace = -1;
258 			break;
259 		case 'm':
260 			if ((minfree = atoi(optarg)) < 0 || minfree > 99)
261 				errx(1, "%s: bad free space %%", optarg);
262 			break;
263 		case 'n':
264 			nflag = 1;
265 			break;
266 		case 'o':
267 			if (strcmp(optarg, "space") == 0)
268 				opt = FS_OPTSPACE;
269 			else if (strcmp(optarg, "time") == 0)
270 				opt = FS_OPTTIME;
271 			else
272 				errx(1,
273 		"%s: unknown optimization preference: use `space' or `time'",
274 				    optarg);
275 			break;
276 		case 'r':
277 			errno = 0;
278 			reserved = strtoimax(optarg, &cp, 0);
279 			if (errno != 0 || cp == optarg ||
280 			    *cp != '\0' || reserved < 0)
281 				errx(1, "%s: bad reserved size", optarg);
282 			break;
283 		case 'p':
284 			is_file = 1;
285 			part_name = optarg[0];
286 			break;
287 
288 		case 's':
289 			errno = 0;
290 			fssize = strtoimax(optarg, &cp, 0);
291 			if (errno != 0 || cp == optarg ||
292 			    *cp != '\0' || fssize < 0)
293 				errx(1, "%s: bad file system size", optarg);
294 			break;
295 		case 't':
296 			tflag = 1;
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 == NULL) {
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 		if (pp->p_size == 0)
368 			errx(1, "%s: `%c' partition is unavailable",
369 			    special, *cp);
370 		if (pp->p_fstype == FS_BOOT)
371 			errx(1, "%s: `%c' partition overlaps boot program",
372 			    special, *cp);
373 		getfssize(&fssize, special, pp->p_size, reserved);
374 		if (sectorsize == 0)
375 			sectorsize = lp->d_secsize;
376 		if (fsize == 0)
377 			fsize = pp->p_fsize;
378 		if (bsize == 0)
379 			bsize = pp->p_frag * pp->p_fsize;
380 		if (is_file)
381 			part_ofs = pp->p_offset;
382 	}
383 	if (sectorsize <= 0)
384 		errx(1, "%s: no default sector size", special);
385 	if (fsize <= 0)
386 		fsize = MAX(DFL_FRAGSIZE, sectorsize);
387 	if (bsize <= 0)
388 		bsize = MIN(DFL_BLKSIZE, 8 * fsize);
389 	if (minfree < MINFREE && opt != FS_OPTSPACE) {
390 		fprintf(stderr, "Warning: changing optimization to space ");
391 		fprintf(stderr, "because minfree is less than %d%%\n", MINFREE);
392 		opt = FS_OPTSPACE;
393 	}
394 	realsectorsize = sectorsize;
395 	if (sectorsize != DEV_BSIZE) {		/* XXX */
396 		int secperblk = sectorsize / DEV_BSIZE;
397 
398 		sectorsize = DEV_BSIZE;
399 		fssize *= secperblk;
400 		if (pp != NULL)
401 			pp->p_size *= secperblk;
402 	}
403 	mkfs(pp, special);
404 	ufs_disk_close(&disk);
405 	if (!jflag)
406 		exit(0);
407 	if (execlp("tunefs", "newfs", "-j", "enable", special, NULL) < 0)
408 		err(1, "Cannot enable soft updates journaling, tunefs");
409 	/* NOT REACHED */
410 }
411 
412 void
413 getfssize(intmax_t *fsz, const char *s, intmax_t disksize, intmax_t reserved)
414 {
415 	intmax_t available;
416 
417 	available = disksize - reserved;
418 	if (available <= 0)
419 		errx(1, "%s: reserved not less than device size %jd",
420 		    s, disksize);
421 	if (*fsz == 0)
422 		*fsz = available;
423 	else if (*fsz > available)
424 		errx(1, "%s: maximum file system size is %jd",
425 		    s, available);
426 }
427 
428 struct disklabel *
429 getdisklabel(char *s)
430 {
431 	static struct disklabel lab;
432 	struct disklabel *lp;
433 
434 	if (is_file) {
435 		if (read(disk.d_fd, bootarea, BBSIZE) != BBSIZE)
436 			err(4, "cannot read bootarea");
437 		if (bsd_disklabel_le_dec(
438 		    bootarea + (0 /* labeloffset */ +
439 				1 /* labelsoffset */ * sectorsize),
440 		    &lab, MAXPARTITIONS))
441 			errx(1, "no valid label found");
442 
443 		lp = &lab;
444 		return &lab;
445 	}
446 
447 	if (disktype) {
448 		lp = getdiskbyname(disktype);
449 		if (lp != NULL)
450 			return (lp);
451 	}
452 	return (NULL);
453 }
454 
455 static void
456 usage()
457 {
458 	fprintf(stderr,
459 	    "usage: %s [ -fsoptions ] special-device%s\n",
460 	    getprogname(),
461 	    " [device-type]");
462 	fprintf(stderr, "where fsoptions are:\n");
463 	fprintf(stderr, "\t-E Erase previous disk content\n");
464 	fprintf(stderr, "\t-J Enable journaling via gjournal\n");
465 	fprintf(stderr, "\t-L volume label to add to superblock\n");
466 	fprintf(stderr,
467 	    "\t-N do not create file system, just print out parameters\n");
468 	fprintf(stderr, "\t-O file system format: 1 => UFS1, 2 => UFS2\n");
469 	fprintf(stderr, "\t-R regression test, suppress random factors\n");
470 	fprintf(stderr, "\t-S sector size\n");
471 	fprintf(stderr, "\t-T disktype\n");
472 	fprintf(stderr, "\t-U enable soft updates\n");
473 	fprintf(stderr, "\t-a maximum contiguous blocks\n");
474 	fprintf(stderr, "\t-b block size\n");
475 	fprintf(stderr, "\t-c blocks per cylinders group\n");
476 	fprintf(stderr, "\t-d maximum extent size\n");
477 	fprintf(stderr, "\t-e maximum blocks per file in a cylinder group\n");
478 	fprintf(stderr, "\t-f frag size\n");
479 	fprintf(stderr, "\t-g average file size\n");
480 	fprintf(stderr, "\t-h average files per directory\n");
481 	fprintf(stderr, "\t-i number of bytes per inode\n");
482 	fprintf(stderr, "\t-j enable soft updates journaling\n");
483 	fprintf(stderr, "\t-k space to hold for metadata blocks\n");
484 	fprintf(stderr, "\t-l enable multilabel MAC\n");
485 	fprintf(stderr, "\t-n do not create .snap directory\n");
486 	fprintf(stderr, "\t-m minimum free space %%\n");
487 	fprintf(stderr, "\t-o optimization preference (`space' or `time')\n");
488 	fprintf(stderr, "\t-p partition name (a..h)\n");
489 	fprintf(stderr, "\t-r reserved sectors at the end of device\n");
490 	fprintf(stderr, "\t-s file system size (sectors)\n");
491 	fprintf(stderr, "\t-t enable TRIM\n");
492 	exit(1);
493 }
494 
495 static int
496 expand_number_int(const char *buf, int *num)
497 {
498 	int64_t num64;
499 	int rval;
500 
501 	rval = expand_number(buf, &num64);
502 	if (rval < 0)
503 		return (rval);
504 	if (num64 > INT_MAX || num64 < INT_MIN) {
505 		errno = ERANGE;
506 		return (-1);
507 	}
508 	*num = (int)num64;
509 	return (0);
510 }
511