Merge branch 'vendor/TCSH'
[dragonfly.git] / sbin / newfs / mkfs.c
1 /*
2  * Copyright (c) 1980, 1989, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * @(#)mkfs.c   8.11 (Berkeley) 5/3/95
34  * $FreeBSD: src/sbin/newfs/mkfs.c,v 1.29.2.6 2001/09/21 19:15:21 dillon Exp $
35  * $DragonFly: src/sbin/newfs/mkfs.c,v 1.14 2007/05/20 19:29:21 dillon Exp $
36  */
37
38 #include "defs.h"
39
40 #include <stdlib.h>
41
42 /*
43  * make file system for cylinder-group style file systems
44  */
45
46 /*
47  * We limit the size of the inode map to be no more than a
48  * third of the cylinder group space, since we must leave at
49  * least an equal amount of space for the block map.
50  *
51  * N.B.: MAXIPG must be a multiple of INOPB(fs).
52  */
53 #define MAXIPG(fs)      roundup((fs)->fs_bsize * NBBY / 3, INOPB(fs))
54
55 #define UMASK           0755
56 #define MAXINOPB        (MAXBSIZE / sizeof(struct ufs1_dinode))
57 #define POWEROF2(num)   (((num) & ((num) - 1)) == 0)
58
59 #ifdef STANDALONE
60 #error "mkfs.c: STANDALONE compilation no longer supported"
61 #endif
62
63 /*
64  * variables set up by front end.
65  */
66 extern int      mfs;            /* run as the memory based filesystem */
67 extern char     *mfs_mtpt;      /* mount point for mfs          */ 
68 extern struct stat mfs_mtstat;  /* stat prior to mount          */
69 extern int      Nflag;          /* run mkfs without writing file system */
70 extern int      Oflag;          /* format as an 4.3BSD file system */
71 extern int      Uflag;          /* enable soft updates for file system */
72 extern u_long   fssize;         /* file system size */
73 extern int      ntracks;        /* # tracks/cylinder */
74 extern int      nsectors;       /* # sectors/track */
75 extern int      nphyssectors;   /* # sectors/track including spares */
76 extern int      secpercyl;      /* sectors per cylinder */
77 extern int      sectorsize;     /* bytes/sector */
78 extern int      realsectorsize; /* bytes/sector in hardware*/
79 extern int      rpm;            /* revolutions/minute of drive */
80 extern int      interleave;     /* hardware sector interleave */
81 extern int      trackskew;      /* sector 0 skew, per track */
82 extern int      fsize;          /* fragment size */
83 extern int      bsize;          /* block size */
84 extern int      cpg;            /* cylinders/cylinder group */
85 extern int      cpgflg;         /* cylinders/cylinder group flag was given */
86 extern int      minfree;        /* free space threshold */
87 extern int      opt;            /* optimization preference (space or time) */
88 extern int      density;        /* number of bytes per inode */
89 extern int      maxcontig;      /* max contiguous blocks to allocate */
90 extern int      rotdelay;       /* rotational delay between blocks */
91 extern int      maxbpg;         /* maximum blocks per file in a cyl group */
92 extern int      nrpos;          /* # of distinguished rotational positions */
93 extern int      bbsize;         /* boot block size */
94 extern int      sbsize;         /* superblock size */
95 extern int      avgfilesize;    /* expected average file size */
96 extern int      avgfilesperdir; /* expected number of files per directory */
97 extern caddr_t  membase;        /* start address of memory based filesystem */
98 extern char *   filename;
99 extern struct disktab geom;
100
101 extern void fatal(const char *fmt, ...);
102
103 union {
104         struct fs fs;
105         char pad[SBSIZE];
106 } fsun;
107 #define sblock  fsun.fs
108 struct  csum *fscs;
109
110 union {
111         struct cg cg;
112         char pad[MAXBSIZE];
113 } cgun;
114 #define acg     cgun.cg
115
116 struct ufs1_dinode zino[MAXBSIZE / sizeof(struct ufs1_dinode)];
117
118 int     fsi, fso;
119 static fsnode_t copyroot;
120 static fsnode_t copyhlinks;
121 #ifdef FSIRAND
122 int     randinit;
123 #endif
124 daddr_t alloc(int, int);
125 long    calcipg(long, long, off_t *);
126 static int charsperline(void);
127 void clrblock(struct fs *, unsigned char *, int);
128 void fsinit(time_t);
129 void initcg(int, time_t);
130 int isblock(struct fs *, unsigned char *, int);
131 void iput(struct ufs1_dinode *, ino_t);
132 int makedir(struct direct *, int);
133 void parentready(int);
134 void rdfs(daddr_t, int, char *);
135 void setblock(struct fs *, unsigned char *, int);
136 void started(int);
137 void wtfs(daddr_t, int, char *);
138 void wtfsflush(void);
139
140 int mfs_ppid = 0;
141 int parentready_signalled;
142
143 void
144 mkfs(char *fsys, int fi, int fo, const char *mfscopy)
145 {
146         long i, mincpc, mincpg, inospercg;
147         long cylno, rpos, blk, j, emitwarn = 0;
148         long used, mincpgcnt, bpcg;
149         off_t usedb;
150         long mapcramped, inodecramped;
151         long postblsize, rotblsize, totalsbsize;
152         int status, fd;
153         time_t utime;
154         quad_t sizepb;
155         int width;
156         char tmpbuf[100];       /* XXX this will break in about 2,500 years */
157
158         time(&utime);
159 #ifdef FSIRAND
160         if (!randinit) {
161                 randinit = 1;
162                 srandomdev();
163         }
164 #endif
165         if (mfs) {
166                 int omask;
167                 pid_t child;
168
169                 mfs_ppid = getpid();
170                 signal(SIGUSR1, parentready);
171                 if ((child = fork()) != 0) {
172                         /*
173                          * Parent
174                          */
175                         if (child == -1)
176                                 err(10, "mfs");
177                         if (mfscopy)
178                             copyroot = FSCopy(&copyhlinks, mfscopy);
179                         signal(SIGUSR1, started);
180                         kill(child, SIGUSR1);
181                         while (waitpid(child, &status, 0) != child)
182                                 ;
183                         exit(WEXITSTATUS(status));
184                         /* NOTREACHED */
185                 }
186
187                 /*
188                  * Child
189                  */
190                 omask = sigblock(sigmask(SIGUSR1));
191                 while (parentready_signalled == 0)
192                         sigpause(omask);
193                 sigsetmask(omask);
194                 if (filename != NULL) {
195                         unsigned char buf[BUFSIZ];
196                         unsigned long l, l1;
197                         ssize_t w;
198
199                         fd = open(filename, O_RDWR|O_TRUNC|O_CREAT, 0644);
200                         if(fd < 0)
201                                 err(12, "%s", filename);
202                         l1 = fssize * sectorsize;
203                         if (l1 > BUFSIZ)
204                                 l1 = BUFSIZ;
205                         for (l = 0; l < fssize * (u_long)sectorsize; l += l1) {
206                                 w = write(fd, buf, l1);
207                                 if (w < 0 || (u_long)w != l1)
208                                         err(12, "%s", filename);
209                         }
210                         membase = mmap(NULL, fssize * sectorsize,
211                                        PROT_READ|PROT_WRITE,
212                                        MAP_SHARED, fd, 0);
213                         if (membase == MAP_FAILED)
214                                 err(12, "mmap");
215                         close(fd);
216                 } else {
217                         membase = mmap(NULL, fssize * sectorsize,
218                                        PROT_READ|PROT_WRITE,
219                                        MAP_SHARED|MAP_ANON, -1, 0);
220                         if (membase == MAP_FAILED)
221                                 errx(13, "mmap (anonymous memory) failed");
222                 }
223         }
224         fsi = fi;
225         fso = fo;
226         if (Oflag) {
227                 sblock.fs_inodefmt = FS_42INODEFMT;
228                 sblock.fs_maxsymlinklen = 0;
229         } else {
230                 sblock.fs_inodefmt = FS_44INODEFMT;
231                 sblock.fs_maxsymlinklen = MAXSYMLINKLEN;
232         }
233         if (Uflag)
234                 sblock.fs_flags |= FS_DOSOFTDEP;
235         /*
236          * Validate the given file system size.
237          * Verify that its last block can actually be accessed.
238          */
239         if (fssize == 0)
240                 printf("preposterous size %lu\n", fssize), exit(13);
241         wtfs(fssize - (realsectorsize / DEV_BSIZE), realsectorsize,
242                  (char *)&sblock);
243         /*
244          * collect and verify the sector and track info
245          */
246         sblock.fs_nsect = nsectors;
247         sblock.fs_ntrak = ntracks;
248         if (sblock.fs_ntrak <= 0)
249                 printf("preposterous ntrak %d\n", sblock.fs_ntrak), exit(14);
250         if (sblock.fs_nsect <= 0)
251                 printf("preposterous nsect %d\n", sblock.fs_nsect), exit(15);
252         /*
253          * collect and verify the filesystem density info
254          */
255         sblock.fs_avgfilesize = avgfilesize;
256         sblock.fs_avgfpdir = avgfilesperdir;
257         if (sblock.fs_avgfilesize <= 0)
258                 printf("illegal expected average file size %d\n",
259                     sblock.fs_avgfilesize), exit(14);
260         if (sblock.fs_avgfpdir <= 0)
261                 printf("illegal expected number of files per directory %d\n",
262                     sblock.fs_avgfpdir), exit(15);
263         /*
264          * collect and verify the block and fragment sizes
265          */
266         sblock.fs_bsize = bsize;
267         sblock.fs_fsize = fsize;
268         if (!POWEROF2(sblock.fs_bsize)) {
269                 printf("block size must be a power of 2, not %d\n",
270                     sblock.fs_bsize);
271                 exit(16);
272         }
273         if (!POWEROF2(sblock.fs_fsize)) {
274                 printf("fragment size must be a power of 2, not %d\n",
275                     sblock.fs_fsize);
276                 exit(17);
277         }
278         if (sblock.fs_fsize < sectorsize) {
279                 printf("fragment size %d is too small, minimum is %d\n",
280                     sblock.fs_fsize, sectorsize);
281                 exit(18);
282         }
283         if (sblock.fs_bsize < MINBSIZE) {
284                 printf("block size %d is too small, minimum is %d\n",
285                     sblock.fs_bsize, MINBSIZE);
286                 exit(19);
287         }
288         if (sblock.fs_bsize < sblock.fs_fsize) {
289                 printf("block size (%d) cannot be smaller than fragment size (%d)\n",
290                     sblock.fs_bsize, sblock.fs_fsize);
291                 exit(20);
292         }
293         sblock.fs_bmask = ~(sblock.fs_bsize - 1);
294         sblock.fs_fmask = ~(sblock.fs_fsize - 1);
295         sblock.fs_qbmask = ~sblock.fs_bmask;
296         sblock.fs_qfmask = ~sblock.fs_fmask;
297         for (sblock.fs_bshift = 0, i = sblock.fs_bsize; i > 1; i >>= 1)
298                 sblock.fs_bshift++;
299         for (sblock.fs_fshift = 0, i = sblock.fs_fsize; i > 1; i >>= 1)
300                 sblock.fs_fshift++;
301         sblock.fs_frag = numfrags(&sblock, sblock.fs_bsize);
302         for (sblock.fs_fragshift = 0, i = sblock.fs_frag; i > 1; i >>= 1)
303                 sblock.fs_fragshift++;
304         if (sblock.fs_frag > MAXFRAG) {
305                 printf("fragment size %d is too small, minimum with block size %d is %d\n",
306                     sblock.fs_fsize, sblock.fs_bsize,
307                     sblock.fs_bsize / MAXFRAG);
308                 exit(21);
309         }
310         sblock.fs_nrpos = nrpos;
311         sblock.fs_nindir = sblock.fs_bsize / sizeof(daddr_t);
312         sblock.fs_inopb = sblock.fs_bsize / sizeof(struct ufs1_dinode);
313         sblock.fs_nspf = sblock.fs_fsize / sectorsize;
314         for (sblock.fs_fsbtodb = 0, i = NSPF(&sblock); i > 1; i >>= 1)
315                 sblock.fs_fsbtodb++;
316         sblock.fs_sblkno =
317             roundup(howmany(bbsize + sbsize, sblock.fs_fsize), sblock.fs_frag);
318         sblock.fs_cblkno = (daddr_t)(sblock.fs_sblkno +
319             roundup(howmany(sbsize, sblock.fs_fsize), sblock.fs_frag));
320         sblock.fs_iblkno = sblock.fs_cblkno + sblock.fs_frag;
321         sblock.fs_cgoffset = roundup(
322             howmany(sblock.fs_nsect, NSPF(&sblock)), sblock.fs_frag);
323         for (sblock.fs_cgmask = 0xffffffff, i = sblock.fs_ntrak; i > 1; i >>= 1)
324                 sblock.fs_cgmask <<= 1;
325         if (!POWEROF2(sblock.fs_ntrak))
326                 sblock.fs_cgmask <<= 1;
327         sblock.fs_maxfilesize = sblock.fs_bsize * NDADDR - 1;
328         for (sizepb = sblock.fs_bsize, i = 0; i < NIADDR; i++) {
329                 sizepb *= NINDIR(&sblock);
330                 sblock.fs_maxfilesize += sizepb;
331         }
332         /*
333          * Validate specified/determined secpercyl
334          * and calculate minimum cylinders per group.
335          */
336         sblock.fs_spc = secpercyl;
337         for (sblock.fs_cpc = NSPB(&sblock), i = sblock.fs_spc;
338              sblock.fs_cpc > 1 && (i & 1) == 0;
339              sblock.fs_cpc >>= 1, i >>= 1)
340                 /* void */;
341         mincpc = sblock.fs_cpc;
342         bpcg = sblock.fs_spc * sectorsize;
343         inospercg = roundup(bpcg / sizeof(struct ufs1_dinode), INOPB(&sblock));
344         if (inospercg > MAXIPG(&sblock))
345                 inospercg = MAXIPG(&sblock);
346         used = (sblock.fs_iblkno + inospercg / INOPF(&sblock)) * NSPF(&sblock);
347         mincpgcnt = howmany(sblock.fs_cgoffset * (~sblock.fs_cgmask) + used,
348             sblock.fs_spc);
349         mincpg = roundup(mincpgcnt, mincpc);
350         /*
351          * Ensure that cylinder group with mincpg has enough space
352          * for block maps.
353          */
354         sblock.fs_cpg = mincpg;
355         sblock.fs_ipg = inospercg;
356         if (maxcontig > 1)
357                 sblock.fs_contigsumsize = MIN(maxcontig, FS_MAXCONTIG);
358         mapcramped = 0;
359         while (CGSIZE(&sblock) > (uint32_t)sblock.fs_bsize) {
360                 mapcramped = 1;
361                 if (sblock.fs_bsize < MAXBSIZE) {
362                         sblock.fs_bsize <<= 1;
363                         if ((i & 1) == 0) {
364                                 i >>= 1;
365                         } else {
366                                 sblock.fs_cpc <<= 1;
367                                 mincpc <<= 1;
368                                 mincpg = roundup(mincpgcnt, mincpc);
369                                 sblock.fs_cpg = mincpg;
370                         }
371                         sblock.fs_frag <<= 1;
372                         sblock.fs_fragshift += 1;
373                         if (sblock.fs_frag <= MAXFRAG)
374                                 continue;
375                 }
376                 if (sblock.fs_fsize == sblock.fs_bsize) {
377                         printf("There is no block size that");
378                         printf(" can support this disk\n");
379                         exit(22);
380                 }
381                 sblock.fs_frag >>= 1;
382                 sblock.fs_fragshift -= 1;
383                 sblock.fs_fsize <<= 1;
384                 sblock.fs_nspf <<= 1;
385         }
386         /*
387          * Ensure that cylinder group with mincpg has enough space for inodes.
388          */
389         inodecramped = 0;
390         inospercg = calcipg(mincpg, bpcg, &usedb);
391         sblock.fs_ipg = inospercg;
392         while (inospercg > MAXIPG(&sblock)) {
393                 inodecramped = 1;
394                 if (mincpc == 1 || sblock.fs_frag == 1 ||
395                     sblock.fs_bsize == MINBSIZE)
396                         break;
397                 printf("With a block size of %d %s %d\n", sblock.fs_bsize,
398                        "minimum bytes per inode is",
399                        (int)((mincpg * (off_t)bpcg - usedb)
400                              / MAXIPG(&sblock) + 1));
401                 sblock.fs_bsize >>= 1;
402                 sblock.fs_frag >>= 1;
403                 sblock.fs_fragshift -= 1;
404                 mincpc >>= 1;
405                 sblock.fs_cpg = roundup(mincpgcnt, mincpc);
406                 if (CGSIZE(&sblock) > (uint32_t)sblock.fs_bsize) {
407                         sblock.fs_bsize <<= 1;
408                         break;
409                 }
410                 mincpg = sblock.fs_cpg;
411                 inospercg = calcipg(mincpg, bpcg, &usedb);
412                 sblock.fs_ipg = inospercg;
413         }
414         if (inodecramped) {
415                 if (inospercg > MAXIPG(&sblock)) {
416                         printf("Minimum bytes per inode is %d\n",
417                                (int)((mincpg * (off_t)bpcg - usedb)
418                                      / MAXIPG(&sblock) + 1));
419                 } else if (!mapcramped) {
420                         printf("With %d bytes per inode, ", density);
421                         printf("minimum cylinders per group is %ld\n", mincpg);
422                 }
423         }
424         if (mapcramped) {
425                 printf("With %d sectors per cylinder, ", sblock.fs_spc);
426                 printf("minimum cylinders per group is %ld\n", mincpg);
427         }
428         if (inodecramped || mapcramped) {
429                 if (sblock.fs_bsize != bsize)
430                         printf("%s to be changed from %d to %d\n",
431                             "This requires the block size",
432                             bsize, sblock.fs_bsize);
433                 if (sblock.fs_fsize != fsize)
434                         printf("\t%s to be changed from %d to %d\n",
435                             "and the fragment size",
436                             fsize, sblock.fs_fsize);
437                 exit(23);
438         }
439         /*
440          * Calculate the number of cylinders per group
441          */
442         sblock.fs_cpg = cpg;
443         if (sblock.fs_cpg % mincpc != 0) {
444                 printf("%s groups must have a multiple of %ld cylinders\n",
445                         cpgflg ? "Cylinder" : "Warning: cylinder", mincpc);
446                 sblock.fs_cpg = roundup(sblock.fs_cpg, mincpc);
447                 if (!cpgflg)
448                         cpg = sblock.fs_cpg;
449         }
450         /*
451          * Must ensure there is enough space for inodes.
452          */
453         sblock.fs_ipg = calcipg(sblock.fs_cpg, bpcg, &usedb);
454         while (sblock.fs_ipg > MAXIPG(&sblock)) {
455                 inodecramped = 1;
456                 sblock.fs_cpg -= mincpc;
457                 sblock.fs_ipg = calcipg(sblock.fs_cpg, bpcg, &usedb);
458         }
459         /*
460          * Must ensure there is enough space to hold block map.
461          */
462         while (CGSIZE(&sblock) > (uint32_t)sblock.fs_bsize) {
463                 mapcramped = 1;
464                 sblock.fs_cpg -= mincpc;
465                 sblock.fs_ipg = calcipg(sblock.fs_cpg, bpcg, &usedb);
466         }
467         sblock.fs_fpg = (sblock.fs_cpg * sblock.fs_spc) / NSPF(&sblock);
468         if ((sblock.fs_cpg * sblock.fs_spc) % NSPB(&sblock) != 0) {
469                 printf("panic (fs_cpg * fs_spc) %% NSPF != 0");
470                 exit(24);
471         }
472         if (sblock.fs_cpg < mincpg) {
473                 printf("cylinder groups must have at least %ld cylinders\n",
474                         mincpg);
475                 exit(25);
476         } else if (sblock.fs_cpg != cpg) {
477                 if (!cpgflg && !mfs)
478                         printf("Warning: ");
479                 else if (!mapcramped && !inodecramped)
480                         exit(26);
481                 if (!mfs) {
482                     if (mapcramped && inodecramped)
483                         printf("Block size and bytes per inode restrict");
484                     else if (mapcramped)
485                         printf("Block size restricts");
486                     else
487                         printf("Bytes per inode restrict");
488                     printf(" cylinders per group to %d.\n", sblock.fs_cpg);
489                 }
490                 if (cpgflg)
491                         exit(27);
492         }
493         sblock.fs_cgsize = fragroundup(&sblock, CGSIZE(&sblock));
494         /*
495          * Now have size for file system and nsect and ntrak.
496          * Determine number of cylinders and blocks in the file system.
497          */
498         sblock.fs_size = fssize = dbtofsb(&sblock, fssize);
499         sblock.fs_ncyl = fssize * NSPF(&sblock) / sblock.fs_spc;
500         if ((long)fssize * NSPF(&sblock) > sblock.fs_ncyl * sblock.fs_spc) {
501                 sblock.fs_ncyl++;
502                 emitwarn = 1;
503         }
504         if (sblock.fs_ncyl < 1) {
505                 printf("file systems must have at least one cylinder\n");
506                 exit(28);
507         }
508         /*
509          * Determine feasability/values of rotational layout tables.
510          *
511          * The size of the rotational layout tables is limited by the
512          * size of the superblock, SBSIZE. The amount of space available
513          * for tables is calculated as (SBSIZE - sizeof (struct fs)).
514          * The size of these tables is inversely proportional to the block
515          * size of the file system. The size increases if sectors per track
516          * are not powers of two, because more cylinders must be described
517          * by the tables before the rotational pattern repeats (fs_cpc).
518          */
519         sblock.fs_interleave = interleave;
520         sblock.fs_trackskew = trackskew;
521         sblock.fs_npsect = nphyssectors;
522         sblock.fs_postblformat = FS_DYNAMICPOSTBLFMT;
523         sblock.fs_sbsize = fragroundup(&sblock, sizeof(struct fs));
524         if (sblock.fs_sbsize > SBSIZE)
525                 sblock.fs_sbsize = SBSIZE;
526         if (sblock.fs_ntrak == 1) {
527                 sblock.fs_cpc = 0;
528                 goto next;
529         }
530         postblsize = sblock.fs_nrpos * sblock.fs_cpc * sizeof(int16_t);
531         rotblsize = sblock.fs_cpc * sblock.fs_spc / NSPB(&sblock);
532         totalsbsize = sizeof(struct fs) + rotblsize;
533         if (sblock.fs_nrpos == 8 && sblock.fs_cpc <= 16) {
534                 /* use old static table space */
535                 sblock.fs_postbloff = (char *)(&sblock.fs_opostbl[0][0]) -
536                     (char *)(&sblock.fs_firstfield);
537                 sblock.fs_rotbloff = &sblock.fs_space[0] -
538                     (u_char *)(&sblock.fs_firstfield);
539         } else {
540                 /* use dynamic table space */
541                 sblock.fs_postbloff = &sblock.fs_space[0] -
542                     (u_char *)(&sblock.fs_firstfield);
543                 sblock.fs_rotbloff = sblock.fs_postbloff + postblsize;
544                 totalsbsize += postblsize;
545         }
546         if (totalsbsize > SBSIZE ||
547             sblock.fs_nsect > (1 << NBBY) * NSPB(&sblock)) {
548                 printf("%s %s %d %s %d.%s",
549                     "Warning: insufficient space in super block for\n",
550                     "rotational layout tables with nsect", sblock.fs_nsect,
551                     "and ntrak", sblock.fs_ntrak,
552                     "\nFile system performance may be impaired.\n");
553                 sblock.fs_cpc = 0;
554                 goto next;
555         }
556         sblock.fs_sbsize = fragroundup(&sblock, totalsbsize);
557         if (sblock.fs_sbsize > SBSIZE)
558                 sblock.fs_sbsize = SBSIZE;
559         /*
560          * calculate the available blocks for each rotational position
561          */
562         for (cylno = 0; cylno < sblock.fs_cpc; cylno++)
563                 for (rpos = 0; rpos < sblock.fs_nrpos; rpos++)
564                         fs_postbl(&sblock, cylno)[rpos] = -1;
565         for (i = (rotblsize - 1) * sblock.fs_frag;
566              i >= 0; i -= sblock.fs_frag) {
567                 cylno = cbtocylno(&sblock, i);
568                 rpos = cbtorpos(&sblock, i);
569                 blk = fragstoblks(&sblock, i);
570                 if (fs_postbl(&sblock, cylno)[rpos] == -1)
571                         fs_rotbl(&sblock)[blk] = 0;
572                 else
573                         fs_rotbl(&sblock)[blk] =
574                             fs_postbl(&sblock, cylno)[rpos] - blk;
575                 fs_postbl(&sblock, cylno)[rpos] = blk;
576         }
577 next:
578         /*
579          * Compute/validate number of cylinder groups.
580          */
581         sblock.fs_ncg = sblock.fs_ncyl / sblock.fs_cpg;
582         if (sblock.fs_ncyl % sblock.fs_cpg)
583                 sblock.fs_ncg++;
584         sblock.fs_dblkno = sblock.fs_iblkno + sblock.fs_ipg / INOPF(&sblock);
585         i = MIN(~sblock.fs_cgmask, sblock.fs_ncg - 1);
586         if (cgdmin(&sblock, i) - cgbase(&sblock, i) >= sblock.fs_fpg) {
587                 printf("inode blocks/cyl group (%ld) >= data blocks (%ld)\n",
588                     cgdmin(&sblock, i) - cgbase(&sblock, i) / sblock.fs_frag,
589                     (long)(sblock.fs_fpg / sblock.fs_frag));
590                 printf("number of cylinders per cylinder group (%d) %s.\n",
591                     sblock.fs_cpg, "must be increased");
592                 exit(29);
593         }
594         j = sblock.fs_ncg - 1;
595         if ((i = fssize - j * sblock.fs_fpg) < sblock.fs_fpg &&
596             cgdmin(&sblock, j) - cgbase(&sblock, j) > i) {
597                 if (j == 0) {
598                         printf("Filesystem must have at least %d sectors\n",
599                             NSPF(&sblock) *
600                             (cgdmin(&sblock, 0) + 3 * sblock.fs_frag));
601                         exit(30);
602                 }
603                 printf(
604 "Warning: inode blocks/cyl group (%ld) >= data blocks (%ld) in last\n",
605                     (cgdmin(&sblock, j) - cgbase(&sblock, j)) / sblock.fs_frag,
606                     i / sblock.fs_frag);
607                 printf(
608 "    cylinder group. This implies %ld sector(s) cannot be allocated.\n",
609                     i * NSPF(&sblock));
610                 sblock.fs_ncg--;
611                 sblock.fs_ncyl -= sblock.fs_ncyl % sblock.fs_cpg;
612                 sblock.fs_size = fssize = sblock.fs_ncyl * sblock.fs_spc /
613                     NSPF(&sblock);
614                 emitwarn = 0;
615         }
616         if (emitwarn && !mfs) {
617                 printf("Warning: %lu sector(s) in last cylinder unallocated\n",
618                     sblock.fs_spc -
619                     (fssize * NSPF(&sblock) - (sblock.fs_ncyl - 1)
620                     * sblock.fs_spc));
621         }
622         /*
623          * fill in remaining fields of the super block
624          */
625         sblock.fs_csaddr = cgdmin(&sblock, 0);
626         sblock.fs_cssize =
627             fragroundup(&sblock, sblock.fs_ncg * sizeof(struct csum));
628         /*
629          * The superblock fields 'fs_csmask' and 'fs_csshift' are no
630          * longer used. However, we still initialise them so that the
631          * filesystem remains compatible with old kernels.
632          */
633         i = sblock.fs_bsize / sizeof(struct csum);
634         sblock.fs_csmask = ~(i - 1);
635         for (sblock.fs_csshift = 0; i > 1; i >>= 1)
636                 sblock.fs_csshift++;
637         fscs = (struct csum *)calloc(1, sblock.fs_cssize);
638         if (fscs == NULL)
639                 errx(31, "calloc failed");
640         sblock.fs_magic = FS_MAGIC;
641         sblock.fs_rotdelay = rotdelay;
642         sblock.fs_minfree = minfree;
643         sblock.fs_maxcontig = maxcontig;
644         sblock.fs_maxbpg = maxbpg;
645         sblock.fs_rps = rpm / 60;
646         sblock.fs_optim = opt;
647         sblock.fs_cgrotor = 0;
648         sblock.fs_cstotal.cs_ndir = 0;
649         sblock.fs_cstotal.cs_nbfree = 0;
650         sblock.fs_cstotal.cs_nifree = 0;
651         sblock.fs_cstotal.cs_nffree = 0;
652         sblock.fs_fmod = 0;
653         sblock.fs_ronly = 0;
654         sblock.fs_clean = 1;
655 #ifdef FSIRAND
656         sblock.fs_id[0] = (long)utime;
657         sblock.fs_id[1] = random();
658 #endif
659
660         /*
661          * Dump out summary information about file system.
662          */
663         if (!mfs) {
664                 printf("%s:\t%d sectors in %d %s of %d tracks, %d sectors\n",
665                     fsys, sblock.fs_size * NSPF(&sblock), sblock.fs_ncyl,
666                     "cylinders", sblock.fs_ntrak, sblock.fs_nsect);
667 #define B2MBFACTOR (1 / (1024.0 * 1024.0))
668                 printf("\t%.1fMB in %d cyl groups (%d c/g, %.2fMB/g, %d i/g)%s\n",
669                     (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
670                     sblock.fs_ncg, sblock.fs_cpg,
671                     (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
672                     sblock.fs_ipg,
673                         sblock.fs_flags & FS_DOSOFTDEP ? " SOFTUPDATES" : "");
674 #undef B2MBFACTOR
675         }
676         /*
677          * Now build the cylinders group blocks and
678          * then print out indices of cylinder groups.
679          */
680         if (!mfs)
681                 printf("super-block backups (for fsck -b #) at:\n");
682         i = 0;
683         width = charsperline();
684         for (cylno = 0; cylno < sblock.fs_ncg; cylno++) {
685                 initcg(cylno, utime);
686                 if (mfs)
687                         continue;
688                 j = snprintf(tmpbuf, sizeof(tmpbuf), " %ld%s",
689                     fsbtodb(&sblock, cgsblock(&sblock, cylno)),
690                     cylno < (sblock.fs_ncg-1) ? "," : "" );
691                 if (i + j >= width) {
692                         printf("\n");
693                         i = 0;
694                 }
695                 i += j;
696                 printf("%s", tmpbuf);
697                 fflush(stdout);
698         }
699         if (!mfs)
700                 printf("\n");
701         if (Nflag && !mfs)
702                 exit(0);
703         /*
704          * Now construct the initial file system,
705          * then write out the super-block.
706          */
707         fsinit(utime);
708         sblock.fs_time = utime;
709         wtfs((int)SBOFF / sectorsize, sbsize, (char *)&sblock);
710         for (i = 0; i < sblock.fs_cssize; i += sblock.fs_bsize)
711                 wtfs(fsbtodb(&sblock, sblock.fs_csaddr + numfrags(&sblock, i)),
712                         sblock.fs_cssize - i < sblock.fs_bsize ?
713                             sblock.fs_cssize - i : sblock.fs_bsize,
714                         ((char *)fscs) + i);
715         /*
716          * Write out the duplicate super blocks
717          */
718         for (cylno = 0; cylno < sblock.fs_ncg; cylno++)
719                 wtfs(fsbtodb(&sblock, cgsblock(&sblock, cylno)),
720                     sbsize, (char *)&sblock);
721         wtfsflush();
722
723         /*
724          * NOTE: we no longer update information in the disklabel
725          */
726
727         /*
728          * Notify parent process of success.
729          * Dissociate from session and tty.
730          *
731          * NOTE: We are the child and may receive a SIGINT due
732          *       to losing the tty session? XXX
733          */
734         if (mfs) {
735                 /* YYY */
736                 kill(mfs_ppid, SIGUSR1);
737                 setsid();
738                 close(0);
739                 close(1);
740                 close(2);
741                 chdir("/");
742                 /* returns to mount_mfs (newfs) and issues the mount */
743         }
744 }
745
746 /*
747  * Initialize a cylinder group.
748  */
749 void
750 initcg(int cylno, time_t utime)
751 {
752         daddr_t cbase, d, dlower, dupper, dmax, blkno;
753         long i;
754         unsigned long k;
755         struct csum *cs;
756 #ifdef FSIRAND
757         uint32_t j;
758 #endif
759
760         /*
761          * Determine block bounds for cylinder group.
762          * Allow space for super block summary information in first
763          * cylinder group.
764          */
765         cbase = cgbase(&sblock, cylno);
766         dmax = cbase + sblock.fs_fpg;
767         if (dmax > sblock.fs_size)
768                 dmax = sblock.fs_size;
769         dlower = cgsblock(&sblock, cylno) - cbase;
770         dupper = cgdmin(&sblock, cylno) - cbase;
771         if (cylno == 0)
772                 dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
773         cs = fscs + cylno;
774         memset(&acg, 0, sblock.fs_cgsize);
775         acg.cg_time = utime;
776         acg.cg_magic = CG_MAGIC;
777         acg.cg_cgx = cylno;
778         if (cylno == sblock.fs_ncg - 1)
779                 acg.cg_ncyl = sblock.fs_ncyl % sblock.fs_cpg;
780         else
781                 acg.cg_ncyl = sblock.fs_cpg;
782         acg.cg_niblk = sblock.fs_ipg;
783         acg.cg_ndblk = dmax - cbase;
784         if (sblock.fs_contigsumsize > 0)
785                 acg.cg_nclusterblks = acg.cg_ndblk / sblock.fs_frag;
786         acg.cg_btotoff = &acg.cg_space[0] - (u_char *)(&acg.cg_firstfield);
787         acg.cg_boff = acg.cg_btotoff + sblock.fs_cpg * sizeof(int32_t);
788         acg.cg_iusedoff = acg.cg_boff +
789                 sblock.fs_cpg * sblock.fs_nrpos * sizeof(u_int16_t);
790         acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, NBBY);
791         if (sblock.fs_contigsumsize <= 0) {
792                 acg.cg_nextfreeoff = acg.cg_freeoff +
793                    howmany(sblock.fs_cpg * sblock.fs_spc / NSPF(&sblock), NBBY);
794         } else {
795                 acg.cg_clustersumoff = acg.cg_freeoff + howmany
796                     (sblock.fs_cpg * sblock.fs_spc / NSPF(&sblock), NBBY) -
797                     sizeof(u_int32_t);
798                 acg.cg_clustersumoff =
799                     roundup(acg.cg_clustersumoff, sizeof(u_int32_t));
800                 acg.cg_clusteroff = acg.cg_clustersumoff +
801                     (sblock.fs_contigsumsize + 1) * sizeof(u_int32_t);
802                 acg.cg_nextfreeoff = acg.cg_clusteroff + howmany
803                     (sblock.fs_cpg * sblock.fs_spc / NSPB(&sblock), NBBY);
804         }
805         if (acg.cg_nextfreeoff - (long)(&acg.cg_firstfield) > sblock.fs_cgsize) {
806                 printf("Panic: cylinder group too big\n");
807                 exit(37);
808         }
809         acg.cg_cs.cs_nifree += sblock.fs_ipg;
810         if (cylno == 0) {
811                 for (k = 0; k < ROOTINO; k++) {
812                         setbit(cg_inosused(&acg), k);
813                         acg.cg_cs.cs_nifree--;
814                 }
815         }
816         for (i = 0; i < sblock.fs_ipg / INOPF(&sblock); i += sblock.fs_frag) {
817 #ifdef FSIRAND
818                 for (j = 0;
819                      j < sblock.fs_bsize / sizeof(struct ufs1_dinode);
820                      j++) {
821                         zino[j].di_gen = random();
822                 }
823 #endif
824                 wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
825                     sblock.fs_bsize, (char *)zino);
826         }
827         if (cylno > 0) {
828                 /*
829                  * In cylno 0, beginning space is reserved
830                  * for boot and super blocks.
831                  */
832                 for (d = 0; d < dlower; d += sblock.fs_frag) {
833                         blkno = d / sblock.fs_frag;
834                         setblock(&sblock, cg_blksfree(&acg), blkno);
835                         if (sblock.fs_contigsumsize > 0)
836                                 setbit(cg_clustersfree(&acg), blkno);
837                         acg.cg_cs.cs_nbfree++;
838                         cg_blktot(&acg)[cbtocylno(&sblock, d)]++;
839                         cg_blks(&sblock, &acg, cbtocylno(&sblock, d))
840                             [cbtorpos(&sblock, d)]++;
841                 }
842                 sblock.fs_dsize += dlower;
843         }
844         sblock.fs_dsize += acg.cg_ndblk - dupper;
845         if ((i = dupper % sblock.fs_frag)) {
846                 acg.cg_frsum[sblock.fs_frag - i]++;
847                 for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
848                         setbit(cg_blksfree(&acg), dupper);
849                         acg.cg_cs.cs_nffree++;
850                 }
851         }
852         for (d = dupper; d + sblock.fs_frag <= dmax - cbase; ) {
853                 blkno = d / sblock.fs_frag;
854                 setblock(&sblock, cg_blksfree(&acg), blkno);
855                 if (sblock.fs_contigsumsize > 0)
856                         setbit(cg_clustersfree(&acg), blkno);
857                 acg.cg_cs.cs_nbfree++;
858                 cg_blktot(&acg)[cbtocylno(&sblock, d)]++;
859                 cg_blks(&sblock, &acg, cbtocylno(&sblock, d))
860                     [cbtorpos(&sblock, d)]++;
861                 d += sblock.fs_frag;
862         }
863         if (d < dmax - cbase) {
864                 acg.cg_frsum[dmax - cbase - d]++;
865                 for (; d < dmax - cbase; d++) {
866                         setbit(cg_blksfree(&acg), d);
867                         acg.cg_cs.cs_nffree++;
868                 }
869         }
870         if (sblock.fs_contigsumsize > 0) {
871                 int32_t *sump = cg_clustersum(&acg);
872                 u_char *mapp = cg_clustersfree(&acg);
873                 int map = *mapp++;
874                 int bit = 1;
875                 int run = 0;
876
877                 for (i = 0; i < acg.cg_nclusterblks; i++) {
878                         if ((map & bit) != 0) {
879                                 run++;
880                         } else if (run != 0) {
881                                 if (run > sblock.fs_contigsumsize)
882                                         run = sblock.fs_contigsumsize;
883                                 sump[run]++;
884                                 run = 0;
885                         }
886                         if ((i & (NBBY - 1)) != (NBBY - 1)) {
887                                 bit <<= 1;
888                         } else {
889                                 map = *mapp++;
890                                 bit = 1;
891                         }
892                 }
893                 if (run != 0) {
894                         if (run > sblock.fs_contigsumsize)
895                                 run = sblock.fs_contigsumsize;
896                         sump[run]++;
897                 }
898         }
899         sblock.fs_cstotal.cs_ndir += acg.cg_cs.cs_ndir;
900         sblock.fs_cstotal.cs_nffree += acg.cg_cs.cs_nffree;
901         sblock.fs_cstotal.cs_nbfree += acg.cg_cs.cs_nbfree;
902         sblock.fs_cstotal.cs_nifree += acg.cg_cs.cs_nifree;
903         *cs = acg.cg_cs;
904         wtfs(fsbtodb(&sblock, cgtod(&sblock, cylno)),
905                 sblock.fs_bsize, (char *)&acg);
906 }
907
908 /*
909  * initialize the file system
910  */
911 struct ufs1_dinode node;
912
913 #ifdef LOSTDIR
914 #define PREDEFDIR 3
915 #else
916 #define PREDEFDIR 2
917 #endif
918
919 struct direct root_dir[] = {
920         { ROOTINO, sizeof(struct direct), DT_DIR, 1, "." },
921         { ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
922 #ifdef LOSTDIR
923         { LOSTFOUNDINO, sizeof(struct direct), DT_DIR, 10, "lost+found" },
924 #endif
925 };
926 struct odirect {
927         u_long  d_ino;
928         u_short d_reclen;
929         u_short d_namlen;
930         u_char  d_name[MAXNAMLEN + 1];
931 } oroot_dir[] = {
932         { ROOTINO, sizeof(struct direct), 1, "." },
933         { ROOTINO, sizeof(struct direct), 2, ".." },
934 #ifdef LOSTDIR
935         { LOSTFOUNDINO, sizeof(struct direct), 10, "lost+found" },
936 #endif
937 };
938 #ifdef LOSTDIR
939 struct direct lost_found_dir[] = {
940         { LOSTFOUNDINO, sizeof(struct direct), DT_DIR, 1, "." },
941         { ROOTINO, sizeof(struct direct), DT_DIR, 2, ".." },
942         { 0, DIRBLKSIZ, 0, 0, 0 },
943 };
944 struct odirect olost_found_dir[] = {
945         { LOSTFOUNDINO, sizeof(struct direct), 1, "." },
946         { ROOTINO, sizeof(struct direct), 2, ".." },
947         { 0, DIRBLKSIZ, 0, 0 },
948 };
949 #endif
950 char buf[MAXBSIZE];
951
952 void
953 fsinit(time_t utime)
954 {
955 #ifdef LOSTDIR
956         int i;
957 #endif
958
959         /*
960          * initialize the node
961          */
962         node.di_atime = utime;
963         node.di_mtime = utime;
964         node.di_ctime = utime;
965 #ifdef LOSTDIR
966         /*
967          * create the lost+found directory
968          */
969         if (Oflag) {
970                 makedir((struct direct *)olost_found_dir, 2);
971                 for (i = DIRBLKSIZ; i < sblock.fs_bsize; i += DIRBLKSIZ)
972                         memmove(&buf[i], &olost_found_dir[2],
973                             DIRSIZ(0, &olost_found_dir[2]));
974         } else {
975                 makedir(lost_found_dir, 2);
976                 for (i = DIRBLKSIZ; i < sblock.fs_bsize; i += DIRBLKSIZ)
977                         memmove(&buf[i], &lost_found_dir[2],
978                             DIRSIZ(0, &lost_found_dir[2]));
979         }
980         node.di_mode = IFDIR | UMASK;
981         node.di_nlink = 2;
982         node.di_size = sblock.fs_bsize;
983         node.di_db[0] = alloc(node.di_size, node.di_mode);
984         node.di_blocks = btodb(fragroundup(&sblock, node.di_size));
985         wtfs(fsbtodb(&sblock, node.di_db[0]), node.di_size, buf);
986         iput(&node, LOSTFOUNDINO);
987 #endif
988         /*
989          * create the root directory
990          */
991         if (mfs)
992                 node.di_mode = IFDIR | 01777;
993         else
994                 node.di_mode = IFDIR | UMASK;
995         node.di_nlink = PREDEFDIR;
996         if (Oflag)
997                 node.di_size = makedir((struct direct *)oroot_dir, PREDEFDIR);
998         else
999                 node.di_size = makedir(root_dir, PREDEFDIR);
1000         node.di_db[0] = alloc(sblock.fs_fsize, node.di_mode);
1001         node.di_blocks = btodb(fragroundup(&sblock, node.di_size));
1002         wtfs(fsbtodb(&sblock, node.di_db[0]), sblock.fs_fsize, buf);
1003         iput(&node, ROOTINO);
1004 }
1005
1006 /*
1007  * construct a set of directory entries in "buf".
1008  * return size of directory.
1009  */
1010 int
1011 makedir(struct direct *protodir, int entries)
1012 {
1013         char *cp;
1014         int i, spcleft;
1015
1016         spcleft = DIRBLKSIZ;
1017         for (cp = buf, i = 0; i < entries - 1; i++) {
1018                 protodir[i].d_reclen = DIRSIZ(0, &protodir[i]);
1019                 memmove(cp, &protodir[i], protodir[i].d_reclen);
1020                 cp += protodir[i].d_reclen;
1021                 spcleft -= protodir[i].d_reclen;
1022         }
1023         protodir[i].d_reclen = spcleft;
1024         memmove(cp, &protodir[i], DIRSIZ(0, &protodir[i]));
1025         return (DIRBLKSIZ);
1026 }
1027
1028 /*
1029  * allocate a block or frag
1030  */
1031 daddr_t
1032 alloc(int size, int mode)
1033 {
1034         int i, frag;
1035         daddr_t d, blkno;
1036
1037         rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
1038             (char *)&acg);
1039         if (acg.cg_magic != CG_MAGIC) {
1040                 printf("cg 0: bad magic number\n");
1041                 return (0);
1042         }
1043         if (acg.cg_cs.cs_nbfree == 0) {
1044                 printf("first cylinder group ran out of space\n");
1045                 return (0);
1046         }
1047         for (d = 0; d < acg.cg_ndblk; d += sblock.fs_frag)
1048                 if (isblock(&sblock, cg_blksfree(&acg), d / sblock.fs_frag))
1049                         goto goth;
1050         printf("internal error: can't find block in cyl 0\n");
1051         return (0);
1052 goth:
1053         blkno = fragstoblks(&sblock, d);
1054         clrblock(&sblock, cg_blksfree(&acg), blkno);
1055         if (sblock.fs_contigsumsize > 0)
1056                 clrbit(cg_clustersfree(&acg), blkno);
1057         acg.cg_cs.cs_nbfree--;
1058         sblock.fs_cstotal.cs_nbfree--;
1059         fscs[0].cs_nbfree--;
1060         if (mode & IFDIR) {
1061                 acg.cg_cs.cs_ndir++;
1062                 sblock.fs_cstotal.cs_ndir++;
1063                 fscs[0].cs_ndir++;
1064         }
1065         cg_blktot(&acg)[cbtocylno(&sblock, d)]--;
1066         cg_blks(&sblock, &acg, cbtocylno(&sblock, d))[cbtorpos(&sblock, d)]--;
1067         if (size != sblock.fs_bsize) {
1068                 frag = howmany(size, sblock.fs_fsize);
1069                 fscs[0].cs_nffree += sblock.fs_frag - frag;
1070                 sblock.fs_cstotal.cs_nffree += sblock.fs_frag - frag;
1071                 acg.cg_cs.cs_nffree += sblock.fs_frag - frag;
1072                 acg.cg_frsum[sblock.fs_frag - frag]++;
1073                 for (i = frag; i < sblock.fs_frag; i++)
1074                         setbit(cg_blksfree(&acg), d + i);
1075         }
1076         wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
1077             (char *)&acg);
1078         return (d);
1079 }
1080
1081 /*
1082  * Calculate number of inodes per group.
1083  */
1084 long
1085 calcipg(long cylspg, long bpcg, off_t *usedbp)
1086 {
1087         int i;
1088         long ipg, new_ipg, ncg, ncyl;
1089         off_t usedb;
1090
1091         /*
1092          * Prepare to scale by fssize / (number of sectors in cylinder groups).
1093          * Note that fssize is still in sectors, not filesystem blocks.
1094          */
1095         ncyl = howmany(fssize, (u_int)secpercyl);
1096         ncg = howmany(ncyl, cylspg);
1097         /*
1098          * Iterate a few times to allow for ipg depending on itself.
1099          */
1100         ipg = 0;
1101         for (i = 0; i < 10; i++) {
1102                 usedb = (sblock.fs_iblkno + ipg / INOPF(&sblock))
1103                         * NSPF(&sblock) * (off_t)sectorsize;
1104                 new_ipg = (cylspg * (quad_t)bpcg - usedb) / density * fssize
1105                           / ncg / secpercyl / cylspg;
1106                 new_ipg = roundup(new_ipg, INOPB(&sblock));
1107                 if (new_ipg == ipg)
1108                         break;
1109                 ipg = new_ipg;
1110         }
1111         *usedbp = usedb;
1112         return (ipg);
1113 }
1114
1115 /*
1116  * Allocate an inode on the disk
1117  */
1118 void
1119 iput(struct ufs1_dinode *ip, ino_t ino)
1120 {
1121         struct ufs1_dinode inobuf[MAXINOPB];
1122         daddr_t d;
1123         int c;
1124
1125 #ifdef FSIRAND
1126         ip->di_gen = random();
1127 #endif
1128         c = ino_to_cg(&sblock, ino);
1129         rdfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
1130             (char *)&acg);
1131         if (acg.cg_magic != CG_MAGIC) {
1132                 printf("cg 0: bad magic number\n");
1133                 exit(31);
1134         }
1135         acg.cg_cs.cs_nifree--;
1136         setbit(cg_inosused(&acg), ino);
1137         wtfs(fsbtodb(&sblock, cgtod(&sblock, 0)), sblock.fs_cgsize,
1138             (char *)&acg);
1139         sblock.fs_cstotal.cs_nifree--;
1140         fscs[0].cs_nifree--;
1141         if (ino >= (uint32_t)sblock.fs_ipg * (uint32_t)sblock.fs_ncg) {
1142                 printf("fsinit: inode value out of range (%ju).\n",
1143                     (uintmax_t)ino);
1144                 exit(32);
1145         }
1146         d = fsbtodb(&sblock, ino_to_fsba(&sblock, ino));
1147         rdfs(d, sblock.fs_bsize, (char *)inobuf);
1148         inobuf[ino_to_fsbo(&sblock, ino)] = *ip;
1149         wtfs(d, sblock.fs_bsize, (char *)inobuf);
1150 }
1151
1152 /*
1153  * Parent notifies child that it can proceed with the newfs and mount
1154  * operation (occurs after parent has copied the underlying filesystem
1155  * if the -C option was specified (for MFS), or immediately after the
1156  * parent forked the child otherwise).
1157  */
1158 void
1159 parentready(__unused int signo)
1160 {
1161         parentready_signalled = 1;
1162 }
1163
1164 /*
1165  * Notify parent process that the filesystem has created itself successfully.
1166  *
1167  * We have to wait until the mount has actually completed!
1168  */
1169 void
1170 started(__unused int signo)
1171 {
1172         int retry = 100;        /* 10 seconds, 100ms */
1173
1174         while (mfs_ppid && retry) {
1175                 struct stat st;
1176
1177                 if (
1178                     stat(mfs_mtpt, &st) < 0 ||
1179                     st.st_dev != mfs_mtstat.st_dev
1180                 ) {
1181                         break;
1182                 }
1183                 usleep(100*1000);
1184                 --retry;
1185         }
1186         if (retry == 0) {
1187                 fatal("mfs mount failed waiting for mount to go active");
1188         } else if (copyroot) {
1189                 FSPaste(mfs_mtpt, copyroot, copyhlinks);
1190         }
1191         exit(0);
1192 }
1193
1194 #ifdef __ELF__
1195 extern char *_etext;
1196 #define etext _etext
1197 #else
1198 extern char *etext;
1199 #endif
1200
1201 /*
1202  * read a block from the file system
1203  */
1204 void
1205 rdfs(daddr_t bno, int size, char *bf)
1206 {
1207         int n;
1208
1209         wtfsflush();
1210         if (mfs) {
1211                 memmove(bf, membase + bno * sectorsize, size);
1212                 return;
1213         }
1214         if (lseek(fsi, (off_t)bno * sectorsize, 0) < 0) {
1215                 printf("seek error: %ld\n", (long)bno);
1216                 err(33, "rdfs");
1217         }
1218         n = read(fsi, bf, size);
1219         if (n != size) {
1220                 printf("read error: %ld\n", (long)bno);
1221                 err(34, "rdfs");
1222         }
1223 }
1224
1225 #define WCSIZE (128 * 1024)
1226 daddr_t wc_sect;                /* units of sectorsize */
1227 int wc_end;                     /* bytes */
1228 static char wc[WCSIZE];         /* bytes */
1229
1230 /*
1231  * Flush dirty write behind buffer.
1232  */
1233 void
1234 wtfsflush(void)
1235 {
1236         int n;
1237         if (wc_end) {
1238                 if (lseek(fso, (off_t)wc_sect * sectorsize, SEEK_SET) < 0) {
1239                         printf("seek error: %ld\n", (long)wc_sect);
1240                         err(35, "wtfs - writecombine");
1241                 }
1242                 n = write(fso, wc, wc_end);
1243                 if (n != wc_end) {
1244                         printf("write error: %ld\n", (long)wc_sect);
1245                         err(36, "wtfs - writecombine");
1246                 }
1247                 wc_end = 0;
1248         }
1249 }
1250
1251 /*
1252  * write a block to the file system
1253  */
1254 void
1255 wtfs(daddr_t bno, int size, char *bf)
1256 {
1257         int n;
1258         int done;
1259
1260         if (mfs) {
1261                 memmove(membase + bno * sectorsize, bf, size);
1262                 return;
1263         }
1264         if (Nflag)
1265                 return;
1266         done = 0;
1267         if (wc_end == 0 && size <= WCSIZE) {
1268                 wc_sect = bno;
1269                 bcopy(bf, wc, size);
1270                 wc_end = size;
1271                 if (wc_end < WCSIZE)
1272                         return;
1273                 done = 1;
1274         }
1275         if ((off_t)wc_sect * sectorsize + wc_end == (off_t)bno * sectorsize &&
1276             wc_end + size <= WCSIZE) {
1277                 bcopy(bf, wc + wc_end, size);
1278                 wc_end += size;
1279                 if (wc_end < WCSIZE)
1280                         return;
1281                 done = 1;
1282         }
1283         wtfsflush();
1284         if (done)
1285                 return;
1286         if (lseek(fso, (off_t)bno * sectorsize, SEEK_SET) < 0) {
1287                 printf("seek error: %ld\n", (long)bno);
1288                 err(35, "wtfs");
1289         }
1290         n = write(fso, bf, size);
1291         if (n != size) {
1292                 printf("write error: fso %d blk %ld %d/%d\n", 
1293                         fso, (long)bno, n, size);
1294                 err(36, "wtfs");
1295         }
1296 }
1297
1298 /*
1299  * check if a block is available
1300  */
1301 int
1302 isblock(struct fs *fs, unsigned char *cp, int h)
1303 {
1304         unsigned char mask;
1305
1306         switch (fs->fs_frag) {
1307         case 8:
1308                 return (cp[h] == 0xff);
1309         case 4:
1310                 mask = 0x0f << ((h & 0x1) << 2);
1311                 return ((cp[h >> 1] & mask) == mask);
1312         case 2:
1313                 mask = 0x03 << ((h & 0x3) << 1);
1314                 return ((cp[h >> 2] & mask) == mask);
1315         case 1:
1316                 mask = 0x01 << (h & 0x7);
1317                 return ((cp[h >> 3] & mask) == mask);
1318         default:
1319                 fprintf(stderr, "isblock bad fs_frag %d\n", fs->fs_frag);
1320                 return (0);
1321         }
1322 }
1323
1324 /*
1325  * take a block out of the map
1326  */
1327 void
1328 clrblock(struct fs *fs, unsigned char *cp, int h)
1329 {
1330         switch ((fs)->fs_frag) {
1331         case 8:
1332                 cp[h] = 0;
1333                 return;
1334         case 4:
1335                 cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
1336                 return;
1337         case 2:
1338                 cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
1339                 return;
1340         case 1:
1341                 cp[h >> 3] &= ~(0x01 << (h & 0x7));
1342                 return;
1343         default:
1344                 fprintf(stderr, "clrblock bad fs_frag %d\n", fs->fs_frag);
1345                 return;
1346         }
1347 }
1348
1349 /*
1350  * put a block into the map
1351  */
1352 void
1353 setblock(struct fs *fs, unsigned char *cp, int h)
1354 {
1355         switch (fs->fs_frag) {
1356         case 8:
1357                 cp[h] = 0xff;
1358                 return;
1359         case 4:
1360                 cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
1361                 return;
1362         case 2:
1363                 cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
1364                 return;
1365         case 1:
1366                 cp[h >> 3] |= (0x01 << (h & 0x7));
1367                 return;
1368         default:
1369                 fprintf(stderr, "setblock bad fs_frag %d\n", fs->fs_frag);
1370                 return;
1371         }
1372 }
1373
1374 /*
1375  * Determine the number of characters in a
1376  * single line.
1377  */
1378
1379 static int
1380 charsperline(void)
1381 {
1382         int columns;
1383         char *cp;
1384         struct winsize ws;
1385
1386         columns = 0;
1387         if (ioctl(0, TIOCGWINSZ, &ws) != -1)
1388                 columns = ws.ws_col;
1389         if (columns == 0 && (cp = getenv("COLUMNS")))
1390                 columns = atoi(cp);
1391         if (columns == 0)
1392                 columns = 80;   /* last resort */
1393         return columns;
1394 }