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