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