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