sbin/newfs_hammer2: Drop unused GIG
[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 #define MAXLABELS       HAMMER2_SET_COUNT
58
59 #define hammer2_icrc32(buf, size)       iscsi_crc32((buf), (size))
60 #define hammer2_icrc32c(buf, size, crc) iscsi_crc32_ext((buf), (size), (crc))
61 uint32_t iscsi_crc32(const void *buf, size_t size);
62 uint32_t iscsi_crc32_ext(const void *buf, size_t size, uint32_t ocrc);
63
64 static hammer2_off_t check_volume(const char *path, int *fdp);
65 static int64_t getsize(const char *str, int64_t minval, int64_t maxval, int pw);
66 static const char *sizetostr(hammer2_off_t size);
67 static uint64_t nowtime(void);
68 static int blkrefary_cmp(const void *b1, const void *b2);
69 static void usage(void);
70
71 static void format_hammer2(int fd, hammer2_off_t total_space,
72                                 hammer2_off_t free_space);
73 static void alloc_direct(hammer2_off_t *basep, hammer2_blockref_t *bref,
74                                 size_t bytes);
75 static hammer2_key_t dirhash(const unsigned char *name, size_t len);
76
77 static int Hammer2Version = -1;
78 static int ForceOpt = 0;
79 static uuid_t Hammer2_FSType;   /* static filesystem type id for HAMMER2 */
80 static uuid_t Hammer2_VolFSID;  /* unique filesystem id in volu header */
81 static uuid_t Hammer2_SupCLID;  /* PFS cluster id in super-root inode */
82 static uuid_t Hammer2_SupFSID;  /* PFS unique id in super-root inode */
83 static uuid_t Hammer2_PfsCLID[MAXLABELS];
84 static uuid_t Hammer2_PfsFSID[MAXLABELS];
85 static const char *Label[MAXLABELS];
86 static hammer2_off_t BootAreaSize;
87 static hammer2_off_t AuxAreaSize;
88 static int NLabels;
89
90 int
91 main(int ac, char **av)
92 {
93         uint32_t status;
94         hammer2_off_t total_space;
95         hammer2_off_t free_space;
96         hammer2_off_t reserved_space;
97         int ch;
98         int fd = -1;
99         int i;
100         int defaultlabels = 1;
101         char *vol_fsid;
102         char *sup_clid_name;
103         char *sup_fsid_name;
104         char *pfs_clid_name;
105         char *pfs_fsid_name;
106
107         Label[NLabels++] = "LOCAL";
108
109         /*
110          * Sanity check basic filesystem structures.  No cookies for us
111          * if it gets broken!
112          */
113         assert(sizeof(hammer2_volume_data_t) == HAMMER2_VOLUME_BYTES);
114         assert(sizeof(hammer2_inode_data_t) == HAMMER2_INODE_BYTES);
115         assert(sizeof(hammer2_blockref_t) == HAMMER2_BLOCKREF_BYTES);
116
117         /*
118          * Generate a filesystem id and lookup the filesystem type
119          */
120         srandomdev();
121         uuidgen(&Hammer2_VolFSID, 1);
122         uuidgen(&Hammer2_SupCLID, 1);
123         uuidgen(&Hammer2_SupFSID, 1);
124         uuid_from_string(HAMMER2_UUID_STRING, &Hammer2_FSType, &status);
125         /*uuid_name_lookup(&Hammer2_FSType, "DragonFly HAMMER2", &status);*/
126         if (status != uuid_s_ok) {
127                 errx(1, "uuids file does not have the DragonFly "
128                         "HAMMER2 filesystem type");
129         }
130
131         /*
132          * Parse arguments
133          */
134         while ((ch = getopt(ac, av, "fL:b:m:r:V:")) != -1) {
135                 switch(ch) {
136                 case 'f':
137                         ForceOpt = 1;
138                         break;
139                 case 'L':
140                         defaultlabels = 0;
141                         if (strcasecmp(optarg, "none") == 0) {
142                                 break;
143                         }
144                         if (NLabels >= MAXLABELS) {
145                                 errx(1,
146                                      "Limit of %d local labels",
147                                      MAXLABELS - 1);
148                         }
149                         Label[NLabels++] = optarg;
150                         if (strlen(Label[NLabels-1]) > HAMMER2_INODE_MAXNAME) {
151                                 errx(1, "Volume label '%s' is too long "
152                                         "(64 chars max)\n", optarg);
153                         }
154                         break;
155                 case 'b':
156                         BootAreaSize = getsize(optarg,
157                                          HAMMER2_NEWFS_ALIGN,
158                                          HAMMER2_BOOT_MAX_BYTES, 2);
159                         break;
160                 case 'r':
161                         AuxAreaSize = getsize(optarg,
162                                          HAMMER2_NEWFS_ALIGN,
163                                          HAMMER2_REDO_MAX_BYTES, 2);
164                         break;
165                 case 'V':
166                         Hammer2Version = strtol(optarg, NULL, 0);
167                         if (Hammer2Version < HAMMER2_VOL_VERSION_MIN ||
168                             Hammer2Version >= HAMMER2_VOL_VERSION_WIP) {
169                                 errx(1,
170                                      "I don't understand how to format "
171                                      "HAMMER2 version %d\n",
172                                      Hammer2Version);
173                         }
174                         break;
175                 default:
176                         usage();
177                         break;
178                 }
179         }
180
181         /*
182          * Check Hammer2 version
183          */
184         if (Hammer2Version < 0) {
185                 size_t olen = sizeof(Hammer2Version);
186                 Hammer2Version = HAMMER2_VOL_VERSION_DEFAULT;
187                 if (sysctlbyname("vfs.hammer2.supported_version",
188                                  &Hammer2Version, &olen, NULL, 0) == 0) {
189                         if (Hammer2Version >= HAMMER2_VOL_VERSION_WIP) {
190                                 Hammer2Version = HAMMER2_VOL_VERSION_WIP - 1;
191                                 fprintf(stderr,
192                                         "newfs_hammer2: WARNING: HAMMER2 VFS "
193                                         "supports higher version than I "
194                                         "understand,\n"
195                                         "using version %d\n",
196                                         Hammer2Version);
197                         }
198                 } else {
199                         fprintf(stderr,
200                                 "newfs_hammer2: WARNING: HAMMER2 VFS not "
201                                 "loaded, cannot get version info.\n"
202                                 "Using version %d\n",
203                                 HAMMER2_VOL_VERSION_DEFAULT);
204                 }
205         }
206
207         ac -= optind;
208         av += optind;
209
210         if (ac != 1 || av[0][0] == 0) {
211                 fprintf(stderr, "Exactly one disk device must be specified\n");
212                 exit(1);
213         }
214
215         /*
216          * Adjust Label[] and NLabels.
217          */
218         if (defaultlabels) {
219                 char c = av[0][strlen(av[0]) - 1];
220                 if (c == 'a')
221                         Label[NLabels++] = "BOOT";
222                 else if (c == 'd')
223                         Label[NLabels++] = "ROOT";
224                 else
225                         Label[NLabels++] = "DATA";
226         }
227
228         /*
229          * Collect volume information.
230          */
231         total_space = check_volume(av[0], &fd);
232
233         /*
234          * ~typically 8MB alignment to avoid edge cases for reserved blocks
235          * and so raid stripes (if any) operate efficiently.
236          */
237         total_space &= ~HAMMER2_VOLUME_ALIGNMASK64;
238
239         /*
240          * Calculate defaults for the boot area size and round to the
241          * volume alignment boundary.
242          *
243          * NOTE: These areas are currently not used for booting but are
244          *       reserved for future filesystem expansion.
245          */
246         if (BootAreaSize == 0) {
247                 BootAreaSize = HAMMER2_BOOT_NOM_BYTES;
248                 while (BootAreaSize > total_space / 20)
249                         BootAreaSize >>= 1;
250                 if (BootAreaSize < HAMMER2_BOOT_MIN_BYTES)
251                         BootAreaSize = HAMMER2_BOOT_MIN_BYTES;
252         } else if (BootAreaSize < HAMMER2_BOOT_MIN_BYTES) {
253                 BootAreaSize = HAMMER2_BOOT_MIN_BYTES;
254         }
255         BootAreaSize = (BootAreaSize + HAMMER2_VOLUME_ALIGNMASK64) &
256                        ~HAMMER2_VOLUME_ALIGNMASK64;
257
258         /*
259          * Calculate defaults for the redo area size and round to the
260          * volume alignment boundary.
261          *
262          * NOTE: These areas are currently not used for logging but are
263          *       reserved for future filesystem expansion.
264          */
265         if (AuxAreaSize == 0) {
266                 AuxAreaSize = HAMMER2_REDO_NOM_BYTES;
267                 while (AuxAreaSize > total_space / 20)
268                         AuxAreaSize >>= 1;
269                 if (AuxAreaSize < HAMMER2_REDO_MIN_BYTES)
270                         AuxAreaSize = HAMMER2_REDO_MIN_BYTES;
271         } else if (AuxAreaSize < HAMMER2_REDO_MIN_BYTES) {
272                 AuxAreaSize = HAMMER2_REDO_MIN_BYTES;
273         }
274         AuxAreaSize = (AuxAreaSize + HAMMER2_VOLUME_ALIGNMASK64) &
275                        ~HAMMER2_VOLUME_ALIGNMASK64;
276
277         /*
278          * We'll need to stuff this in the volume header soon.
279          */
280         uuid_to_string(&Hammer2_VolFSID, &vol_fsid, &status);
281         uuid_to_string(&Hammer2_SupCLID, &sup_clid_name, &status);
282         uuid_to_string(&Hammer2_SupFSID, &sup_fsid_name, &status);
283
284         /*
285          * Calculate the amount of reserved space.  HAMMER2_ZONE_SEG (4MB)
286          * is reserved at the beginning of every 2GB of storage, rounded up.
287          * Thus a 200MB filesystem will still have a 4MB reserve area.
288          *
289          * We also include the boot and redo areas in the reserve.  The
290          * reserve is used to help 'df' calculate the amount of available
291          * space.
292          *
293          * XXX I kinda screwed up and made the reserved area on the LEVEL1
294          *     boundary rather than the ZONE boundary.  LEVEL1 is on 1GB
295          *     boundaries rather than 2GB boundaries.  Stick with the LEVEL1
296          *     boundary.
297          */
298         reserved_space = ((total_space + HAMMER2_FREEMAP_LEVEL1_MASK) /
299                           HAMMER2_FREEMAP_LEVEL1_SIZE) * HAMMER2_ZONE_SEG64;
300
301         free_space = total_space - reserved_space -
302                      BootAreaSize - AuxAreaSize;
303
304         format_hammer2(fd, total_space, free_space);
305         fsync(fd);
306         close(fd);
307
308         printf("---------------------------------------------\n");
309         printf("version:          %d\n", Hammer2Version);
310         printf("total-size:       %s (%jd bytes)\n",
311                sizetostr(total_space),
312                (intmax_t)total_space);
313         printf("boot-area-size:   %s\n", sizetostr(BootAreaSize));
314         printf("aux-area-size:    %s\n", sizetostr(AuxAreaSize));
315         printf("topo-reserved:    %s\n", sizetostr(reserved_space));
316         printf("free-space:       %s\n", sizetostr(free_space));
317         printf("vol-fsid:         %s\n", vol_fsid);
318         printf("sup-clid:         %s\n", sup_clid_name);
319         printf("sup-fsid:         %s\n", sup_fsid_name);
320         for (i = 0; i < NLabels; ++i) {
321                 printf("PFS \"%s\"\n", Label[i]);
322                 uuid_to_string(&Hammer2_PfsCLID[i], &pfs_clid_name, &status);
323                 uuid_to_string(&Hammer2_PfsFSID[i], &pfs_fsid_name, &status);
324                 printf("    clid %s\n", pfs_clid_name);
325                 printf("    fsid %s\n", pfs_fsid_name);
326         }
327         printf("\n");
328
329         free(vol_fsid);
330         free(sup_clid_name);
331         free(sup_fsid_name);
332         free(pfs_clid_name);
333         free(pfs_fsid_name);
334
335         return(0);
336 }
337
338 static
339 void
340 usage(void)
341 {
342         fprintf(stderr,
343                 "usage: newfs_hammer2 -L label [-f] [-b bootsize] "
344                 "[-r redosize] [-V version] special ...\n"
345         );
346         exit(1);
347 }
348
349 /*
350  * Convert the size in bytes to a human readable string.
351  */
352 static
353 const char *
354 sizetostr(hammer2_off_t size)
355 {
356         static char buf[32];
357
358         if (size < 1024 / 2) {
359                 snprintf(buf, sizeof(buf), "%6.2f", (double)size);
360         } else if (size < 1024 * 1024 / 2) {
361                 snprintf(buf, sizeof(buf), "%6.2fKB",
362                         (double)size / 1024);
363         } else if (size < 1024 * 1024 * 1024LL / 2) {
364                 snprintf(buf, sizeof(buf), "%6.2fMB",
365                         (double)size / (1024 * 1024));
366         } else if (size < 1024 * 1024 * 1024LL * 1024LL / 2) {
367                 snprintf(buf, sizeof(buf), "%6.2fGB",
368                         (double)size / (1024 * 1024 * 1024LL));
369         } else {
370                 snprintf(buf, sizeof(buf), "%6.2fTB",
371                         (double)size / (1024 * 1024 * 1024LL * 1024LL));
372         }
373         return(buf);
374 }
375
376 /*
377  * Convert a string to a 64 bit signed integer with various requirements.
378  */
379 static int64_t
380 getsize(const char *str, int64_t minval, int64_t maxval, int powerof2)
381 {
382         int64_t val;
383         char *ptr;
384
385         val = strtoll(str, &ptr, 0);
386         switch(*ptr) {
387         case 't':
388         case 'T':
389                 val *= 1024;
390                 /* fall through */
391         case 'g':
392         case 'G':
393                 val *= 1024;
394                 /* fall through */
395         case 'm':
396         case 'M':
397                 val *= 1024;
398                 /* fall through */
399         case 'k':
400         case 'K':
401                 val *= 1024;
402                 break;
403         default:
404                 errx(1, "Unknown suffix in number '%s'\n", str);
405                 /* not reached */
406         }
407         if (ptr[1]) {
408                 errx(1, "Unknown suffix in number '%s'\n", str);
409                 /* not reached */
410         }
411         if (val < minval) {
412                 errx(1, "Value too small: %s, min is %s\n",
413                      str, sizetostr(minval));
414                 /* not reached */
415         }
416         if (val > maxval) {
417                 errx(1, "Value too large: %s, max is %s\n",
418                      str, sizetostr(maxval));
419                 /* not reached */
420         }
421         if ((powerof2 & 1) && (val ^ (val - 1)) != ((val << 1) - 1)) {
422                 errx(1, "Value not power of 2: %s\n", str);
423                 /* not reached */
424         }
425         if ((powerof2 & 2) && (val & HAMMER2_NEWFS_ALIGNMASK)) {
426                 errx(1, "Value not an integral multiple of %dK: %s",
427                      HAMMER2_NEWFS_ALIGN / 1024, str);
428                 /* not reached */
429         }
430         return(val);
431 }
432
433 static uint64_t
434 nowtime(void)
435 {
436         struct timeval tv;
437         uint64_t xtime;
438
439         gettimeofday(&tv, NULL);
440         xtime = tv.tv_sec * 1000000LL + tv.tv_usec;
441         return(xtime);
442 }
443
444 /*
445  * Figure out how big the volume is.
446  */
447 static
448 hammer2_off_t
449 check_volume(const char *path, int *fdp)
450 {
451         struct partinfo pinfo;
452         struct stat st;
453         hammer2_off_t size;
454
455         /*
456          * Get basic information about the volume
457          */
458         *fdp = open(path, O_RDWR);
459         if (*fdp < 0)
460                 err(1, "Unable to open %s R+W", path);
461         if (ioctl(*fdp, DIOCGPART, &pinfo) < 0) {
462                 /*
463                  * Allow the formatting of regular files as HAMMER2 volumes
464                  */
465                 if (fstat(*fdp, &st) < 0)
466                         err(1, "Unable to stat %s", path);
467                 if (!S_ISREG(st.st_mode))
468                         errx(1, "Unsupported file type for %s", path);
469                 size = st.st_size;
470         } else {
471                 /*
472                  * When formatting a block device as a HAMMER2 volume the
473                  * sector size must be compatible.  HAMMER2 uses 64K
474                  * filesystem buffers but logical buffers for direct I/O
475                  * can be as small as HAMMER2_LOGSIZE (16KB).
476                  */
477                 if (pinfo.reserved_blocks) {
478                         errx(1, "HAMMER2 cannot be placed in a partition "
479                                 "which overlaps the disklabel or MBR");
480                 }
481                 if (pinfo.media_blksize > HAMMER2_PBUFSIZE ||
482                     HAMMER2_PBUFSIZE % pinfo.media_blksize) {
483                         errx(1, "A media sector size of %d is not supported",
484                              pinfo.media_blksize);
485                 }
486                 size = pinfo.media_size;
487         }
488         printf("Volume %-15s size %s\n", path, sizetostr(size));
489         return (size);
490 }
491
492 /*
493  * Create the volume header, the super-root directory inode, and
494  * the writable snapshot subdirectory (named via the label) which
495  * is to be the initial mount point, or at least the first mount point.
496  *
497  * [----reserved_area----][boot_area][aux_area]
498  * [[vol_hdr]...         ]                     [sroot][root]...
499  *
500  * Also format the allocation map.
501  *
502  * NOTE: The passed total_space is 8MB-aligned to avoid edge cases.
503  */
504 static
505 void
506 format_hammer2(int fd, hammer2_off_t total_space, hammer2_off_t free_space)
507 {
508         char *buf = malloc(HAMMER2_PBUFSIZE);
509         hammer2_volume_data_t *vol;
510         hammer2_inode_data_t *rawip;
511         hammer2_blockref_t sroot_blockref;
512         hammer2_blockref_t root_blockref[MAXLABELS];
513         uint64_t now;
514         hammer2_off_t volu_base = 0;
515         hammer2_off_t boot_base = HAMMER2_ZONE_SEG;
516         hammer2_off_t aux_base = boot_base + BootAreaSize;
517         hammer2_off_t alloc_base = aux_base + AuxAreaSize;
518         hammer2_off_t tmp_base;
519         size_t n;
520         int i;
521
522         /*
523          * Clear the entire reserve for the first 2G segment and
524          * make sure we can write to the last block.
525          */
526         bzero(buf, HAMMER2_PBUFSIZE);
527         tmp_base = volu_base;
528         for (i = 0; i < HAMMER2_ZONE_BLOCKS_SEG; ++i) {
529                 n = pwrite(fd, buf, HAMMER2_PBUFSIZE, tmp_base);
530                 if (n != HAMMER2_PBUFSIZE) {
531                         perror("write");
532                         exit(1);
533                 }
534                 tmp_base += HAMMER2_PBUFSIZE;
535         }
536
537         n = pwrite(fd, buf, HAMMER2_PBUFSIZE,
538                    volu_base + total_space - HAMMER2_PBUFSIZE);
539         if (n != HAMMER2_PBUFSIZE) {
540                 perror("write (at-end-of-volume)");
541                 exit(1);
542         }
543
544         /*
545          * Make sure alloc_base won't cross the reserved area at the
546          * beginning of each 2GB zone.
547          *
548          * Reserve space for the super-root inode and the root inode.
549          * Make sure they are in the same 64K block to simplify our code.
550          */
551         assert((alloc_base & HAMMER2_PBUFMASK) == 0);
552         assert(alloc_base < HAMMER2_ZONE_BYTES64 - HAMMER2_ZONE_SEG);
553         now = nowtime();
554         bzero(buf, HAMMER2_PBUFSIZE);
555
556         alloc_base &= ~HAMMER2_PBUFMASK64;
557         alloc_direct(&alloc_base, &sroot_blockref, HAMMER2_INODE_BYTES);
558
559         for (i = 0; i < NLabels; ++i) {
560                 uuidgen(&Hammer2_PfsCLID[i], 1);
561                 uuidgen(&Hammer2_PfsFSID[i], 1);
562
563                 alloc_direct(&alloc_base, &root_blockref[i],
564                              HAMMER2_INODE_BYTES);
565                 assert(((sroot_blockref.data_off ^ root_blockref[i].data_off) &
566                         HAMMER2_OFF_MASK_HI) == 0);
567
568                 /*
569                  * Format the root directory inode, which is left empty.
570                  */
571                 rawip = (void *)(buf + (HAMMER2_OFF_MASK_LO &
572                                         root_blockref[i].data_off));
573                 rawip->meta.version = HAMMER2_INODE_VERSION_ONE;
574                 rawip->meta.ctime = now;
575                 rawip->meta.mtime = now;
576                 /* rawip->atime = now; NOT IMPL MUST BE ZERO */
577                 rawip->meta.btime = now;
578                 rawip->meta.type = HAMMER2_OBJTYPE_DIRECTORY;
579                 rawip->meta.mode = 0755;
580                 rawip->meta.inum = 1;   /* root inode, inumber 1 */
581                 rawip->meta.nlinks = 1; /* directory link count compat */
582
583                 rawip->meta.name_len = strlen(Label[i]);
584                 bcopy(Label[i], rawip->filename, rawip->meta.name_len);
585                 rawip->meta.name_key =
586                                 dirhash(rawip->filename, rawip->meta.name_len);
587
588                 /*
589                  * Compression mode and supported copyids.
590                  *
591                  * Do not allow compression when creating any "BOOT" label
592                  * (pfs-create also does the same if the pfs is named "BOOT")
593                  */
594                 if (strcasecmp(Label[i], "BOOT") == 0) {
595                         rawip->meta.comp_algo = HAMMER2_ENC_ALGO(
596                                                     HAMMER2_COMP_AUTOZERO);
597                         rawip->meta.check_algo = HAMMER2_ENC_ALGO(
598                                                     HAMMER2_CHECK_XXHASH64);
599                 } else  {
600                         rawip->meta.comp_algo = HAMMER2_ENC_ALGO(
601                                                     HAMMER2_COMP_NEWFS_DEFAULT);
602                         rawip->meta.check_algo = HAMMER2_ENC_ALGO(
603                                                     HAMMER2_CHECK_XXHASH64);
604                 }
605
606                 /*
607                  * NOTE: We leave nmasters set to 0, which means that we
608                  *       don't know how many masters there are.  The quorum
609                  *       calculation will effectively be 1 ( 0 / 2 + 1 ).
610                  */
611                 rawip->meta.pfs_clid = Hammer2_PfsCLID[i];
612                 rawip->meta.pfs_fsid = Hammer2_PfsFSID[i];
613                 rawip->meta.pfs_type = HAMMER2_PFSTYPE_MASTER;
614                 rawip->meta.op_flags |= HAMMER2_OPFLAG_PFSROOT;
615
616                 /* first allocatable inode number */
617                 rawip->meta.pfs_inum = 16;
618
619                 /* rawip->u.blockset is left empty */
620
621                 /*
622                  * The root blockref will be stored in the super-root inode as
623                  * the only directory entry.  The copyid here is the actual
624                  * copyid of the storage ref.
625                  *
626                  * The key field for a directory entry's blockref is
627                  * essentially the name key for the entry.
628                  */
629                 root_blockref[i].key = rawip->meta.name_key;
630                 root_blockref[i].copyid = HAMMER2_COPYID_LOCAL;
631                 root_blockref[i].keybits = 0;
632                 root_blockref[i].check.xxhash64.value =
633                                 XXH64(rawip, sizeof(*rawip), XXH_HAMMER2_SEED);
634                 root_blockref[i].type = HAMMER2_BREF_TYPE_INODE;
635                 root_blockref[i].methods =
636                                 HAMMER2_ENC_CHECK(HAMMER2_CHECK_XXHASH64) |
637                                 HAMMER2_ENC_COMP(HAMMER2_COMP_NONE);
638                 root_blockref[i].mirror_tid = 16;
639                 root_blockref[i].flags = HAMMER2_BREF_FLAG_PFSROOT;
640         }
641
642         /*
643          * Format the super-root directory inode, giving it one directory
644          * entry (root_blockref) and fixup the icrc method.
645          *
646          * The superroot contains one directory entry pointing at the root
647          * inode (named via the label).  Inodes contain one blockset which
648          * is fully associative so we can put the entry anywhere without
649          * having to worry about the hash.  Use index 0.
650          */
651         rawip = (void *)(buf + (HAMMER2_OFF_MASK_LO & sroot_blockref.data_off));
652         rawip->meta.version = HAMMER2_INODE_VERSION_ONE;
653         rawip->meta.ctime = now;
654         rawip->meta.mtime = now;
655         /* rawip->meta.atime = now; NOT IMPL MUST BE ZERO */
656         rawip->meta.btime = now;
657         rawip->meta.type = HAMMER2_OBJTYPE_DIRECTORY;
658         rawip->meta.mode = 0700;        /* super-root - root only */
659         rawip->meta.inum = 0;           /* super root inode, inumber 0 */
660         rawip->meta.nlinks = 2;         /* directory link count compat */
661
662         rawip->meta.name_len = 0;       /* super-root is unnamed */
663         rawip->meta.name_key = 0;
664
665         rawip->meta.comp_algo = HAMMER2_ENC_ALGO(HAMMER2_COMP_AUTOZERO);
666         rawip->meta.check_algo = HAMMER2_ENC_ALGO(HAMMER2_CHECK_XXHASH64);
667
668         /*
669          * The super-root is flagged as a PFS and typically given its own
670          * random FSID, making it possible to mirror an entire HAMMER2 disk
671          * snapshots and all if desired.  PFS ids are used to match up
672          * mirror sources and targets and cluster copy sources and targets.
673          *
674          * (XXX whole-disk logical mirroring is not really supported in
675          *  the first attempt because each PFS is in its own modify/mirror
676          *  transaction id domain, so normal mechanics cannot cross a PFS
677          *  boundary).
678          */
679         rawip->meta.pfs_clid = Hammer2_SupCLID;
680         rawip->meta.pfs_fsid = Hammer2_SupFSID;
681         rawip->meta.pfs_type = HAMMER2_PFSTYPE_SUPROOT;
682         snprintf((char*)rawip->filename, sizeof(rawip->filename), "SUPROOT");
683         rawip->meta.name_key = 0;
684         rawip->meta.name_len = strlen((char*)rawip->filename);
685
686         /* The super-root has an inode number of 0 */
687         rawip->meta.pfs_inum = 0;
688
689         /*
690          * Currently newfs_hammer2 just throws the PFS inodes into the
691          * top-level block table at the volume root and doesn't try to
692          * create an indirect block, so we are limited to ~4 at filesystem
693          * creation time.  More can be added after mounting.
694          */
695         qsort(root_blockref, NLabels, sizeof(root_blockref[0]), blkrefary_cmp);
696         for (i = 0; i < NLabels; ++i)
697                 rawip->u.blockset.blockref[i] = root_blockref[i];
698
699         /*
700          * The sroot blockref will be stored in the volume header.
701          */
702         sroot_blockref.copyid = HAMMER2_COPYID_LOCAL;
703         sroot_blockref.keybits = 0;
704         sroot_blockref.check.xxhash64.value =
705                                         XXH64(rawip, sizeof(*rawip), XXH_HAMMER2_SEED);
706         sroot_blockref.type = HAMMER2_BREF_TYPE_INODE;
707         sroot_blockref.methods = HAMMER2_ENC_CHECK(HAMMER2_CHECK_XXHASH64) |
708                                  HAMMER2_ENC_COMP(HAMMER2_COMP_AUTOZERO);
709         sroot_blockref.mirror_tid = 16;
710         rawip = NULL;
711
712         /*
713          * Write out the 64K HAMMER2 block containing the root and sroot.
714          */
715         n = pwrite(fd, buf, HAMMER2_PBUFSIZE,
716                    sroot_blockref.data_off & HAMMER2_OFF_MASK_HI);
717         if (n != HAMMER2_PBUFSIZE) {
718                 perror("write");
719                 exit(1);
720         }
721
722         /*
723          * Format the volume header.
724          *
725          * The volume header points to sroot_blockref.  Also be absolutely
726          * sure that allocator_beg is set.
727          */
728         bzero(buf, HAMMER2_PBUFSIZE);
729         vol = (void *)buf;
730
731         vol->magic = HAMMER2_VOLUME_ID_HBO;
732         vol->boot_beg = boot_base;
733         vol->boot_end = boot_base + BootAreaSize;
734         vol->aux_beg = aux_base;
735         vol->aux_end = aux_base + AuxAreaSize;
736         vol->volu_size = total_space;
737         vol->version = Hammer2Version;
738         vol->flags = 0;
739
740         vol->fsid = Hammer2_VolFSID;
741         vol->fstype = Hammer2_FSType;
742
743         vol->peer_type = DMSG_PEER_HAMMER2;     /* LNK_CONN identification */
744
745         vol->allocator_size = free_space;
746         vol->allocator_free = free_space;
747         vol->allocator_beg = alloc_base;
748
749         vol->sroot_blockset.blockref[0] = sroot_blockref;
750         vol->mirror_tid = 16;   /* all blockref mirror TIDs set to 16 */
751         vol->freemap_tid = 16;  /* all blockref mirror TIDs set to 16 */
752         vol->icrc_sects[HAMMER2_VOL_ICRC_SECT1] =
753                         hammer2_icrc32((char *)vol + HAMMER2_VOLUME_ICRC1_OFF,
754                                        HAMMER2_VOLUME_ICRC1_SIZE);
755
756         /*
757          * Set ICRC_SECT0 after all remaining elements of sect0 have been
758          * populated in the volume header.  Note hat ICRC_SECT* (except for
759          * SECT0) are part of sect0.
760          */
761         vol->icrc_sects[HAMMER2_VOL_ICRC_SECT0] =
762                         hammer2_icrc32((char *)vol + HAMMER2_VOLUME_ICRC0_OFF,
763                                        HAMMER2_VOLUME_ICRC0_SIZE);
764         vol->icrc_volheader =
765                         hammer2_icrc32((char *)vol + HAMMER2_VOLUME_ICRCVH_OFF,
766                                        HAMMER2_VOLUME_ICRCVH_SIZE);
767
768         /*
769          * Write the volume header and all alternates.
770          */
771         for (i = 0; i < HAMMER2_NUM_VOLHDRS; ++i) {
772                 if (i * HAMMER2_ZONE_BYTES64 >= total_space)
773                         break;
774                 n = pwrite(fd, buf, HAMMER2_PBUFSIZE,
775                            volu_base + i * HAMMER2_ZONE_BYTES64);
776                 if (n != HAMMER2_PBUFSIZE) {
777                         perror("write");
778                         exit(1);
779                 }
780         }
781
782         /*
783          * Cleanup
784          */
785         free(buf);
786 }
787
788 static void
789 alloc_direct(hammer2_off_t *basep, hammer2_blockref_t *bref, size_t bytes)
790 {
791         int radix;
792
793         radix = 0;
794         assert(bytes);
795         while ((bytes & 1) == 0) {
796                 bytes >>= 1;
797                 ++radix;
798         }
799         assert(bytes == 1);
800         if (radix < HAMMER2_RADIX_MIN)
801                 radix = HAMMER2_RADIX_MIN;
802
803         bzero(bref, sizeof(*bref));
804         bref->data_off = *basep | radix;
805         bref->vradix = radix;
806
807         *basep += 1U << radix;
808 }
809
810 /*
811  * Borrow HAMMER1's directory hash algorithm #1 with a few modifications.
812  * The filename is split into fields which are hashed separately and then
813  * added together.
814  *
815  * Differences include: bit 63 must be set to 1 for HAMMER2 (HAMMER1 sets
816  * it to 0), this is because bit63=0 is used for hidden hardlinked inodes.
817  * (This means we do not need to do a 0-check/or-with-0x100000000 either).
818  *
819  * Also, the iscsi crc code is used instead of the old crc32 code.
820  */
821 static hammer2_key_t
822 dirhash(const unsigned char *name, size_t len)
823 {
824         const unsigned char *aname = name;
825         uint32_t crcx;
826         uint64_t key;
827         size_t i;
828         size_t j;
829
830         /*
831          * Filesystem version 6 or better will create directories
832          * using the ALG1 dirhash.  This hash breaks the filename
833          * up into domains separated by special characters and
834          * hashes each domain independently.
835          *
836          * We also do a simple sub-sort using the first character
837          * of the filename in the top 5-bits.
838          */
839         key = 0;
840
841         /*
842          * m32
843          */
844         crcx = 0;
845         for (i = j = 0; i < len; ++i) {
846                 if (aname[i] == '.' ||
847                     aname[i] == '-' ||
848                     aname[i] == '_' ||
849                     aname[i] == '~') {
850                         if (i != j)
851                                 crcx += hammer2_icrc32(aname + j, i - j);
852                         j = i + 1;
853                 }
854         }
855         if (i != j)
856                 crcx += hammer2_icrc32(aname + j, i - j);
857
858         /*
859          * The directory hash utilizes the top 32 bits of the 64-bit key.
860          * Bit 63 must be set to 1.
861          */
862         crcx |= 0x80000000U;
863         key |= (uint64_t)crcx << 32;
864
865         /*
866          * l16 - crc of entire filename
867          *
868          * This crc reduces degenerate hash collision conditions
869          */
870         crcx = hammer2_icrc32(aname, len);
871         crcx = crcx ^ (crcx << 16);
872         key |= crcx & 0xFFFF0000U;
873
874         /*
875          * Set bit 15.  This allows readdir to strip bit 63 so a positive
876          * 64-bit cookie/offset can always be returned, and still guarantee
877          * that the values 0x0000-0x7FFF are available for artificial entries.
878          * ('.' and '..').
879          */
880         key |= 0x8000U;
881
882         return (key);
883 }
884
885 static int
886 blkrefary_cmp(const void *b1, const void *b2)
887 {
888         const hammer2_blockref_t *bref1 = b1;
889         const hammer2_blockref_t *bref2 = b2;
890         if (bref1->key < bref2->key)
891                 return(-1);
892         if (bref1->key > bref2->key)
893                 return(1);
894         return 0;
895 }