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