Merge branch 'vendor/BYACC'
[dragonfly.git] / sbin / newfs_hammer2 / newfs_hammer2.c
1 /*
2  * Copyright (c) 2011-2015 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@dragonflybsd.org>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 #include <sys/types.h>
36 #include <sys/diskslice.h>
37 #include <sys/diskmbr.h>
38 #include <sys/stat.h>
39 #include <sys/time.h>
40 #include <sys/sysctl.h>
41 #include <sys/ioctl.h>
42 #include <vfs/hammer2/hammer2_xxhash.h>
43 #include <vfs/hammer2/hammer2_disk.h>
44
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <stdarg.h>
48 #include <stddef.h>
49 #include <unistd.h>
50 #include <string.h>
51 #include <errno.h>
52 #include <fcntl.h>
53 #include <assert.h>
54 #include <err.h>
55 #include <uuid.h>
56
57 #include "hammer2_subs.h"
58
59 #define MAXLABELS       HAMMER2_SET_COUNT
60
61 static hammer2_off_t check_volume(const char *path, int *fdp);
62 static int64_t getsize(const char *str, int64_t minval, int64_t maxval, int pw);
63 static uint64_t nowtime(void);
64 static int blkrefary_cmp(const void *b1, const void *b2);
65 static void usage(void);
66
67 static void format_hammer2(int fd, hammer2_off_t total_space,
68                                 hammer2_off_t free_space);
69 static void alloc_direct(hammer2_off_t *basep, hammer2_blockref_t *bref,
70                                 size_t bytes);
71
72 static int Hammer2Version = -1;
73 static uuid_t Hammer2_FSType;   /* static filesystem type id for HAMMER2 */
74 static uuid_t Hammer2_VolFSID;  /* unique filesystem id in volu header */
75 static uuid_t Hammer2_SupCLID;  /* PFS cluster id in super-root inode */
76 static uuid_t Hammer2_SupFSID;  /* PFS unique id in super-root inode */
77 static uuid_t Hammer2_PfsCLID[MAXLABELS];
78 static uuid_t Hammer2_PfsFSID[MAXLABELS];
79 static const char *Label[MAXLABELS];
80 static hammer2_off_t BootAreaSize;
81 static hammer2_off_t AuxAreaSize;
82 static int NLabels;
83
84 int
85 main(int ac, char **av)
86 {
87         uint32_t status;
88         hammer2_off_t total_space;
89         hammer2_off_t free_space;
90         hammer2_off_t reserved_space;
91         int ch;
92         int fd = -1;
93         int i;
94         int defaultlabels = 1;
95         char *vol_fsid = NULL;
96         char *sup_clid_name = NULL;
97         char *sup_fsid_name = NULL;
98         char *pfs_clid_name = NULL;
99         char *pfs_fsid_name = NULL;
100
101         Label[NLabels++] = "LOCAL";
102
103         /*
104          * Sanity check basic filesystem structures.  No cookies for us
105          * if it gets broken!
106          */
107         assert(sizeof(hammer2_volume_data_t) == HAMMER2_VOLUME_BYTES);
108         assert(sizeof(hammer2_inode_data_t) == HAMMER2_INODE_BYTES);
109         assert(sizeof(hammer2_blockref_t) == HAMMER2_BLOCKREF_BYTES);
110
111         /*
112          * Generate a filesystem id and lookup the filesystem type
113          */
114         srandomdev();
115         uuidgen(&Hammer2_VolFSID, 1);
116         uuidgen(&Hammer2_SupCLID, 1);
117         uuidgen(&Hammer2_SupFSID, 1);
118         uuid_from_string(HAMMER2_UUID_STRING, &Hammer2_FSType, &status);
119         /*uuid_name_lookup(&Hammer2_FSType, "DragonFly HAMMER2", &status);*/
120         if (status != uuid_s_ok) {
121                 errx(1, "uuids file does not have the DragonFly "
122                         "HAMMER2 filesystem type");
123         }
124
125         /*
126          * Parse arguments
127          */
128         while ((ch = getopt(ac, av, "L:b:r:V:")) != -1) {
129                 switch(ch) {
130                 case 'L':
131                         defaultlabels = 0;
132                         if (strcasecmp(optarg, "none") == 0) {
133                                 break;
134                         }
135                         if (NLabels >= MAXLABELS) {
136                                 errx(1, "Limit of %d local labels",
137                                      MAXLABELS - 1);
138                         }
139                         Label[NLabels++] = optarg;
140                         if (strlen(Label[NLabels-1]) > HAMMER2_INODE_MAXNAME) {
141                                 errx(1, "Volume label '%s' is too long "
142                                         "(64 chars max)\n", optarg);
143                         }
144                         break;
145                 case 'b':
146                         BootAreaSize = getsize(optarg,
147                                          HAMMER2_NEWFS_ALIGN,
148                                          HAMMER2_BOOT_MAX_BYTES, 2);
149                         break;
150                 case 'r':
151                         AuxAreaSize = getsize(optarg,
152                                          HAMMER2_NEWFS_ALIGN,
153                                          HAMMER2_AUX_MAX_BYTES, 2);
154                         break;
155                 case 'V':
156                         Hammer2Version = strtol(optarg, NULL, 0);
157                         if (Hammer2Version < HAMMER2_VOL_VERSION_MIN ||
158                             Hammer2Version >= HAMMER2_VOL_VERSION_WIP) {
159                                 errx(1,
160                                      "I don't understand how to format "
161                                      "HAMMER2 version %d\n",
162                                      Hammer2Version);
163                         }
164                         break;
165                 default:
166                         usage();
167                         break;
168                 }
169         }
170
171         /*
172          * Check Hammer2 version
173          */
174         if (Hammer2Version < 0) {
175                 size_t olen = sizeof(Hammer2Version);
176                 Hammer2Version = HAMMER2_VOL_VERSION_DEFAULT;
177                 if (sysctlbyname("vfs.hammer2.supported_version",
178                                  &Hammer2Version, &olen, NULL, 0) == 0) {
179                         if (Hammer2Version >= HAMMER2_VOL_VERSION_WIP) {
180                                 Hammer2Version = HAMMER2_VOL_VERSION_WIP - 1;
181                                 fprintf(stderr,
182                                         "newfs_hammer2: WARNING: HAMMER2 VFS "
183                                         "supports higher version than I "
184                                         "understand,\n"
185                                         "using version %d\n",
186                                         Hammer2Version);
187                         }
188                 } else {
189                         fprintf(stderr,
190                                 "newfs_hammer2: WARNING: HAMMER2 VFS not "
191                                 "loaded, cannot get version info.\n"
192                                 "Using version %d\n",
193                                 HAMMER2_VOL_VERSION_DEFAULT);
194                 }
195         }
196
197         ac -= optind;
198         av += optind;
199
200         if (ac != 1 || av[0][0] == 0) {
201                 fprintf(stderr, "Exactly one disk device must be specified\n");
202                 exit(1);
203         }
204
205         /*
206          * Adjust Label[] and NLabels.
207          */
208         if (defaultlabels) {
209                 char c = av[0][strlen(av[0]) - 1];
210                 if (c == 'a')
211                         Label[NLabels++] = "BOOT";
212                 else if (c == 'd')
213                         Label[NLabels++] = "ROOT";
214                 else
215                         Label[NLabels++] = "DATA";
216         }
217
218         /*
219          * Collect volume information.
220          */
221         total_space = check_volume(av[0], &fd);
222
223         /*
224          * ~typically 8MB alignment to avoid edge cases for reserved blocks
225          * and so raid stripes (if any) operate efficiently.
226          */
227         total_space &= ~HAMMER2_VOLUME_ALIGNMASK64;
228
229         /*
230          * Calculate defaults for the boot area size and round to the
231          * volume alignment boundary.
232          *
233          * NOTE: These areas are currently not used for booting but are
234          *       reserved for future filesystem expansion.
235          */
236         if (BootAreaSize == 0) {
237                 BootAreaSize = HAMMER2_BOOT_NOM_BYTES;
238                 while (BootAreaSize > total_space / 20)
239                         BootAreaSize >>= 1;
240                 if (BootAreaSize < HAMMER2_BOOT_MIN_BYTES)
241                         BootAreaSize = HAMMER2_BOOT_MIN_BYTES;
242         } else if (BootAreaSize < HAMMER2_BOOT_MIN_BYTES) {
243                 BootAreaSize = HAMMER2_BOOT_MIN_BYTES;
244         }
245         BootAreaSize = (BootAreaSize + HAMMER2_VOLUME_ALIGNMASK64) &
246                         ~HAMMER2_VOLUME_ALIGNMASK64;
247
248         /*
249          * Calculate defaults for the aux area size and round to the
250          * volume alignment boundary.
251          *
252          * NOTE: These areas are currently not used for logging but are
253          *       reserved for future filesystem expansion.
254          */
255         if (AuxAreaSize == 0) {
256                 AuxAreaSize = HAMMER2_AUX_NOM_BYTES;
257                 while (AuxAreaSize > total_space / 20)
258                         AuxAreaSize >>= 1;
259                 if (AuxAreaSize < HAMMER2_AUX_MIN_BYTES)
260                         AuxAreaSize = HAMMER2_AUX_MIN_BYTES;
261         } else if (AuxAreaSize < HAMMER2_AUX_MIN_BYTES) {
262                 AuxAreaSize = HAMMER2_AUX_MIN_BYTES;
263         }
264         AuxAreaSize = (AuxAreaSize + HAMMER2_VOLUME_ALIGNMASK64) &
265                        ~HAMMER2_VOLUME_ALIGNMASK64;
266
267         /*
268          * We'll need to stuff this in the volume header soon.
269          */
270         hammer2_uuid_to_str(&Hammer2_VolFSID, &vol_fsid);
271         hammer2_uuid_to_str(&Hammer2_SupCLID, &sup_clid_name);
272         hammer2_uuid_to_str(&Hammer2_SupFSID, &sup_fsid_name);
273
274         /*
275          * Calculate the amount of reserved space.  HAMMER2_ZONE_SEG (4MB)
276          * is reserved at the beginning of every 1GB of storage, rounded up.
277          * Thus a 200MB filesystem will still have a 4MB reserve area.
278          *
279          * We also include the boot and aux areas in the reserve.  The
280          * reserve is used to help 'df' calculate the amount of available
281          * space.
282          *
283          * XXX I kinda screwed up and made the reserved area on the LEVEL1
284          *     boundary rather than the ZONE boundary.  LEVEL1 is on 1GB
285          *     boundaries rather than 2GB boundaries.  Stick with the LEVEL1
286          *     boundary.
287          */
288         reserved_space = ((total_space + HAMMER2_FREEMAP_LEVEL1_MASK) /
289                           HAMMER2_FREEMAP_LEVEL1_SIZE) * HAMMER2_ZONE_SEG64;
290
291         free_space = total_space - reserved_space - BootAreaSize - AuxAreaSize;
292         if ((int64_t)free_space < 0) {
293                 fprintf(stderr, "Not enough free space\n");
294                 exit(1);
295         }
296
297         format_hammer2(fd, total_space, free_space);
298         fsync(fd);
299         close(fd);
300
301         printf("---------------------------------------------\n");
302         printf("version:          %d\n", Hammer2Version);
303         printf("total-size:       %s (%jd bytes)\n",
304                sizetostr(total_space),
305                (intmax_t)total_space);
306         printf("boot-area-size:   %s\n", sizetostr(BootAreaSize));
307         printf("aux-area-size:    %s\n", sizetostr(AuxAreaSize));
308         printf("topo-reserved:    %s\n", sizetostr(reserved_space));
309         printf("free-space:       %s\n", sizetostr(free_space));
310         printf("vol-fsid:         %s\n", vol_fsid);
311         printf("sup-clid:         %s\n", sup_clid_name);
312         printf("sup-fsid:         %s\n", sup_fsid_name);
313         for (i = 0; i < NLabels; ++i) {
314                 printf("PFS \"%s\"\n", Label[i]);
315                 hammer2_uuid_to_str(&Hammer2_PfsCLID[i], &pfs_clid_name);
316                 hammer2_uuid_to_str(&Hammer2_PfsFSID[i], &pfs_fsid_name);
317                 printf("    clid %s\n", pfs_clid_name);
318                 printf("    fsid %s\n", pfs_fsid_name);
319         }
320
321         free(vol_fsid);
322         free(sup_clid_name);
323         free(sup_fsid_name);
324         free(pfs_clid_name);
325         free(pfs_fsid_name);
326
327         return(0);
328 }
329
330 static
331 void
332 usage(void)
333 {
334         fprintf(stderr,
335                 "usage: newfs_hammer2 [-b bootsize] [-r auxsize] "
336                 "[-V version] [-L label ...] special\n"
337         );
338         exit(1);
339 }
340
341 /*
342  * Convert a string to a 64 bit signed integer with various requirements.
343  */
344 static int64_t
345 getsize(const char *str, int64_t minval, int64_t maxval, int powerof2)
346 {
347         int64_t val;
348         char *ptr;
349
350         val = strtoll(str, &ptr, 0);
351         switch(*ptr) {
352         case 't':
353         case 'T':
354                 val *= 1024;
355                 /* fall through */
356         case 'g':
357         case 'G':
358                 val *= 1024;
359                 /* fall through */
360         case 'm':
361         case 'M':
362                 val *= 1024;
363                 /* fall through */
364         case 'k':
365         case 'K':
366                 val *= 1024;
367                 break;
368         default:
369                 errx(1, "Unknown suffix in number '%s'\n", str);
370                 /* not reached */
371         }
372         if (ptr[1]) {
373                 errx(1, "Unknown suffix in number '%s'\n", str);
374                 /* not reached */
375         }
376         if (val < minval) {
377                 errx(1, "Value too small: %s, min is %s\n",
378                      str, sizetostr(minval));
379                 /* not reached */
380         }
381         if (val > maxval) {
382                 errx(1, "Value too large: %s, max is %s\n",
383                      str, sizetostr(maxval));
384                 /* not reached */
385         }
386         if ((powerof2 & 1) && (val ^ (val - 1)) != ((val << 1) - 1)) {
387                 errx(1, "Value not power of 2: %s\n", str);
388                 /* not reached */
389         }
390         if ((powerof2 & 2) && (val & HAMMER2_NEWFS_ALIGNMASK)) {
391                 errx(1, "Value not an integral multiple of %dK: %s",
392                      HAMMER2_NEWFS_ALIGN / 1024, str);
393                 /* not reached */
394         }
395         return(val);
396 }
397
398 static uint64_t
399 nowtime(void)
400 {
401         struct timeval tv;
402         uint64_t xtime;
403
404         gettimeofday(&tv, NULL);
405         xtime = tv.tv_sec * 1000000LL + tv.tv_usec;
406         return(xtime);
407 }
408
409 /*
410  * Figure out how big the volume is.
411  */
412 static
413 hammer2_off_t
414 check_volume(const char *path, int *fdp)
415 {
416         struct partinfo pinfo;
417         struct stat st;
418         hammer2_off_t size;
419
420         /*
421          * Get basic information about the volume
422          */
423         *fdp = open(path, O_RDWR);
424         if (*fdp < 0)
425                 err(1, "Unable to open %s R+W", path);
426         if (ioctl(*fdp, DIOCGPART, &pinfo) < 0) {
427                 /*
428                  * Allow the formatting of regular files as HAMMER2 volumes
429                  */
430                 if (fstat(*fdp, &st) < 0)
431                         err(1, "Unable to stat %s", path);
432                 if (!S_ISREG(st.st_mode))
433                         errx(1, "Unsupported file type for %s", path);
434                 size = st.st_size;
435         } else {
436                 /*
437                  * When formatting a block device as a HAMMER2 volume the
438                  * sector size must be compatible.  HAMMER2 uses 64K
439                  * filesystem buffers but logical buffers for direct I/O
440                  * can be as small as HAMMER2_LOGSIZE (16KB).
441                  */
442                 if (pinfo.reserved_blocks) {
443                         errx(1, "HAMMER2 cannot be placed in a partition "
444                                 "which overlaps the disklabel or MBR");
445                 }
446                 if (pinfo.media_blksize > HAMMER2_PBUFSIZE ||
447                     HAMMER2_PBUFSIZE % pinfo.media_blksize) {
448                         errx(1, "A media sector size of %d is not supported",
449                              pinfo.media_blksize);
450                 }
451                 size = pinfo.media_size;
452         }
453         printf("Volume %-15s size %s\n", path, sizetostr(size));
454         return (size);
455 }
456
457 /*
458  * Create the volume header, the super-root directory inode, and
459  * the writable snapshot subdirectory (named via the label) which
460  * is to be the initial mount point, or at least the first mount point.
461  * newfs_hammer2 doesn't format the freemap bitmaps for these.
462  *
463  * 0                      4MB
464  * [----reserved_area----][boot_area][aux_area]
465  * [[vol_hdr][freemap]...]                     [sroot][root][root]...
466  *     \                                        ^\     ^     ^
467  *      \--------------------------------------/  \---/-----/---...
468  *
469  * NOTE: The passed total_space is 8MB-aligned to avoid edge cases.
470  */
471 static
472 void
473 format_hammer2(int fd, hammer2_off_t total_space, hammer2_off_t free_space)
474 {
475         char *buf = malloc(HAMMER2_PBUFSIZE);
476         hammer2_volume_data_t *vol;
477         hammer2_inode_data_t *rawip;
478         hammer2_blockref_t sroot_blockref;
479         hammer2_blockref_t root_blockref[MAXLABELS];
480         uint64_t now;
481         hammer2_off_t volu_base = 0;
482         hammer2_off_t boot_base = HAMMER2_ZONE_SEG;
483         hammer2_off_t aux_base = boot_base + BootAreaSize;
484         hammer2_off_t alloc_base = aux_base + AuxAreaSize;
485         hammer2_off_t tmp_base;
486         size_t n;
487         int i;
488
489         /*
490          * Clear the entire reserve for the first 2G segment and
491          * make sure we can write to the last block.
492          */
493         bzero(buf, HAMMER2_PBUFSIZE);
494         tmp_base = volu_base;
495         for (i = 0; i < HAMMER2_ZONE_BLOCKS_SEG; ++i) {
496                 n = pwrite(fd, buf, HAMMER2_PBUFSIZE, tmp_base);
497                 if (n != HAMMER2_PBUFSIZE) {
498                         perror("write");
499                         exit(1);
500                 }
501                 tmp_base += HAMMER2_PBUFSIZE;
502         }
503
504         n = pwrite(fd, buf, HAMMER2_PBUFSIZE,
505                    volu_base + total_space - HAMMER2_PBUFSIZE);
506         if (n != HAMMER2_PBUFSIZE) {
507                 perror("write (at-end-of-volume)");
508                 exit(1);
509         }
510
511         /*
512          * Make sure alloc_base won't cross the reserved area at the
513          * beginning of each 1GB.
514          *
515          * Reserve space for the super-root inode and the root inode.
516          * Make sure they are in the same 64K block to simplify our code.
517          */
518         assert((alloc_base & HAMMER2_PBUFMASK) == 0);
519         assert(alloc_base < HAMMER2_FREEMAP_LEVEL1_SIZE);
520
521         /*
522          * Clear the boot/aux area.
523          */
524         for (tmp_base = boot_base; tmp_base < alloc_base;
525              tmp_base += HAMMER2_PBUFSIZE) {
526                 n = pwrite(fd, buf, HAMMER2_PBUFSIZE, tmp_base);
527                 if (n != HAMMER2_PBUFSIZE) {
528                         perror("write (boot/aux)");
529                         exit(1);
530                 }
531         }
532
533         now = nowtime();
534         alloc_base &= ~HAMMER2_PBUFMASK64;
535         alloc_direct(&alloc_base, &sroot_blockref, HAMMER2_INODE_BYTES);
536
537         for (i = 0; i < NLabels; ++i) {
538                 uuidgen(&Hammer2_PfsCLID[i], 1);
539                 uuidgen(&Hammer2_PfsFSID[i], 1);
540
541                 alloc_direct(&alloc_base, &root_blockref[i],
542                              HAMMER2_INODE_BYTES);
543                 assert(((sroot_blockref.data_off ^ root_blockref[i].data_off) &
544                         ~HAMMER2_PBUFMASK64) == 0);
545
546                 /*
547                  * Format the root directory inode, which is left empty.
548                  */
549                 rawip = (void *)(buf + (HAMMER2_OFF_MASK_LO &
550                                         root_blockref[i].data_off));
551                 rawip->meta.version = HAMMER2_INODE_VERSION_ONE;
552                 rawip->meta.ctime = now;
553                 rawip->meta.mtime = now;
554                 /* rawip->atime = now; NOT IMPL MUST BE ZERO */
555                 rawip->meta.btime = now;
556                 rawip->meta.type = HAMMER2_OBJTYPE_DIRECTORY;
557                 rawip->meta.mode = 0755;
558                 rawip->meta.inum = 1;   /* root inode, inumber 1 */
559                 rawip->meta.nlinks = 1; /* directory link count compat */
560
561                 rawip->meta.name_len = strlen(Label[i]);
562                 bcopy(Label[i], rawip->filename, rawip->meta.name_len);
563                 rawip->meta.name_key =
564                                 dirhash(rawip->filename, rawip->meta.name_len);
565
566                 /*
567                  * Compression mode and supported copyids.
568                  *
569                  * Do not allow compression when creating any "BOOT" label
570                  * (pfs-create also does the same if the pfs is named "BOOT")
571                  */
572                 if (strcasecmp(Label[i], "BOOT") == 0) {
573                         rawip->meta.comp_algo = HAMMER2_ENC_ALGO(
574                                                     HAMMER2_COMP_AUTOZERO);
575                         rawip->meta.check_algo = HAMMER2_ENC_ALGO(
576                                                     HAMMER2_CHECK_XXHASH64);
577                 } else {
578                         rawip->meta.comp_algo = HAMMER2_ENC_ALGO(
579                                                     HAMMER2_COMP_NEWFS_DEFAULT);
580                         rawip->meta.check_algo = HAMMER2_ENC_ALGO(
581                                                     HAMMER2_CHECK_XXHASH64);
582                 }
583
584                 /*
585                  * NOTE: We leave nmasters set to 0, which means that we
586                  *       don't know how many masters there are.  The quorum
587                  *       calculation will effectively be 1 ( 0 / 2 + 1 ).
588                  */
589                 rawip->meta.pfs_clid = Hammer2_PfsCLID[i];
590                 rawip->meta.pfs_fsid = Hammer2_PfsFSID[i];
591                 rawip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
592                 rawip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
593
594                 /* first allocatable inode number */
595                 rawip->meta.pfs_inum = 16;
596
597                 /* rawip->u.blockset is left empty */
598
599                 /*
600                  * The root blockref will be stored in the super-root inode as
601                  * the only directory entry.  The copyid here is the actual
602                  * copyid of the storage ref.
603                  *
604                  * The key field for a directory entry's blockref is
605                  * essentially the name key for the entry.
606                  */
607                 root_blockref[i].key = rawip->meta.name_key;
608                 root_blockref[i].copyid = HAMMER2_COPYID_LOCAL;
609                 root_blockref[i].keybits = 0;
610                 root_blockref[i].check.xxhash64.value =
611                                 XXH64(rawip, sizeof(*rawip), XXH_HAMMER2_SEED);
612                 root_blockref[i].type = HAMMER2_BREF_TYPE_INODE;
613                 root_blockref[i].methods =
614                                 HAMMER2_ENC_CHECK(HAMMER2_CHECK_XXHASH64) |
615                                 HAMMER2_ENC_COMP(HAMMER2_COMP_NONE);
616                 root_blockref[i].mirror_tid = 16;
617                 root_blockref[i].flags = HAMMER2_BREF_FLAG_PFSROOT;
618         }
619
620         /*
621          * Format the super-root directory inode, giving it one directory
622          * entry (root_blockref) and fixup the icrc method.
623          *
624          * The superroot contains one directory entry pointing at the root
625          * inode (named via the label).  Inodes contain one blockset which
626          * is fully associative so we can put the entry anywhere without
627          * having to worry about the hash.  Use index 0.
628          */
629         rawip = (void *)(buf + (HAMMER2_OFF_MASK_LO & sroot_blockref.data_off));
630         rawip->meta.version = HAMMER2_INODE_VERSION_ONE;
631         rawip->meta.ctime = now;
632         rawip->meta.mtime = now;
633         /* rawip->meta.atime = now; NOT IMPL MUST BE ZERO */
634         rawip->meta.btime = now;
635         rawip->meta.type = HAMMER2_OBJTYPE_DIRECTORY;
636         rawip->meta.mode = 0700;        /* super-root - root only */
637         rawip->meta.inum = 0;           /* super root inode, inumber 0 */
638         rawip->meta.nlinks = 2;         /* directory link count compat */
639
640         rawip->meta.name_len = 0;       /* super-root is unnamed */
641         rawip->meta.name_key = 0;
642
643         rawip->meta.comp_algo = HAMMER2_ENC_ALGO(HAMMER2_COMP_AUTOZERO);
644         rawip->meta.check_algo = HAMMER2_ENC_ALGO(HAMMER2_CHECK_XXHASH64);
645
646         /*
647          * The super-root is flagged as a PFS and typically given its own
648          * random FSID, making it possible to mirror an entire HAMMER2 disk
649          * snapshots and all if desired.  PFS ids are used to match up
650          * mirror sources and targets and cluster copy sources and targets.
651          *
652          * (XXX whole-disk logical mirroring is not really supported in
653          *  the first attempt because each PFS is in its own modify/mirror
654          *  transaction id domain, so normal mechanics cannot cross a PFS
655          *  boundary).
656          */
657         rawip->meta.pfs_clid = Hammer2_SupCLID;
658         rawip->meta.pfs_fsid = Hammer2_SupFSID;
659         rawip->meta.pfs_type = HAMMER2_PFSTYPE_SUPROOT;
660         snprintf((char*)rawip->filename, sizeof(rawip->filename), "SUPROOT");
661         rawip->meta.name_key = 0;
662         rawip->meta.name_len = strlen((char*)rawip->filename);
663
664         /* The super-root has an inode number of 0 */
665         rawip->meta.pfs_inum = 0;
666
667         /*
668          * Currently newfs_hammer2 just throws the PFS inodes into the
669          * top-level block table at the volume root and doesn't try to
670          * create an indirect block, so we are limited to ~4 at filesystem
671          * creation time.  More can be added after mounting.
672          */
673         qsort(root_blockref, NLabels, sizeof(root_blockref[0]), blkrefary_cmp);
674         for (i = 0; i < NLabels; ++i)
675                 rawip->u.blockset.blockref[i] = root_blockref[i];
676
677         /*
678          * The sroot blockref will be stored in the volume header.
679          */
680         sroot_blockref.copyid = HAMMER2_COPYID_LOCAL;
681         sroot_blockref.keybits = 0;
682         sroot_blockref.check.xxhash64.value =
683                                 XXH64(rawip, sizeof(*rawip), XXH_HAMMER2_SEED);
684         sroot_blockref.type = HAMMER2_BREF_TYPE_INODE;
685         sroot_blockref.methods = HAMMER2_ENC_CHECK(HAMMER2_CHECK_XXHASH64) |
686                                  HAMMER2_ENC_COMP(HAMMER2_COMP_AUTOZERO);
687         sroot_blockref.mirror_tid = 16;
688         rawip = NULL;
689
690         /*
691          * Write out the 64K HAMMER2 block containing the root and sroot.
692          */
693         assert((sroot_blockref.data_off & ~HAMMER2_PBUFMASK64) ==
694                 ((alloc_base - 1) & ~HAMMER2_PBUFMASK64));
695         n = pwrite(fd, buf, HAMMER2_PBUFSIZE,
696                    sroot_blockref.data_off & ~HAMMER2_PBUFMASK64);
697         if (n != HAMMER2_PBUFSIZE) {
698                 perror("write");
699                 exit(1);
700         }
701
702         /*
703          * Format the volume header.
704          *
705          * The volume header points to sroot_blockref.  Also be absolutely
706          * sure that allocator_beg is set.
707          */
708         assert(HAMMER2_VOLUME_BYTES <= HAMMER2_PBUFSIZE);
709         bzero(buf, HAMMER2_PBUFSIZE);
710         vol = (void *)buf;
711
712         vol->magic = HAMMER2_VOLUME_ID_HBO;
713         vol->boot_beg = boot_base;
714         vol->boot_end = boot_base + BootAreaSize;
715         vol->aux_beg = aux_base;
716         vol->aux_end = aux_base + AuxAreaSize;
717         vol->volu_size = total_space;
718         vol->version = Hammer2Version;
719         vol->flags = 0;
720
721         vol->fsid = Hammer2_VolFSID;
722         vol->fstype = Hammer2_FSType;
723
724         vol->peer_type = DMSG_PEER_HAMMER2;     /* LNK_CONN identification */
725
726         vol->allocator_size = free_space;
727         vol->allocator_free = free_space;
728         vol->allocator_beg = alloc_base;
729
730         vol->sroot_blockset.blockref[0] = sroot_blockref;
731         vol->mirror_tid = 16;   /* all blockref mirror TIDs set to 16 */
732         vol->freemap_tid = 16;  /* all blockref mirror TIDs set to 16 */
733         vol->icrc_sects[HAMMER2_VOL_ICRC_SECT1] =
734                         hammer2_icrc32((char *)vol + HAMMER2_VOLUME_ICRC1_OFF,
735                                        HAMMER2_VOLUME_ICRC1_SIZE);
736
737         /*
738          * Set ICRC_SECT0 after all remaining elements of sect0 have been
739          * populated in the volume header.  Note hat ICRC_SECT* (except for
740          * SECT0) are part of sect0.
741          */
742         vol->icrc_sects[HAMMER2_VOL_ICRC_SECT0] =
743                         hammer2_icrc32((char *)vol + HAMMER2_VOLUME_ICRC0_OFF,
744                                        HAMMER2_VOLUME_ICRC0_SIZE);
745         vol->icrc_volheader =
746                         hammer2_icrc32((char *)vol + HAMMER2_VOLUME_ICRCVH_OFF,
747                                        HAMMER2_VOLUME_ICRCVH_SIZE);
748
749         /*
750          * Write the volume header and all alternates.
751          */
752         for (i = 0; i < HAMMER2_NUM_VOLHDRS; ++i) {
753                 if (i * HAMMER2_ZONE_BYTES64 >= total_space)
754                         break;
755                 n = pwrite(fd, buf, HAMMER2_PBUFSIZE,
756                            volu_base + i * HAMMER2_ZONE_BYTES64);
757                 if (n != HAMMER2_PBUFSIZE) {
758                         perror("write");
759                         exit(1);
760                 }
761         }
762
763         /*
764          * Cleanup
765          */
766         free(buf);
767 }
768
769 static void
770 alloc_direct(hammer2_off_t *basep, hammer2_blockref_t *bref, size_t bytes)
771 {
772         int radix;
773
774         radix = 0;
775         assert(bytes);
776         while ((bytes & 1) == 0) {
777                 bytes >>= 1;
778                 ++radix;
779         }
780         assert(bytes == 1);
781         if (radix < HAMMER2_RADIX_MIN)
782                 radix = HAMMER2_RADIX_MIN;
783
784         bzero(bref, sizeof(*bref));
785         bref->data_off = *basep | radix;
786         bref->vradix = radix;
787
788         *basep += 1U << radix;
789 }
790
791 static int
792 blkrefary_cmp(const void *b1, const void *b2)
793 {
794         const hammer2_blockref_t *bref1 = b1;
795         const hammer2_blockref_t *bref2 = b2;
796
797         if (bref1->key < bref2->key)
798                 return(-1);
799         if (bref1->key > bref2->key)
800                 return(1);
801         return 0;
802 }