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