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