xref: /freebsd/sbin/newfs/newfs.c (revision 8ddb146abcdf061be9f2c0db7e391697dafad85c)
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/extattr.h>
69 #include <ufs/ufs/quota.h>
70 #include <ufs/ufs/ufsmount.h>
71 
72 #include <ctype.h>
73 #include <err.h>
74 #include <errno.h>
75 #include <inttypes.h>
76 #include <paths.h>
77 #include <stdarg.h>
78 #include <stdio.h>
79 #include <stdlib.h>
80 #include <string.h>
81 #include <syslog.h>
82 #include <unistd.h>
83 
84 #include <libutil.h>
85 
86 #include "newfs.h"
87 
88 int	Eflag;			/* Erase previous disk contents */
89 int	Lflag;			/* add a volume label */
90 int	Nflag;			/* run without writing file system */
91 int	Oflag = 2;		/* file system format (1 => UFS1, 2 => UFS2) */
92 int	Rflag;			/* regression test */
93 int	Uflag;			/* enable soft updates for file system */
94 int	jflag;			/* enable soft updates journaling for filesys */
95 int	Xflag = 0;		/* exit in middle of newfs for testing */
96 int	Jflag;			/* enable gjournal for file system */
97 int	lflag;			/* enable multilabel for file system */
98 int	nflag;			/* do not create .snap directory */
99 int	tflag;			/* enable TRIM */
100 intmax_t fssize;		/* file system size */
101 off_t	mediasize;		/* device size */
102 int	sectorsize;		/* bytes/sector */
103 int	realsectorsize;		/* bytes/sector in hardware */
104 int	fsize = 0;		/* fragment size */
105 int	bsize = 0;		/* block size */
106 int	maxbsize = 0;		/* maximum clustering */
107 int	maxblkspercg = MAXBLKSPERCG; /* maximum blocks per cylinder group */
108 int	minfree = MINFREE;	/* free space threshold */
109 int	metaspace;		/* space held for metadata blocks */
110 int	opt = DEFAULTOPT;	/* optimization preference (space or time) */
111 int	density;		/* number of bytes per inode */
112 int	maxcontig = 0;		/* max contiguous blocks to allocate */
113 int	maxbpg;			/* maximum blocks per file in a cyl group */
114 int	avgfilesize = AVFILESIZ;/* expected average file size */
115 int	avgfilesperdir = AFPDIR;/* expected number of files per directory */
116 u_char	*volumelabel = NULL;	/* volume label for filesystem */
117 struct uufsd disk;		/* libufs disk structure */
118 
119 static char	device[MAXPATHLEN];
120 static u_char   bootarea[BBSIZE];
121 static int	is_file;		/* work on a file, not a device */
122 static char	*dkname;
123 static char	*disktype;
124 
125 static void getfssize(intmax_t *, const char *p, intmax_t, intmax_t);
126 static struct disklabel *getdisklabel(void);
127 static void usage(void);
128 static int expand_number_int(const char *buf, int *num);
129 
130 ufs2_daddr_t part_ofs; /* partition offset in blocks, used with files */
131 
132 int
133 main(int argc, char *argv[])
134 {
135 	struct partition *pp;
136 	struct disklabel *lp;
137 	struct stat st;
138 	char *cp, *special;
139 	intmax_t reserved;
140 	int ch, i, rval;
141 	char part_name;		/* partition name, default to full disk */
142 
143 	part_name = 'c';
144 	reserved = 0;
145 	while ((ch = getopt(argc, argv,
146 	    "EJL:NO:RS:T:UXa:b:c:d:e:f:g:h:i:jk:lm:no:p:r:s:t")) != -1)
147 		switch (ch) {
148 		case 'E':
149 			Eflag = 1;
150 			break;
151 		case 'J':
152 			Jflag = 1;
153 			break;
154 		case 'L':
155 			volumelabel = optarg;
156 			i = -1;
157 			while (isalnum(volumelabel[++i]) ||
158 			    volumelabel[i] == '_' || volumelabel[i] == '-');
159 			if (volumelabel[i] != '\0') {
160 				errx(1, "bad volume label. Valid characters "
161 				    "are alphanumerics, dashes, and underscores.");
162 			}
163 			if (strlen(volumelabel) >= MAXVOLLEN) {
164 				errx(1, "bad volume label. Length is longer than %d.",
165 				    MAXVOLLEN);
166 			}
167 			Lflag = 1;
168 			break;
169 		case 'N':
170 			Nflag = 1;
171 			break;
172 		case 'O':
173 			if ((Oflag = atoi(optarg)) < 1 || Oflag > 2)
174 				errx(1, "%s: bad file system format value",
175 				    optarg);
176 			break;
177 		case 'R':
178 			Rflag = 1;
179 			break;
180 		case 'S':
181 			rval = expand_number_int(optarg, &sectorsize);
182 			if (rval < 0 || sectorsize <= 0)
183 				errx(1, "%s: bad sector size", optarg);
184 			break;
185 		case 'T':
186 			disktype = optarg;
187 			break;
188 		case 'j':
189 			jflag = 1;
190 			/* fall through to enable soft updates */
191 			/* FALLTHROUGH */
192 		case 'U':
193 			Uflag = 1;
194 			break;
195 		case 'X':
196 			Xflag++;
197 			break;
198 		case 'a':
199 			rval = expand_number_int(optarg, &maxcontig);
200 			if (rval < 0 || maxcontig <= 0)
201 				errx(1, "%s: bad maximum contiguous blocks",
202 				    optarg);
203 			break;
204 		case 'b':
205 			rval = expand_number_int(optarg, &bsize);
206 			if (rval < 0)
207 				 errx(1, "%s: bad block size",
208                                     optarg);
209 			if (bsize < MINBSIZE)
210 				errx(1, "%s: block size too small, min is %d",
211 				    optarg, MINBSIZE);
212 			if (bsize > MAXBSIZE)
213 				errx(1, "%s: block size too large, max is %d",
214 				    optarg, MAXBSIZE);
215 			break;
216 		case 'c':
217 			rval = expand_number_int(optarg, &maxblkspercg);
218 			if (rval < 0 || maxblkspercg <= 0)
219 				errx(1, "%s: bad blocks per cylinder group",
220 				    optarg);
221 			break;
222 		case 'd':
223 			rval = expand_number_int(optarg, &maxbsize);
224 			if (rval < 0 || maxbsize < MINBSIZE)
225 				errx(1, "%s: bad extent block size", optarg);
226 			break;
227 		case 'e':
228 			rval = expand_number_int(optarg, &maxbpg);
229 			if (rval < 0 || maxbpg <= 0)
230 			  errx(1, "%s: bad blocks per file in a cylinder group",
231 				    optarg);
232 			break;
233 		case 'f':
234 			rval = expand_number_int(optarg, &fsize);
235 			if (rval < 0 || fsize <= 0)
236 				errx(1, "%s: bad fragment size", optarg);
237 			break;
238 		case 'g':
239 			rval = expand_number_int(optarg, &avgfilesize);
240 			if (rval < 0 || avgfilesize <= 0)
241 				errx(1, "%s: bad average file size", optarg);
242 			break;
243 		case 'h':
244 			rval = expand_number_int(optarg, &avgfilesperdir);
245 			if (rval < 0 || avgfilesperdir <= 0)
246 			       errx(1, "%s: bad average files per dir", optarg);
247 			break;
248 		case 'i':
249 			rval = expand_number_int(optarg, &density);
250 			if (rval < 0 || density <= 0)
251 				errx(1, "%s: bad bytes per inode", optarg);
252 			break;
253 		case 'l':
254 			lflag = 1;
255 			break;
256 		case 'k':
257 			if ((metaspace = atoi(optarg)) < 0)
258 				errx(1, "%s: bad metadata space %%", optarg);
259 			if (metaspace == 0)
260 				/* force to stay zero in mkfs */
261 				metaspace = -1;
262 			break;
263 		case 'm':
264 			if ((minfree = atoi(optarg)) < 0 || minfree > 99)
265 				errx(1, "%s: bad free space %%", optarg);
266 			break;
267 		case 'n':
268 			nflag = 1;
269 			break;
270 		case 'o':
271 			if (strcmp(optarg, "space") == 0)
272 				opt = FS_OPTSPACE;
273 			else if (strcmp(optarg, "time") == 0)
274 				opt = FS_OPTTIME;
275 			else
276 				errx(1,
277 		"%s: unknown optimization preference: use `space' or `time'",
278 				    optarg);
279 			break;
280 		case 'r':
281 			errno = 0;
282 			reserved = strtoimax(optarg, &cp, 0);
283 			if (errno != 0 || cp == optarg ||
284 			    *cp != '\0' || reserved < 0)
285 				errx(1, "%s: bad reserved size", optarg);
286 			break;
287 		case 'p':
288 			is_file = 1;
289 			part_name = optarg[0];
290 			break;
291 
292 		case 's':
293 			errno = 0;
294 			fssize = strtoimax(optarg, &cp, 0);
295 			if (errno != 0 || cp == optarg ||
296 			    *cp != '\0' || fssize < 0)
297 				errx(1, "%s: bad file system size", optarg);
298 			break;
299 		case 't':
300 			tflag = 1;
301 			break;
302 		case '?':
303 		default:
304 			usage();
305 		}
306 	argc -= optind;
307 	argv += optind;
308 
309 	if (argc != 1)
310 		usage();
311 
312 	special = argv[0];
313 	if (!special[0])
314 		err(1, "empty file/special name");
315 	cp = strrchr(special, '/');
316 	if (cp == NULL) {
317 		/*
318 		 * No path prefix; try prefixing _PATH_DEV.
319 		 */
320 		snprintf(device, sizeof(device), "%s%s", _PATH_DEV, special);
321 		special = device;
322 	}
323 
324 	if (is_file) {
325 		/* bypass ufs_disk_fillout_blank */
326 		bzero( &disk, sizeof(disk));
327 		disk.d_bsize = 1;
328 		disk.d_name = special;
329 		disk.d_fd = open(special, O_RDONLY);
330 		if (disk.d_fd < 0 ||
331 		    (!Nflag && ufs_disk_write(&disk) == -1))
332 			errx(1, "%s: ", special);
333 	} else if (ufs_disk_fillout_blank(&disk, special) == -1 ||
334 	    (!Nflag && ufs_disk_write(&disk) == -1)) {
335 		if (disk.d_error != NULL)
336 			errx(1, "%s: %s", special, disk.d_error);
337 		else
338 			err(1, "%s", special);
339 	}
340 	if (fstat(disk.d_fd, &st) < 0)
341 		err(1, "%s", special);
342 	if ((st.st_mode & S_IFMT) != S_IFCHR) {
343 		warn("%s: not a character-special device", special);
344 		is_file = 1;	/* assume it is a file */
345 		dkname = special;
346 		if (sectorsize == 0)
347 			sectorsize = 512;
348 		mediasize = st.st_size;
349 		/* set fssize from the partition */
350 	} else {
351 	    if (sectorsize == 0)
352 		if (ioctl(disk.d_fd, DIOCGSECTORSIZE, &sectorsize) == -1)
353 		    sectorsize = 0;	/* back out on error for safety */
354 	    if (sectorsize && ioctl(disk.d_fd, DIOCGMEDIASIZE, &mediasize) != -1)
355 		getfssize(&fssize, special, mediasize / sectorsize, reserved);
356 	}
357 	pp = NULL;
358 	lp = getdisklabel();
359 	if (lp != NULL) {
360 		if (!is_file) /* already set for files */
361 			part_name = special[strlen(special) - 1];
362 		if ((part_name < 'a' || part_name - 'a' >= MAXPARTITIONS) &&
363 				!isdigit(part_name))
364 			errx(1, "%s: can't figure out file system partition",
365 					special);
366 		cp = &part_name;
367 		if (isdigit(*cp))
368 			pp = &lp->d_partitions[RAW_PART];
369 		else
370 			pp = &lp->d_partitions[*cp - 'a'];
371 		if (pp->p_size == 0)
372 			errx(1, "%s: `%c' partition is unavailable",
373 			    special, *cp);
374 		if (pp->p_fstype == FS_BOOT)
375 			errx(1, "%s: `%c' partition overlaps boot program",
376 			    special, *cp);
377 		getfssize(&fssize, special, pp->p_size, reserved);
378 		if (sectorsize == 0)
379 			sectorsize = lp->d_secsize;
380 		if (fsize == 0)
381 			fsize = pp->p_fsize;
382 		if (bsize == 0)
383 			bsize = pp->p_frag * pp->p_fsize;
384 		if (is_file)
385 			part_ofs = pp->p_offset;
386 	}
387 	if (sectorsize <= 0)
388 		errx(1, "%s: no default sector size", special);
389 	if (fsize <= 0)
390 		fsize = MAX(DFL_FRAGSIZE, sectorsize);
391 	if (bsize <= 0)
392 		bsize = MIN(DFL_BLKSIZE, 8 * fsize);
393 	if (minfree < MINFREE && opt != FS_OPTSPACE) {
394 		fprintf(stderr, "Warning: changing optimization to space ");
395 		fprintf(stderr, "because minfree is less than %d%%\n", MINFREE);
396 		opt = FS_OPTSPACE;
397 	}
398 	realsectorsize = sectorsize;
399 	if (sectorsize != DEV_BSIZE) {		/* XXX */
400 		int secperblk = sectorsize / DEV_BSIZE;
401 
402 		sectorsize = DEV_BSIZE;
403 		fssize *= secperblk;
404 		if (pp != NULL)
405 			pp->p_size *= secperblk;
406 	}
407 	mkfs(pp, special);
408 	ufs_disk_close(&disk);
409 	if (!jflag)
410 		exit(0);
411 	if (execlp("tunefs", "newfs", "-j", "enable", special, NULL) < 0)
412 		err(1, "Cannot enable soft updates journaling, tunefs");
413 	/* NOT REACHED */
414 }
415 
416 void
417 getfssize(intmax_t *fsz, const char *s, intmax_t disksize, intmax_t reserved)
418 {
419 	intmax_t available;
420 
421 	available = disksize - reserved;
422 	if (available <= 0)
423 		errx(1, "%s: reserved not less than device size %jd",
424 		    s, disksize);
425 	if (*fsz == 0)
426 		*fsz = available;
427 	else if (*fsz > available)
428 		errx(1, "%s: maximum file system size is %jd",
429 		    s, available);
430 }
431 
432 struct disklabel *
433 getdisklabel(void)
434 {
435 	static struct disklabel lab;
436 	struct disklabel *lp;
437 
438 	if (is_file) {
439 		if (read(disk.d_fd, bootarea, BBSIZE) != BBSIZE)
440 			err(4, "cannot read bootarea");
441 		if (bsd_disklabel_le_dec(
442 		    bootarea + (0 /* labeloffset */ +
443 				1 /* labelsoffset */ * sectorsize),
444 		    &lab, MAXPARTITIONS))
445 			errx(1, "no valid label found");
446 
447 		lp = &lab;
448 		return &lab;
449 	}
450 
451 	if (disktype) {
452 		lp = getdiskbyname(disktype);
453 		if (lp != NULL)
454 			return (lp);
455 	}
456 	return (NULL);
457 }
458 
459 static void
460 usage(void)
461 {
462 	fprintf(stderr,
463 	    "usage: %s [ -fsoptions ] special-device%s\n",
464 	    getprogname(),
465 	    " [device-type]");
466 	fprintf(stderr, "where fsoptions are:\n");
467 	fprintf(stderr, "\t-E Erase previous disk content\n");
468 	fprintf(stderr, "\t-J Enable journaling via gjournal\n");
469 	fprintf(stderr, "\t-L volume label to add to superblock\n");
470 	fprintf(stderr,
471 	    "\t-N do not create file system, just print out parameters\n");
472 	fprintf(stderr, "\t-O file system format: 1 => UFS1, 2 => UFS2\n");
473 	fprintf(stderr, "\t-R regression test, suppress random factors\n");
474 	fprintf(stderr, "\t-S sector size\n");
475 	fprintf(stderr, "\t-T disktype\n");
476 	fprintf(stderr, "\t-U enable soft updates\n");
477 	fprintf(stderr, "\t-a maximum contiguous blocks\n");
478 	fprintf(stderr, "\t-b block size\n");
479 	fprintf(stderr, "\t-c blocks per cylinders group\n");
480 	fprintf(stderr, "\t-d maximum extent size\n");
481 	fprintf(stderr, "\t-e maximum blocks per file in a cylinder group\n");
482 	fprintf(stderr, "\t-f frag size\n");
483 	fprintf(stderr, "\t-g average file size\n");
484 	fprintf(stderr, "\t-h average files per directory\n");
485 	fprintf(stderr, "\t-i number of bytes per inode\n");
486 	fprintf(stderr, "\t-j enable soft updates journaling\n");
487 	fprintf(stderr, "\t-k space to hold for metadata blocks\n");
488 	fprintf(stderr, "\t-l enable multilabel MAC\n");
489 	fprintf(stderr, "\t-n do not create .snap directory\n");
490 	fprintf(stderr, "\t-m minimum free space %%\n");
491 	fprintf(stderr, "\t-o optimization preference (`space' or `time')\n");
492 	fprintf(stderr, "\t-p partition name (a..h)\n");
493 	fprintf(stderr, "\t-r reserved sectors at the end of device\n");
494 	fprintf(stderr, "\t-s file system size (sectors)\n");
495 	fprintf(stderr, "\t-t enable TRIM\n");
496 	exit(1);
497 }
498 
499 static int
500 expand_number_int(const char *buf, int *num)
501 {
502 	int64_t num64;
503 	int rval;
504 
505 	rval = expand_number(buf, &num64);
506 	if (rval < 0)
507 		return (rval);
508 	if (num64 > INT_MAX || num64 < INT_MIN) {
509 		errno = ERANGE;
510 		return (-1);
511 	}
512 	*num = (int)num64;
513 	return (0);
514 }
515