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