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