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