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