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