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