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