sbin/hammer: Fix conditional for Hammer_FSId initialization
[dragonfly.git] / sbin / hammer / ondisk.c
1 /*
2  * Copyright (c) 2007 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
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/diskslice.h>
36 #include <sys/diskmbr.h>
37
38 #include "hammer_util.h"
39
40 static void get_buffer_readahead(struct buffer_info *base);
41 static __inline void *get_ondisk(hammer_off_t buf_offset,
42                         struct buffer_info **bufferp, int isnew);
43 static int readhammerbuf(struct volume_info *vol, void *data, int64_t offset);
44 static int writehammerbuf(struct volume_info *vol, const void *data,
45                         int64_t offset);
46
47 int DebugOpt;
48
49 uuid_t Hammer_FSType;
50 uuid_t Hammer_FSId;
51 int     UseReadBehind = -4;
52 int     UseReadAhead = 4;
53 int     AssertOnFailure = 1;
54 struct volume_list VolList = TAILQ_HEAD_INITIALIZER(VolList);
55 static int valid_hammer_volumes;
56
57 static __inline
58 int
59 buffer_hash(hammer_off_t buf_offset)
60 {
61         int hi;
62
63         hi = (int)(buf_offset / HAMMER_BUFSIZE) & HAMMER_BUFLISTMASK;
64         return(hi);
65 }
66
67 static struct buffer_info*
68 find_buffer(struct volume_info *volume, hammer_off_t buf_offset)
69 {
70         int hi;
71         struct buffer_info *buf;
72
73         hi = buffer_hash(buf_offset);
74         TAILQ_FOREACH(buf, &volume->buffer_lists[hi], entry)
75                 if (buf->buf_offset == buf_offset)
76                         return(buf);
77         return(NULL);
78 }
79
80 static
81 struct volume_info *
82 __alloc_volume(const char *volname, int oflags)
83 {
84         struct volume_info *vol;
85         int i;
86
87         vol = malloc(sizeof(*vol));
88         if (vol == NULL)
89                 err(1, "alloc_volume");
90         bzero(vol, sizeof(*vol));
91
92         vol->vol_no = -1;
93         vol->name = strdup(volname);
94         vol->fd = open(vol->name, oflags);
95         if (vol->fd < 0)
96                 err(1, "alloc_volume: Failed to open %s", vol->name);
97
98         vol->size = 0;
99         vol->device_offset = 0;
100         vol->type = NULL;
101
102         vol->ondisk = malloc(HAMMER_BUFSIZE);
103         if (vol->ondisk == NULL)
104                 err(1, "alloc_volume");
105         bzero(vol->ondisk, HAMMER_BUFSIZE);
106
107         for (i = 0; i < HAMMER_BUFLISTS; ++i)
108                 TAILQ_INIT(&vol->buffer_lists[i]);
109
110         return(vol);
111 }
112
113 static void
114 __add_volume(struct volume_info *vol)
115 {
116         struct volume_info *scan;
117         struct stat st1, st2;
118
119         if (fstat(vol->fd, &st1) != 0)
120                 errx(1, "add_volume: %s: Failed to stat", vol->name);
121
122         TAILQ_FOREACH(scan, &VolList, entry) {
123                 if (scan->vol_no == vol->vol_no) {
124                         errx(1, "add_volume: %s: Duplicate volume number %d "
125                                 "against %s",
126                                 vol->name, vol->vol_no, scan->name);
127                 }
128                 if (fstat(scan->fd, &st2) != 0) {
129                         errx(1, "add_volume: %s: Failed to stat %s",
130                                 vol->name, scan->name);
131                 }
132                 if ((st1.st_ino == st2.st_ino) && (st1.st_dev == st2.st_dev)) {
133                         errx(1, "add_volume: %s: Specified more than once",
134                                 vol->name);
135                 }
136         }
137
138         TAILQ_INSERT_TAIL(&VolList, vol, entry);
139 }
140
141 /*
142  * Initialize a volume structure and ondisk vol_no field.
143  */
144 struct volume_info *
145 init_volume(int32_t vol_no, const char *filename, int oflags)
146 {
147         struct volume_info *vol;
148
149         vol = __alloc_volume(filename, oflags);
150         vol->vol_no = vol->ondisk->vol_no = vol_no;
151         vol->cache.modified = 1;
152
153         __add_volume(vol);
154
155         return(vol);
156 }
157
158 /*
159  * Initialize a volume structure and read ondisk volume header.
160  */
161 struct volume_info*
162 load_volume(const char *filename, int oflags)
163 {
164         struct volume_info *vol;
165         struct hammer_volume_ondisk *ondisk;
166         int n;
167
168         vol = __alloc_volume(filename, oflags);
169         ondisk = vol->ondisk;
170
171         n = readhammerbuf(vol, ondisk, 0);
172         if (n == -1) {
173                 err(1, "load_volume: %s: Read failed at offset 0", vol->name);
174         }
175         vol->vol_no = ondisk->vol_no;
176
177         if (ondisk->vol_rootvol != HAMMER_ROOT_VOLNO) {
178                 errx(1, "load_volume: Invalid root volume# %d",
179                         ondisk->vol_rootvol);
180         }
181
182         if (bcmp(&Hammer_FSType, &ondisk->vol_fstype, sizeof(Hammer_FSType))) {
183                 errx(1, "load_volume: %s: Header does not indicate "
184                         "that this is a hammer volume", vol->name);
185         }
186
187         if (valid_hammer_volumes++ == 0) {
188                 Hammer_FSId = ondisk->vol_fsid;
189         } else if (bcmp(&Hammer_FSId, &ondisk->vol_fsid, sizeof(Hammer_FSId))) {
190                 errx(1, "load_volume: %s: FSId does match other volumes!",
191                         vol->name);
192         }
193
194         __add_volume(vol);
195
196         return(vol);
197 }
198
199 /*
200  * Check basic volume characteristics.
201  */
202 void
203 check_volume(struct volume_info *vol)
204 {
205         struct partinfo pinfo;
206         struct stat st;
207
208         /*
209          * Get basic information about the volume
210          */
211         if (ioctl(vol->fd, DIOCGPART, &pinfo) < 0) {
212                 /*
213                  * Allow the formatting of regular files as HAMMER volumes
214                  */
215                 if (fstat(vol->fd, &st) < 0)
216                         err(1, "Unable to stat %s", vol->name);
217                 vol->size = st.st_size;
218                 vol->type = "REGFILE";
219         } else {
220                 /*
221                  * When formatting a block device as a HAMMER volume the
222                  * sector size must be compatible.  HAMMER uses 16384 byte
223                  * filesystem buffers.
224                  */
225                 if (pinfo.reserved_blocks) {
226                         errx(1, "HAMMER cannot be placed in a partition "
227                                 "which overlaps the disklabel or MBR");
228                 }
229                 if (pinfo.media_blksize > HAMMER_BUFSIZE ||
230                     HAMMER_BUFSIZE % pinfo.media_blksize) {
231                         errx(1, "A media sector size of %d is not supported",
232                              pinfo.media_blksize);
233                 }
234
235                 vol->size = pinfo.media_size;
236                 vol->device_offset = pinfo.media_offset;
237                 vol->type = "DEVICE";
238         }
239 }
240
241 struct volume_info *
242 get_volume(int32_t vol_no)
243 {
244         struct volume_info *vol;
245
246         TAILQ_FOREACH(vol, &VolList, entry) {
247                 if (vol->vol_no == vol_no)
248                         break;
249         }
250         if (vol == NULL)
251                 errx(1, "get_volume: Volume %d does not exist!", vol_no);
252
253         ++vol->cache.refs;
254         /* not added to or removed from hammer cache */
255         return(vol);
256 }
257
258 struct volume_info *
259 get_root_volume(void)
260 {
261         return(get_volume(HAMMER_ROOT_VOLNO));
262 }
263
264 void
265 rel_volume(struct volume_info *volume)
266 {
267         if (volume == NULL)
268                 return;
269         /* not added to or removed from hammer cache */
270         --volume->cache.refs;
271 }
272
273 /*
274  * Acquire the specified buffer.  isnew is -1 only when called
275  * via get_buffer_readahead() to prevent another readahead.
276  */
277 struct buffer_info *
278 get_buffer(hammer_off_t buf_offset, int isnew)
279 {
280         void *ondisk;
281         struct buffer_info *buf;
282         struct volume_info *volume;
283         hammer_off_t orig_offset = buf_offset;
284         int vol_no;
285         int zone;
286         int hi, n;
287         int dora = 0;
288
289         zone = HAMMER_ZONE_DECODE(buf_offset);
290         if (zone > HAMMER_ZONE_RAW_BUFFER_INDEX) {
291                 buf_offset = blockmap_lookup(buf_offset, NULL, NULL, NULL);
292         }
293         if (buf_offset == HAMMER_OFF_BAD)
294                 return(NULL);
295         assert((buf_offset & HAMMER_OFF_ZONE_MASK) == HAMMER_ZONE_RAW_BUFFER);
296
297         vol_no = HAMMER_VOL_DECODE(buf_offset);
298         volume = get_volume(vol_no);
299         if (volume == NULL)
300                 return(NULL);
301
302         buf_offset &= ~HAMMER_BUFMASK64;
303         buf = find_buffer(volume, buf_offset);
304
305         if (buf == NULL) {
306                 buf = malloc(sizeof(*buf));
307                 bzero(buf, sizeof(*buf));
308                 if (DebugOpt > 1) {
309                         fprintf(stderr, "get_buffer: %016llx %016llx at %p\n",
310                                 (long long)orig_offset, (long long)buf_offset,
311                                 buf);
312                 }
313                 buf->buf_offset = buf_offset;
314                 buf->raw_offset = hammer_xlate_to_phys(volume->ondisk,
315                                                         buf_offset);
316                 buf->volume = volume;
317                 hi = buffer_hash(buf_offset);
318                 TAILQ_INSERT_TAIL(&volume->buffer_lists[hi], buf, entry);
319                 ++volume->cache.refs;
320                 buf->cache.u.buffer = buf;
321                 hammer_cache_add(&buf->cache, ISBUFFER);
322                 dora = (isnew == 0);
323         } else {
324                 if (DebugOpt > 1) {
325                         fprintf(stderr, "get_buffer: %016llx %016llx at %p *\n",
326                                 (long long)orig_offset, (long long)buf_offset,
327                                 buf);
328                 }
329                 hammer_cache_used(&buf->cache);
330                 ++buf->use_count;
331         }
332         ++buf->cache.refs;
333         hammer_cache_flush();
334         if ((ondisk = buf->ondisk) == NULL) {
335                 buf->ondisk = ondisk = malloc(HAMMER_BUFSIZE);
336                 if (isnew <= 0) {
337                         n = readhammerbuf(volume, ondisk, buf->raw_offset);
338                         if (n == -1) {
339                                 if (AssertOnFailure)
340                                         err(1, "get_buffer: %s:%016llx "
341                                             "Read failed at offset %016llx",
342                                             volume->name,
343                                             (long long)buf->buf_offset,
344                                             (long long)buf->raw_offset);
345                                 bzero(ondisk, HAMMER_BUFSIZE);
346                         }
347                 }
348         }
349         if (isnew > 0) {
350                 bzero(ondisk, HAMMER_BUFSIZE);
351                 buf->cache.modified = 1;
352         }
353         if (dora)
354                 get_buffer_readahead(buf);
355         return(buf);
356 }
357
358 static void
359 get_buffer_readahead(struct buffer_info *base)
360 {
361         struct buffer_info *buf;
362         struct volume_info *vol;
363         hammer_off_t buf_offset;
364         int64_t raw_offset;
365         int ri = UseReadBehind;
366         int re = UseReadAhead;
367
368         raw_offset = base->raw_offset + ri * HAMMER_BUFSIZE;
369         vol = base->volume;
370
371         while (ri < re) {
372                 if (raw_offset >= vol->ondisk->vol_buf_end)
373                         break;
374                 if (raw_offset < vol->ondisk->vol_buf_beg || ri == 0) {
375                         ++ri;
376                         raw_offset += HAMMER_BUFSIZE;
377                         continue;
378                 }
379                 buf_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no,
380                         raw_offset - vol->ondisk->vol_buf_beg);
381                 buf = find_buffer(vol, buf_offset);
382                 if (buf == NULL) {
383                         buf = get_buffer(buf_offset, -1);
384                         rel_buffer(buf);
385                 }
386                 ++ri;
387                 raw_offset += HAMMER_BUFSIZE;
388         }
389 }
390
391 void
392 rel_buffer(struct buffer_info *buffer)
393 {
394         struct volume_info *volume;
395         int hi;
396
397         if (buffer == NULL)
398                 return;
399         assert(buffer->cache.refs > 0);
400         if (--buffer->cache.refs == 0) {
401                 if (buffer->cache.delete) {
402                         hi = buffer_hash(buffer->buf_offset);
403                         volume = buffer->volume;
404                         if (buffer->cache.modified)
405                                 flush_buffer(buffer);
406                         TAILQ_REMOVE(&volume->buffer_lists[hi], buffer, entry);
407                         hammer_cache_del(&buffer->cache);
408                         free(buffer->ondisk);
409                         free(buffer);
410                         rel_volume(volume);
411                 }
412         }
413 }
414
415 /*
416  * Retrieve a pointer to a buffer data given a buffer offset.  The underlying
417  * bufferp is freed if isnew or the offset is out of range of the cached data.
418  * If bufferp is freed a referenced buffer is loaded into it.
419  */
420 void *
421 get_buffer_data(hammer_off_t buf_offset, struct buffer_info **bufferp,
422                 int isnew)
423 {
424         if (*bufferp != NULL) {
425                 if (isnew > 0 ||
426                     (((*bufferp)->buf_offset ^ buf_offset) & ~HAMMER_BUFMASK64)) {
427                         rel_buffer(*bufferp);
428                         *bufferp = NULL;
429                 }
430         }
431         return(get_ondisk(buf_offset, bufferp, isnew));
432 }
433
434 /*
435  * Retrieve a pointer to a B-Tree node given a zone offset.  The underlying
436  * bufferp is freed if non-NULL and a referenced buffer is loaded into it.
437  */
438 hammer_node_ondisk_t
439 get_node(hammer_off_t node_offset, struct buffer_info **bufferp)
440 {
441         if (*bufferp != NULL) {
442                 rel_buffer(*bufferp);
443                 *bufferp = NULL;
444         }
445         return(get_ondisk(node_offset, bufferp, 0));
446 }
447
448 /*
449  * Return a pointer to a buffer data given a buffer offset.
450  * If *bufferp is NULL acquire the buffer otherwise use that buffer.
451  */
452 static __inline
453 void *
454 get_ondisk(hammer_off_t buf_offset, struct buffer_info **bufferp, int isnew)
455 {
456         struct buffer_info *buffer;
457
458         buffer = *bufferp;
459         if (buffer == NULL) {
460                 buffer = *bufferp = get_buffer(buf_offset, isnew);
461                 if (buffer == NULL)
462                         return(NULL);
463         }
464
465         return((char *)buffer->ondisk +
466                 ((int32_t)buf_offset & HAMMER_BUFMASK));
467 }
468
469 /*
470  * Allocate HAMMER elements - btree nodes, meta data, data storage
471  */
472 void *
473 alloc_btree_element(hammer_off_t *offp, struct buffer_info **data_bufferp)
474 {
475         hammer_node_ondisk_t node;
476
477         node = alloc_blockmap(HAMMER_ZONE_BTREE_INDEX, sizeof(*node),
478                               offp, data_bufferp);
479         bzero(node, sizeof(*node));
480         return (node);
481 }
482
483 void *
484 alloc_meta_element(hammer_off_t *offp, int32_t data_len,
485                    struct buffer_info **data_bufferp)
486 {
487         void *data;
488
489         data = alloc_blockmap(HAMMER_ZONE_META_INDEX, data_len,
490                               offp, data_bufferp);
491         bzero(data, data_len);
492         return (data);
493 }
494
495 /*
496  * The only data_len supported by HAMMER userspace for large data zone
497  * (zone 10) is HAMMER_BUFSIZE which is 16KB.  >16KB data does not fit
498  * in a buffer allocated by get_buffer().  Also alloc_blockmap() does
499  * not consider >16KB buffer size.
500  */
501 void *
502 alloc_data_element(hammer_off_t *offp, int32_t data_len,
503                    struct buffer_info **data_bufferp)
504 {
505         void *data;
506         int zone;
507
508         if (data_len == 0)
509                 return(NULL);
510
511         zone = hammer_data_zone_index(data_len);
512         assert(data_len <= HAMMER_BUFSIZE); /* just one buffer */
513         assert(zone == HAMMER_ZONE_LARGE_DATA_INDEX ||
514                zone == HAMMER_ZONE_SMALL_DATA_INDEX);
515
516         data = alloc_blockmap(zone, data_len, offp, data_bufferp);
517         bzero(data, data_len);
518         return(data);
519 }
520
521 /*
522  * Format a new blockmap.  This is mostly a degenerate case because
523  * all allocations are now actually done from the freemap.
524  */
525 void
526 format_blockmap(struct volume_info *root_vol, int zone, hammer_off_t offset)
527 {
528         hammer_blockmap_t blockmap;
529         hammer_off_t zone_base;
530
531         /* Only root volume needs formatting */
532         assert(root_vol->vol_no == HAMMER_ROOT_VOLNO);
533
534         assert(hammer_is_zone2_mapped_index(zone));
535
536         blockmap = &root_vol->ondisk->vol0_blockmap[zone];
537         zone_base = HAMMER_ZONE_ENCODE(zone, offset);
538
539         bzero(blockmap, sizeof(*blockmap));
540         blockmap->phys_offset = 0;
541         blockmap->first_offset = zone_base;
542         blockmap->next_offset = zone_base;
543         blockmap->alloc_offset = HAMMER_ENCODE(zone, 255, -1);
544         blockmap->entry_crc = crc32(blockmap, HAMMER_BLOCKMAP_CRCSIZE);
545         root_vol->cache.modified = 1;
546 }
547
548 /*
549  * Format a new freemap.  Set all layer1 entries to UNAVAIL.  The initialize
550  * code will load each volume's freemap.
551  */
552 void
553 format_freemap(struct volume_info *root_vol)
554 {
555         struct buffer_info *buffer = NULL;
556         hammer_off_t layer1_offset;
557         hammer_blockmap_t blockmap;
558         struct hammer_blockmap_layer1 *layer1;
559         int i, isnew;
560
561         /* Only root volume needs formatting */
562         assert(root_vol->vol_no == HAMMER_ROOT_VOLNO);
563
564         layer1_offset = alloc_bigblock(root_vol, HAMMER_ZONE_FREEMAP_INDEX);
565         for (i = 0; i < HAMMER_BIGBLOCK_SIZE; i += sizeof(*layer1)) {
566                 isnew = ((i % HAMMER_BUFSIZE) == 0);
567                 layer1 = get_buffer_data(layer1_offset + i, &buffer, isnew);
568                 bzero(layer1, sizeof(*layer1));
569                 layer1->phys_offset = HAMMER_BLOCKMAP_UNAVAIL;
570                 layer1->blocks_free = 0;
571                 layer1->layer1_crc = crc32(layer1, HAMMER_LAYER1_CRCSIZE);
572         }
573         assert(i == HAMMER_BIGBLOCK_SIZE);
574         rel_buffer(buffer);
575
576         blockmap = &root_vol->ondisk->vol0_blockmap[HAMMER_ZONE_FREEMAP_INDEX];
577         bzero(blockmap, sizeof(*blockmap));
578         blockmap->phys_offset = layer1_offset;
579         blockmap->first_offset = 0;
580         blockmap->next_offset = HAMMER_ENCODE_RAW_BUFFER(0, 0);
581         blockmap->alloc_offset = HAMMER_ENCODE_RAW_BUFFER(255, -1);
582         blockmap->entry_crc = crc32(blockmap, HAMMER_BLOCKMAP_CRCSIZE);
583         root_vol->cache.modified = 1;
584 }
585
586 /*
587  * Load the volume's remaining free space into the freemap.
588  *
589  * Returns the number of big-blocks available.
590  */
591 int64_t
592 initialize_freemap(struct volume_info *vol)
593 {
594         struct volume_info *root_vol;
595         struct buffer_info *buffer1 = NULL;
596         struct buffer_info *buffer2 = NULL;
597         struct hammer_blockmap_layer1 *layer1;
598         struct hammer_blockmap_layer2 *layer2;
599         hammer_off_t layer1_base;
600         hammer_off_t layer1_offset;
601         hammer_off_t layer2_offset;
602         hammer_off_t phys_offset;
603         hammer_off_t block_offset;
604         hammer_off_t aligned_vol_free_end;
605         hammer_blockmap_t freemap;
606         int64_t count = 0;
607         int64_t layer1_count = 0;
608
609         root_vol = get_root_volume();
610         aligned_vol_free_end = (vol->vol_free_end + HAMMER_BLOCKMAP_LAYER2_MASK)
611                                 & ~HAMMER_BLOCKMAP_LAYER2_MASK;
612
613         printf("initialize freemap volume %d\n", vol->vol_no);
614
615         /*
616          * Initialize the freemap.  First preallocate the big-blocks required
617          * to implement layer2.   This preallocation is a bootstrap allocation
618          * using blocks from the target volume.
619          */
620         freemap = &root_vol->ondisk->vol0_blockmap[HAMMER_ZONE_FREEMAP_INDEX];
621         layer1_base = freemap->phys_offset;
622
623         for (phys_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no, 0);
624              phys_offset < aligned_vol_free_end;
625              phys_offset += HAMMER_BLOCKMAP_LAYER2) {
626                 layer1_offset = layer1_base +
627                                 HAMMER_BLOCKMAP_LAYER1_OFFSET(phys_offset);
628                 layer1 = get_buffer_data(layer1_offset, &buffer1, 0);
629                 if (layer1->phys_offset == HAMMER_BLOCKMAP_UNAVAIL) {
630                         layer1->phys_offset = alloc_bigblock(vol,
631                                                 HAMMER_ZONE_FREEMAP_INDEX);
632                         layer1->blocks_free = 0;
633                         buffer1->cache.modified = 1;
634                         layer1->layer1_crc = crc32(layer1,
635                                                    HAMMER_LAYER1_CRCSIZE);
636                 }
637         }
638
639         /*
640          * Now fill everything in.
641          */
642         for (phys_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no, 0);
643              phys_offset < aligned_vol_free_end;
644              phys_offset += HAMMER_BLOCKMAP_LAYER2) {
645                 layer1_count = 0;
646                 layer1_offset = layer1_base +
647                                 HAMMER_BLOCKMAP_LAYER1_OFFSET(phys_offset);
648                 layer1 = get_buffer_data(layer1_offset, &buffer1, 0);
649                 assert(layer1->phys_offset != HAMMER_BLOCKMAP_UNAVAIL);
650
651                 for (block_offset = 0;
652                      block_offset < HAMMER_BLOCKMAP_LAYER2;
653                      block_offset += HAMMER_BIGBLOCK_SIZE) {
654                         layer2_offset = layer1->phys_offset +
655                                         HAMMER_BLOCKMAP_LAYER2_OFFSET(block_offset);
656                         layer2 = get_buffer_data(layer2_offset, &buffer2, 0);
657                         bzero(layer2, sizeof(*layer2));
658
659                         if (phys_offset + block_offset < vol->vol_free_off) {
660                                 /*
661                                  * Fixups XXX - big-blocks already allocated as part
662                                  * of the freemap bootstrap.
663                                  */
664                                 if (layer2->zone == 0) {
665                                         layer2->zone = HAMMER_ZONE_FREEMAP_INDEX;
666                                         layer2->append_off = HAMMER_BIGBLOCK_SIZE;
667                                         layer2->bytes_free = 0;
668                                 }
669                         } else if (phys_offset + block_offset < vol->vol_free_end) {
670                                 layer2->zone = 0;
671                                 layer2->append_off = 0;
672                                 layer2->bytes_free = HAMMER_BIGBLOCK_SIZE;
673                                 ++count;
674                                 ++layer1_count;
675                         } else {
676                                 layer2->zone = HAMMER_ZONE_UNAVAIL_INDEX;
677                                 layer2->append_off = HAMMER_BIGBLOCK_SIZE;
678                                 layer2->bytes_free = 0;
679                         }
680                         layer2->entry_crc = crc32(layer2, HAMMER_LAYER2_CRCSIZE);
681                         buffer2->cache.modified = 1;
682                 }
683
684                 layer1->blocks_free += layer1_count;
685                 layer1->layer1_crc = crc32(layer1, HAMMER_LAYER1_CRCSIZE);
686                 buffer1->cache.modified = 1;
687         }
688
689         rel_buffer(buffer1);
690         rel_buffer(buffer2);
691         rel_volume(root_vol);
692         return(count);
693 }
694
695 /*
696  * Returns the number of big-blocks available for filesystem data and undos
697  * without formatting.
698  */
699 int64_t
700 count_freemap(struct volume_info *vol)
701 {
702         hammer_off_t phys_offset;
703         hammer_off_t vol_free_off;
704         hammer_off_t aligned_vol_free_end;
705         int64_t count = 0;
706
707         vol_free_off = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no, 0);
708         aligned_vol_free_end = (vol->vol_free_end + HAMMER_BLOCKMAP_LAYER2_MASK)
709                                 & ~HAMMER_BLOCKMAP_LAYER2_MASK;
710
711         if (vol->vol_no == HAMMER_ROOT_VOLNO)
712                 vol_free_off += HAMMER_BIGBLOCK_SIZE;
713
714         for (phys_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no, 0);
715              phys_offset < aligned_vol_free_end;
716              phys_offset += HAMMER_BLOCKMAP_LAYER2) {
717                 vol_free_off += HAMMER_BIGBLOCK_SIZE;
718         }
719
720         for (phys_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no, 0);
721              phys_offset < aligned_vol_free_end;
722              phys_offset += HAMMER_BIGBLOCK_SIZE) {
723                 if (phys_offset < vol_free_off) {
724                         ;
725                 } else if (phys_offset < vol->vol_free_end) {
726                         ++count;
727                 }
728         }
729
730         return(count);
731 }
732
733 /*
734  * Format the undomap for the root volume.
735  */
736 void
737 format_undomap(struct volume_info *root_vol, int64_t *undo_buffer_size)
738 {
739         const int undo_zone = HAMMER_ZONE_UNDO_INDEX;
740         hammer_off_t undo_limit;
741         hammer_blockmap_t blockmap;
742         struct hammer_volume_ondisk *ondisk;
743         struct buffer_info *buffer = NULL;
744         hammer_off_t scan;
745         int n;
746         int limit_index;
747         uint32_t seqno;
748
749         /* Only root volume needs formatting */
750         assert(root_vol->vol_no == HAMMER_ROOT_VOLNO);
751         ondisk = root_vol->ondisk;
752
753         /*
754          * Size the undo buffer in multiples of HAMMER_BIGBLOCK_SIZE,
755          * up to HAMMER_UNDO_LAYER2 big-blocks.  Size to approximately
756          * 0.1% of the disk.
757          *
758          * The minimum UNDO fifo size is 500MB, or approximately 1% of
759          * the recommended 50G disk.
760          *
761          * Changing this minimum is rather dangerous as complex filesystem
762          * operations can cause the UNDO FIFO to fill up otherwise.
763          */
764         undo_limit = *undo_buffer_size;
765         if (undo_limit == 0) {
766                 undo_limit = (ondisk->vol_buf_end - ondisk->vol_buf_beg) / 1000;
767                 if (undo_limit < 500*1024*1024)
768                         undo_limit = 500*1024*1024;
769         }
770         undo_limit = (undo_limit + HAMMER_BIGBLOCK_MASK64) &
771                      ~HAMMER_BIGBLOCK_MASK64;
772         if (undo_limit < HAMMER_BIGBLOCK_SIZE)
773                 undo_limit = HAMMER_BIGBLOCK_SIZE;
774         if (undo_limit > HAMMER_BIGBLOCK_SIZE * HAMMER_UNDO_LAYER2)
775                 undo_limit = HAMMER_BIGBLOCK_SIZE * HAMMER_UNDO_LAYER2;
776         *undo_buffer_size = undo_limit;
777
778         blockmap = &ondisk->vol0_blockmap[undo_zone];
779         bzero(blockmap, sizeof(*blockmap));
780         blockmap->phys_offset = HAMMER_BLOCKMAP_UNAVAIL;
781         blockmap->first_offset = HAMMER_ZONE_ENCODE(undo_zone, 0);
782         blockmap->next_offset = blockmap->first_offset;
783         blockmap->alloc_offset = HAMMER_ZONE_ENCODE(undo_zone, undo_limit);
784         blockmap->entry_crc = crc32(blockmap, HAMMER_BLOCKMAP_CRCSIZE);
785
786         limit_index = undo_limit / HAMMER_BIGBLOCK_SIZE;
787         assert(limit_index <= HAMMER_UNDO_LAYER2);
788
789         for (n = 0; n < limit_index; ++n) {
790                 ondisk->vol0_undo_array[n] = alloc_bigblock(NULL,
791                                                         HAMMER_ZONE_UNDO_INDEX);
792         }
793         while (n < HAMMER_UNDO_LAYER2) {
794                 ondisk->vol0_undo_array[n++] = HAMMER_BLOCKMAP_UNAVAIL;
795         }
796
797         /*
798          * Pre-initialize the UNDO blocks (HAMMER version 4+)
799          */
800         printf("initializing the undo map (%jd MB)\n",
801                 (intmax_t)(blockmap->alloc_offset & HAMMER_OFF_LONG_MASK) /
802                 (1024 * 1024));
803
804         scan = blockmap->first_offset;
805         seqno = 0;
806
807         while (scan < blockmap->alloc_offset) {
808                 hammer_fifo_head_t head;
809                 hammer_fifo_tail_t tail;
810                 int isnew;
811                 int bytes = HAMMER_UNDO_ALIGN;
812
813                 isnew = ((scan & HAMMER_BUFMASK64) == 0);
814                 head = get_buffer_data(scan, &buffer, isnew);
815                 buffer->cache.modified = 1;
816                 tail = (void *)((char *)head + bytes - sizeof(*tail));
817
818                 bzero(head, bytes);
819                 head->hdr_signature = HAMMER_HEAD_SIGNATURE;
820                 head->hdr_type = HAMMER_HEAD_TYPE_DUMMY;
821                 head->hdr_size = bytes;
822                 head->hdr_seq = seqno++;
823
824                 tail->tail_signature = HAMMER_TAIL_SIGNATURE;
825                 tail->tail_type = HAMMER_HEAD_TYPE_DUMMY;
826                 tail->tail_size = bytes;
827
828                 head->hdr_crc = crc32(head, HAMMER_FIFO_HEAD_CRCOFF) ^
829                                 crc32(head + 1, bytes - sizeof(*head));
830
831                 scan += bytes;
832         }
833         rel_buffer(buffer);
834 }
835
836 /*
837  * Flush various tracking structures to disk
838  */
839 void
840 flush_all_volumes(void)
841 {
842         struct volume_info *vol;
843
844         TAILQ_FOREACH(vol, &VolList, entry)
845                 flush_volume(vol);
846 }
847
848 void
849 flush_volume(struct volume_info *volume)
850 {
851         struct buffer_info *buffer;
852         int i;
853
854         for (i = 0; i < HAMMER_BUFLISTS; ++i) {
855                 TAILQ_FOREACH(buffer, &volume->buffer_lists[i], entry)
856                         flush_buffer(buffer);
857         }
858         if (writehammerbuf(volume, volume->ondisk, 0) == -1)
859                 err(1, "Write volume %d (%s)", volume->vol_no, volume->name);
860         volume->cache.modified = 0;
861 }
862
863 void
864 flush_buffer(struct buffer_info *buffer)
865 {
866         struct volume_info *vol;
867
868         vol = buffer->volume;
869         if (writehammerbuf(vol, buffer->ondisk, buffer->raw_offset) == -1)
870                 err(1, "Write volume %d (%s)", vol->vol_no, vol->name);
871         buffer->cache.modified = 0;
872 }
873
874 /*
875  * Core I/O operations
876  */
877 static int
878 readhammerbuf(struct volume_info *vol, void *data, int64_t offset)
879 {
880         ssize_t n;
881
882         n = pread(vol->fd, data, HAMMER_BUFSIZE, offset);
883         if (n != HAMMER_BUFSIZE)
884                 return(-1);
885         return(0);
886 }
887
888 static int
889 writehammerbuf(struct volume_info *vol, const void *data, int64_t offset)
890 {
891         ssize_t n;
892
893         n = pwrite(vol->fd, data, HAMMER_BUFSIZE, offset);
894         if (n != HAMMER_BUFSIZE)
895                 return(-1);
896         return(0);
897 }
898
899 int64_t init_boot_area_size(int64_t value, off_t avg_vol_size)
900 {
901         if (value == 0) {
902                 value = HAMMER_BOOT_NOMBYTES;
903                 while (value > avg_vol_size / HAMMER_MAX_VOLUMES)
904                         value >>= 1;
905                 if (value < HAMMER_BOOT_MINBYTES)
906                         value = 0;
907         } else if (value < HAMMER_BOOT_MINBYTES) {
908                 value = HAMMER_BOOT_MINBYTES;
909         }
910
911         return(value);
912 }
913
914 int64_t init_mem_area_size(int64_t value, off_t avg_vol_size)
915 {
916         if (value == 0) {
917                 value = HAMMER_MEM_NOMBYTES;
918                 while (value > avg_vol_size / HAMMER_MAX_VOLUMES)
919                         value >>= 1;
920                 if (value < HAMMER_MEM_MINBYTES)
921                         value = 0;
922         } else if (value < HAMMER_MEM_MINBYTES) {
923                 value = HAMMER_MEM_MINBYTES;
924         }
925
926         return(value);
927 }