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