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