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