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