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