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