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