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