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