sbin/hammer: Remove global variable NumVolumes
[dragonfly.git] / sbin / hammer / ondisk.c
1 /*
2  * Copyright (c) 2007 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 #include <sys/diskslice.h>
36 #include <sys/diskmbr.h>
37
38 #include "hammer_util.h"
39
40 static void get_buffer_readahead(struct buffer_info *base);
41 static __inline void *get_ondisk(hammer_off_t buf_offset,
42                         struct buffer_info **bufferp, int isnew);
43 static int readhammerbuf(struct volume_info *vol, void *data, int64_t offset);
44 static int writehammerbuf(struct volume_info *vol, const void *data,
45                         int64_t offset);
46
47 int DebugOpt;
48
49 uuid_t Hammer_FSType;
50 uuid_t Hammer_FSId;
51 int64_t BootAreaSize;
52 int64_t MemAreaSize;
53 int64_t UndoBufferSize;
54 int     RootVolNo = -1;
55 int     UseReadBehind = -4;
56 int     UseReadAhead = 4;
57 int     AssertOnFailure = 1;
58 struct volume_list VolList = TAILQ_HEAD_INITIALIZER(VolList);
59
60 static __inline
61 int
62 buffer_hash(hammer_off_t buf_offset)
63 {
64         int hi;
65
66         hi = (int)(buf_offset / HAMMER_BUFSIZE) & HAMMER_BUFLISTMASK;
67         return(hi);
68 }
69
70 static struct buffer_info*
71 find_buffer(struct volume_info *volume, hammer_off_t buf_offset)
72 {
73         int hi;
74         struct buffer_info *buf;
75
76         hi = buffer_hash(buf_offset);
77         TAILQ_FOREACH(buf, &volume->buffer_lists[hi], entry)
78                 if (buf->buf_offset == buf_offset)
79                         return(buf);
80         return(NULL);
81 }
82
83 /*
84  * Lookup the requested information structure and related on-disk buffer.
85  * Missing structures are created.
86  */
87 struct volume_info *
88 setup_volume(int32_t vol_no, const char *filename, int isnew, int oflags)
89 {
90         struct volume_info *vol;
91         struct volume_info *scan;
92         struct hammer_volume_ondisk *ondisk;
93         int i, n;
94         struct stat st1, st2;
95
96         /*
97          * Allocate the volume structure
98          */
99         vol = malloc(sizeof(*vol));
100         bzero(vol, sizeof(*vol));
101         for (i = 0; i < HAMMER_BUFLISTS; ++i)
102                 TAILQ_INIT(&vol->buffer_lists[i]);
103         vol->name = strdup(filename);
104         vol->fd = open(vol->name, oflags);
105         if (vol->fd < 0) {
106                 err(1, "setup_volume: %s: Open failed", vol->name);
107         }
108
109         /*
110          * Read or initialize the volume header
111          */
112         vol->ondisk = ondisk = malloc(HAMMER_BUFSIZE);
113         if (isnew > 0) {
114                 bzero(ondisk, HAMMER_BUFSIZE);
115         } else {
116                 n = readhammerbuf(vol, ondisk, 0);
117                 if (n == -1) {
118                         err(1, "setup_volume: %s: Read failed at offset 0",
119                             vol->name);
120                 }
121                 vol_no = ondisk->vol_no;
122                 if (RootVolNo < 0) {
123                         RootVolNo = ondisk->vol_rootvol;
124                 } else if (RootVolNo != (int)ondisk->vol_rootvol) {
125                         errx(1, "setup_volume: %s: root volume disagreement: "
126                                 "%d vs %d",
127                                 vol->name, RootVolNo, ondisk->vol_rootvol);
128                 }
129
130                 if (bcmp(&Hammer_FSType, &ondisk->vol_fstype, sizeof(Hammer_FSType)) != 0) {
131                         errx(1, "setup_volume: %s: Header does not indicate "
132                                 "that this is a hammer volume", vol->name);
133                 }
134                 if (TAILQ_EMPTY(&VolList)) {
135                         Hammer_FSId = vol->ondisk->vol_fsid;
136                 } else if (bcmp(&Hammer_FSId, &ondisk->vol_fsid, sizeof(Hammer_FSId)) != 0) {
137                         errx(1, "setup_volume: %s: FSId does match other "
138                                 "volumes!", vol->name);
139                 }
140         }
141         vol->vol_no = vol_no;
142
143         if (isnew > 0) {
144                 vol->cache.modified = 1;
145         }
146
147         if (fstat(vol->fd, &st1) != 0){
148                 errx(1, "setup_volume: %s: Failed to stat", vol->name);
149         }
150
151         /*
152          * Link the volume structure in
153          */
154         TAILQ_FOREACH(scan, &VolList, entry) {
155                 if (scan->vol_no == vol_no) {
156                         errx(1, "setup_volume: %s: Duplicate volume number %d "
157                                 "against %s", vol->name, vol_no, scan->name);
158                 }
159                 if (fstat(scan->fd, &st2) != 0){
160                         errx(1, "setup_volume: %s: Failed to stat %s",
161                                 vol->name, scan->name);
162                 }
163                 if ((st1.st_ino == st2.st_ino) && (st1.st_dev == st2.st_dev)) {
164                         errx(1, "setup_volume: %s: Specified more than once",
165                                 vol->name);
166                 }
167         }
168         TAILQ_INSERT_TAIL(&VolList, vol, entry);
169         return(vol);
170 }
171
172 /*
173  * Check basic volume characteristics.
174  */
175 void
176 check_volume(struct volume_info *vol)
177 {
178         struct partinfo pinfo;
179         struct stat st;
180
181         /*
182          * Get basic information about the volume
183          */
184         if (ioctl(vol->fd, DIOCGPART, &pinfo) < 0) {
185                 /*
186                  * Allow the formatting of regular files as HAMMER volumes
187                  */
188                 if (fstat(vol->fd, &st) < 0)
189                         err(1, "Unable to stat %s", vol->name);
190                 vol->size = st.st_size;
191                 vol->type = "REGFILE";
192         } else {
193                 /*
194                  * When formatting a block device as a HAMMER volume the
195                  * sector size must be compatible.  HAMMER uses 16384 byte
196                  * filesystem buffers.
197                  */
198                 if (pinfo.reserved_blocks) {
199                         errx(1, "HAMMER cannot be placed in a partition "
200                                 "which overlaps the disklabel or MBR");
201                 }
202                 if (pinfo.media_blksize > HAMMER_BUFSIZE ||
203                     HAMMER_BUFSIZE % pinfo.media_blksize) {
204                         errx(1, "A media sector size of %d is not supported",
205                              pinfo.media_blksize);
206                 }
207
208                 vol->size = pinfo.media_size;
209                 vol->device_offset = pinfo.media_offset;
210                 vol->type = "DEVICE";
211         }
212
213         /*
214          * Reserve space for (future) header junk, setup our poor-man's
215          * big-block allocator.
216          */
217         vol->vol_alloc = HAMMER_BUFSIZE * 16;
218 }
219
220 struct volume_info *
221 get_volume(int32_t vol_no)
222 {
223         struct volume_info *vol;
224
225         TAILQ_FOREACH(vol, &VolList, entry) {
226                 if (vol->vol_no == vol_no)
227                         break;
228         }
229         if (vol == NULL) {
230                 if (AssertOnFailure)
231                         errx(1, "get_volume: Volume %d does not exist!",
232                                 vol_no);
233                 return(NULL);
234         }
235         ++vol->cache.refs;
236         /* not added to or removed from hammer cache */
237         return(vol);
238 }
239
240 void
241 rel_volume(struct volume_info *volume)
242 {
243         if (volume == NULL)
244                 return;
245         /* not added to or removed from hammer cache */
246         --volume->cache.refs;
247 }
248
249 /*
250  * Acquire the specified buffer.  isnew is -1 only when called
251  * via get_buffer_readahead() to prevent another readahead.
252  */
253 struct buffer_info *
254 get_buffer(hammer_off_t buf_offset, int isnew)
255 {
256         void *ondisk;
257         struct buffer_info *buf;
258         struct volume_info *volume;
259         hammer_off_t orig_offset = buf_offset;
260         int vol_no;
261         int zone;
262         int hi, n;
263         int dora = 0;
264
265         zone = HAMMER_ZONE_DECODE(buf_offset);
266         if (zone > HAMMER_ZONE_RAW_BUFFER_INDEX) {
267                 buf_offset = blockmap_lookup(buf_offset, NULL, NULL, NULL);
268         }
269         if (buf_offset == HAMMER_OFF_BAD)
270                 return(NULL);
271
272         if (AssertOnFailure) {
273                 assert((buf_offset & HAMMER_OFF_ZONE_MASK) ==
274                        HAMMER_ZONE_RAW_BUFFER);
275         }
276         vol_no = HAMMER_VOL_DECODE(buf_offset);
277         volume = get_volume(vol_no);
278         if (volume == NULL)
279                 return(NULL);
280
281         buf_offset &= ~HAMMER_BUFMASK64;
282         buf = find_buffer(volume, buf_offset);
283
284         if (buf == NULL) {
285                 buf = malloc(sizeof(*buf));
286                 bzero(buf, sizeof(*buf));
287                 if (DebugOpt > 1) {
288                         fprintf(stderr, "get_buffer: %016llx %016llx at %p\n",
289                                 (long long)orig_offset, (long long)buf_offset,
290                                 buf);
291                 }
292                 buf->buf_offset = buf_offset;
293                 buf->raw_offset = hammer_xlate_to_phys(volume->ondisk,
294                                                         buf_offset);
295                 buf->volume = volume;
296                 hi = buffer_hash(buf_offset);
297                 TAILQ_INSERT_TAIL(&volume->buffer_lists[hi], buf, entry);
298                 ++volume->cache.refs;
299                 buf->cache.u.buffer = buf;
300                 hammer_cache_add(&buf->cache, ISBUFFER);
301                 dora = (isnew == 0);
302         } else {
303                 if (DebugOpt > 1) {
304                         fprintf(stderr, "get_buffer: %016llx %016llx at %p *\n",
305                                 (long long)orig_offset, (long long)buf_offset,
306                                 buf);
307                 }
308                 hammer_cache_used(&buf->cache);
309                 ++buf->use_count;
310         }
311         ++buf->cache.refs;
312         hammer_cache_flush();
313         if ((ondisk = buf->ondisk) == NULL) {
314                 buf->ondisk = ondisk = malloc(HAMMER_BUFSIZE);
315                 if (isnew <= 0) {
316                         n = readhammerbuf(volume, ondisk, buf->raw_offset);
317                         if (n == -1) {
318                                 if (AssertOnFailure)
319                                         err(1, "get_buffer: %s:%016llx "
320                                             "Read failed at offset %016llx",
321                                             volume->name,
322                                             (long long)buf->buf_offset,
323                                             (long long)buf->raw_offset);
324                                 bzero(ondisk, HAMMER_BUFSIZE);
325                         }
326                 }
327         }
328         if (isnew > 0) {
329                 bzero(ondisk, HAMMER_BUFSIZE);
330                 buf->cache.modified = 1;
331         }
332         if (dora)
333                 get_buffer_readahead(buf);
334         return(buf);
335 }
336
337 static void
338 get_buffer_readahead(struct buffer_info *base)
339 {
340         struct buffer_info *buf;
341         struct volume_info *vol;
342         hammer_off_t buf_offset;
343         int64_t raw_offset;
344         int ri = UseReadBehind;
345         int re = UseReadAhead;
346
347         raw_offset = base->raw_offset + ri * HAMMER_BUFSIZE;
348         vol = base->volume;
349
350         while (ri < re) {
351                 if (raw_offset >= vol->ondisk->vol_buf_end)
352                         break;
353                 if (raw_offset < vol->ondisk->vol_buf_beg || ri == 0) {
354                         ++ri;
355                         raw_offset += HAMMER_BUFSIZE;
356                         continue;
357                 }
358                 buf_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no,
359                         raw_offset - vol->ondisk->vol_buf_beg);
360                 buf = find_buffer(vol, buf_offset);
361                 if (buf == NULL) {
362                         buf = get_buffer(buf_offset, -1);
363                         rel_buffer(buf);
364                 }
365                 ++ri;
366                 raw_offset += HAMMER_BUFSIZE;
367         }
368 }
369
370 void
371 rel_buffer(struct buffer_info *buffer)
372 {
373         struct volume_info *volume;
374         int hi;
375
376         if (buffer == NULL)
377                 return;
378         assert(buffer->cache.refs > 0);
379         if (--buffer->cache.refs == 0) {
380                 if (buffer->cache.delete) {
381                         hi = buffer_hash(buffer->buf_offset);
382                         volume = buffer->volume;
383                         if (buffer->cache.modified)
384                                 flush_buffer(buffer);
385                         TAILQ_REMOVE(&volume->buffer_lists[hi], buffer, entry);
386                         hammer_cache_del(&buffer->cache);
387                         free(buffer->ondisk);
388                         free(buffer);
389                         rel_volume(volume);
390                 }
391         }
392 }
393
394 /*
395  * Retrieve a pointer to a buffer data given a buffer offset.  The underlying
396  * bufferp is freed if isnew or the offset is out of range of the cached data.
397  * If bufferp is freed a referenced buffer is loaded into it.
398  */
399 void *
400 get_buffer_data(hammer_off_t buf_offset, struct buffer_info **bufferp,
401                 int isnew)
402 {
403         if (*bufferp != NULL) {
404                 if (isnew > 0 ||
405                     (((*bufferp)->buf_offset ^ buf_offset) & ~HAMMER_BUFMASK64)) {
406                         rel_buffer(*bufferp);
407                         *bufferp = NULL;
408                 }
409         }
410         return(get_ondisk(buf_offset, bufferp, isnew));
411 }
412
413 /*
414  * Retrieve a pointer to a B-Tree node given a zone offset.  The underlying
415  * bufferp is freed if non-NULL and a referenced buffer is loaded into it.
416  */
417 hammer_node_ondisk_t
418 get_node(hammer_off_t node_offset, struct buffer_info **bufferp)
419 {
420         if (*bufferp != NULL) {
421                 rel_buffer(*bufferp);
422                 *bufferp = NULL;
423         }
424         return(get_ondisk(node_offset, bufferp, 0));
425 }
426
427 /*
428  * Return a pointer to a buffer data given a buffer offset.
429  * If *bufferp is NULL acquire the buffer otherwise use that buffer.
430  */
431 static __inline
432 void *
433 get_ondisk(hammer_off_t buf_offset, struct buffer_info **bufferp, int isnew)
434 {
435         struct buffer_info *buffer;
436
437         buffer = *bufferp;
438         if (buffer == NULL) {
439                 buffer = *bufferp = get_buffer(buf_offset, isnew);
440                 if (buffer == NULL)
441                         return(NULL);
442         }
443
444         return((char *)buffer->ondisk +
445                 ((int32_t)buf_offset & HAMMER_BUFMASK));
446 }
447
448 /*
449  * Allocate HAMMER elements - btree nodes, meta data, data storage
450  */
451 void *
452 alloc_btree_element(hammer_off_t *offp, struct buffer_info **data_bufferp)
453 {
454         hammer_node_ondisk_t node;
455
456         node = alloc_blockmap(HAMMER_ZONE_BTREE_INDEX, sizeof(*node),
457                               offp, data_bufferp);
458         bzero(node, sizeof(*node));
459         return (node);
460 }
461
462 void *
463 alloc_meta_element(hammer_off_t *offp, int32_t data_len,
464                    struct buffer_info **data_bufferp)
465 {
466         void *data;
467
468         data = alloc_blockmap(HAMMER_ZONE_META_INDEX, data_len,
469                               offp, data_bufferp);
470         bzero(data, data_len);
471         return (data);
472 }
473
474 /*
475  * The only data_len supported by HAMMER userspace for large data zone
476  * (zone 10) is HAMMER_BUFSIZE which is 16KB.  >16KB data does not fit
477  * in a buffer allocated by get_buffer().  Also alloc_blockmap() does
478  * not consider >16KB buffer size.
479  */
480 void *
481 alloc_data_element(hammer_off_t *offp, int32_t data_len,
482                    struct buffer_info **data_bufferp)
483 {
484         void *data;
485         int zone;
486
487         if (data_len == 0)
488                 return(NULL);
489
490         zone = hammer_data_zone_index(data_len);
491         assert(data_len <= HAMMER_BUFSIZE); /* just one buffer */
492         assert(zone == HAMMER_ZONE_LARGE_DATA_INDEX ||
493                zone == HAMMER_ZONE_SMALL_DATA_INDEX);
494
495         data = alloc_blockmap(zone, data_len, offp, data_bufferp);
496         bzero(data, data_len);
497         return(data);
498 }
499
500 /*
501  * Format a new freemap.  Set all layer1 entries to UNAVAIL.  The initialize
502  * code will load each volume's freemap.
503  */
504 void
505 format_freemap(struct volume_info *root_vol)
506 {
507         struct buffer_info *buffer = NULL;
508         hammer_off_t layer1_offset;
509         hammer_blockmap_t blockmap;
510         struct hammer_blockmap_layer1 *layer1;
511         int i, isnew;
512
513         /* Only root volume needs formatting */
514         assert(root_vol->vol_no == RootVolNo);
515
516         layer1_offset = alloc_bigblock(root_vol, HAMMER_ZONE_FREEMAP_INDEX);
517         for (i = 0; i < HAMMER_BIGBLOCK_SIZE; i += sizeof(*layer1)) {
518                 isnew = ((i % HAMMER_BUFSIZE) == 0);
519                 layer1 = get_buffer_data(layer1_offset + i, &buffer, isnew);
520                 bzero(layer1, sizeof(*layer1));
521                 layer1->phys_offset = HAMMER_BLOCKMAP_UNAVAIL;
522                 layer1->blocks_free = 0;
523                 layer1->layer1_crc = crc32(layer1, HAMMER_LAYER1_CRCSIZE);
524         }
525         assert(i == HAMMER_BIGBLOCK_SIZE);
526         rel_buffer(buffer);
527
528         blockmap = &root_vol->ondisk->vol0_blockmap[HAMMER_ZONE_FREEMAP_INDEX];
529         bzero(blockmap, sizeof(*blockmap));
530         blockmap->phys_offset = layer1_offset;
531         blockmap->first_offset = 0;
532         blockmap->next_offset = HAMMER_ENCODE_RAW_BUFFER(0, 0);
533         blockmap->alloc_offset = HAMMER_ENCODE_RAW_BUFFER(255, -1);
534         blockmap->entry_crc = crc32(blockmap, HAMMER_BLOCKMAP_CRCSIZE);
535         root_vol->cache.modified = 1;
536 }
537
538 /*
539  * Load the volume's remaining free space into the freemap.
540  *
541  * Returns the number of big-blocks available.
542  */
543 int64_t
544 initialize_freemap(struct volume_info *vol)
545 {
546         struct volume_info *root_vol;
547         struct buffer_info *buffer1 = NULL;
548         struct buffer_info *buffer2 = NULL;
549         struct hammer_blockmap_layer1 *layer1;
550         struct hammer_blockmap_layer2 *layer2;
551         hammer_off_t layer1_base;
552         hammer_off_t layer1_offset;
553         hammer_off_t layer2_offset;
554         hammer_off_t phys_offset;
555         hammer_off_t block_offset;
556         hammer_off_t aligned_vol_free_end;
557         hammer_blockmap_t freemap;
558         int64_t count = 0;
559         int64_t layer1_count = 0;
560
561         root_vol = get_volume(RootVolNo);
562         aligned_vol_free_end = (vol->vol_free_end + HAMMER_BLOCKMAP_LAYER2_MASK)
563                                 & ~HAMMER_BLOCKMAP_LAYER2_MASK;
564
565         printf("initialize freemap volume %d\n", vol->vol_no);
566
567         /*
568          * Initialize the freemap.  First preallocate the big-blocks required
569          * to implement layer2.   This preallocation is a bootstrap allocation
570          * using blocks from the target volume.
571          */
572         freemap = &root_vol->ondisk->vol0_blockmap[HAMMER_ZONE_FREEMAP_INDEX];
573         layer1_base = freemap->phys_offset;
574
575         for (phys_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no, 0);
576              phys_offset < aligned_vol_free_end;
577              phys_offset += HAMMER_BLOCKMAP_LAYER2) {
578                 layer1_offset = layer1_base +
579                                 HAMMER_BLOCKMAP_LAYER1_OFFSET(phys_offset);
580                 layer1 = get_buffer_data(layer1_offset, &buffer1, 0);
581                 if (layer1->phys_offset == HAMMER_BLOCKMAP_UNAVAIL) {
582                         layer1->phys_offset = alloc_bigblock(vol,
583                                                 HAMMER_ZONE_FREEMAP_INDEX);
584                         layer1->blocks_free = 0;
585                         buffer1->cache.modified = 1;
586                         layer1->layer1_crc = crc32(layer1,
587                                                    HAMMER_LAYER1_CRCSIZE);
588                 }
589         }
590
591         /*
592          * Now fill everything in.
593          */
594         for (phys_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no, 0);
595              phys_offset < aligned_vol_free_end;
596              phys_offset += HAMMER_BLOCKMAP_LAYER2) {
597                 layer1_count = 0;
598                 layer1_offset = layer1_base +
599                                 HAMMER_BLOCKMAP_LAYER1_OFFSET(phys_offset);
600                 layer1 = get_buffer_data(layer1_offset, &buffer1, 0);
601                 assert(layer1->phys_offset != HAMMER_BLOCKMAP_UNAVAIL);
602
603                 for (block_offset = 0;
604                      block_offset < HAMMER_BLOCKMAP_LAYER2;
605                      block_offset += HAMMER_BIGBLOCK_SIZE) {
606                         layer2_offset = layer1->phys_offset +
607                                         HAMMER_BLOCKMAP_LAYER2_OFFSET(block_offset);
608                         layer2 = get_buffer_data(layer2_offset, &buffer2, 0);
609                         bzero(layer2, sizeof(*layer2));
610
611                         if (phys_offset + block_offset < vol->vol_free_off) {
612                                 /*
613                                  * Fixups XXX - big-blocks already allocated as part
614                                  * of the freemap bootstrap.
615                                  */
616                                 if (layer2->zone == 0) {
617                                         layer2->zone = HAMMER_ZONE_FREEMAP_INDEX;
618                                         layer2->append_off = HAMMER_BIGBLOCK_SIZE;
619                                         layer2->bytes_free = 0;
620                                 }
621                         } else if (phys_offset + block_offset < vol->vol_free_end) {
622                                 layer2->zone = 0;
623                                 layer2->append_off = 0;
624                                 layer2->bytes_free = HAMMER_BIGBLOCK_SIZE;
625                                 ++count;
626                                 ++layer1_count;
627                         } else {
628                                 layer2->zone = HAMMER_ZONE_UNAVAIL_INDEX;
629                                 layer2->append_off = HAMMER_BIGBLOCK_SIZE;
630                                 layer2->bytes_free = 0;
631                         }
632                         layer2->entry_crc = crc32(layer2, HAMMER_LAYER2_CRCSIZE);
633                         buffer2->cache.modified = 1;
634                 }
635
636                 layer1->blocks_free += layer1_count;
637                 layer1->layer1_crc = crc32(layer1, HAMMER_LAYER1_CRCSIZE);
638                 buffer1->cache.modified = 1;
639         }
640
641         rel_buffer(buffer1);
642         rel_buffer(buffer2);
643         rel_volume(root_vol);
644         return(count);
645 }
646
647 /*
648  * Returns the number of big-blocks available for filesystem data and undos
649  * without formatting.
650  */
651 int64_t
652 count_freemap(struct volume_info *vol)
653 {
654         hammer_off_t phys_offset;
655         hammer_off_t vol_free_off;
656         hammer_off_t aligned_vol_free_end;
657         int64_t count = 0;
658
659         vol_free_off = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no, 0);
660         aligned_vol_free_end = (vol->vol_free_end + HAMMER_BLOCKMAP_LAYER2_MASK)
661                                 & ~HAMMER_BLOCKMAP_LAYER2_MASK;
662
663         if (vol->vol_no == RootVolNo)
664                 vol_free_off += HAMMER_BIGBLOCK_SIZE;
665
666         for (phys_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no, 0);
667              phys_offset < aligned_vol_free_end;
668              phys_offset += HAMMER_BLOCKMAP_LAYER2) {
669                 vol_free_off += HAMMER_BIGBLOCK_SIZE;
670         }
671
672         for (phys_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no, 0);
673              phys_offset < aligned_vol_free_end;
674              phys_offset += HAMMER_BIGBLOCK_SIZE) {
675                 if (phys_offset < vol_free_off) {
676                         ;
677                 } else if (phys_offset < vol->vol_free_end) {
678                         ++count;
679                 }
680         }
681
682         return(count);
683 }
684
685 /*
686  * Format the undomap for the root volume.
687  */
688 void
689 format_undomap(struct volume_info *root_vol)
690 {
691         const int undo_zone = HAMMER_ZONE_UNDO_INDEX;
692         hammer_off_t undo_limit;
693         hammer_blockmap_t blockmap;
694         struct hammer_volume_ondisk *ondisk;
695         struct buffer_info *buffer = NULL;
696         hammer_off_t scan;
697         int n;
698         int limit_index;
699         uint32_t seqno;
700
701         /* Only root volume needs formatting */
702         assert(root_vol->vol_no == RootVolNo);
703         ondisk = root_vol->ondisk;
704
705         /*
706          * Size the undo buffer in multiples of HAMMER_BIGBLOCK_SIZE,
707          * up to HAMMER_UNDO_LAYER2 big-blocks.  Size to approximately
708          * 0.1% of the disk.
709          *
710          * The minimum UNDO fifo size is 500MB, or approximately 1% of
711          * the recommended 50G disk.
712          *
713          * Changing this minimum is rather dangerous as complex filesystem
714          * operations can cause the UNDO FIFO to fill up otherwise.
715          */
716         undo_limit = UndoBufferSize;
717         if (undo_limit == 0) {
718                 undo_limit = (ondisk->vol_buf_end - ondisk->vol_buf_beg) / 1000;
719                 if (undo_limit < 500*1024*1024)
720                         undo_limit = 500*1024*1024;
721         }
722         undo_limit = (undo_limit + HAMMER_BIGBLOCK_MASK64) &
723                      ~HAMMER_BIGBLOCK_MASK64;
724         if (undo_limit < HAMMER_BIGBLOCK_SIZE)
725                 undo_limit = HAMMER_BIGBLOCK_SIZE;
726         if (undo_limit > HAMMER_BIGBLOCK_SIZE * HAMMER_UNDO_LAYER2)
727                 undo_limit = HAMMER_BIGBLOCK_SIZE * HAMMER_UNDO_LAYER2;
728         UndoBufferSize = undo_limit;
729
730         blockmap = &ondisk->vol0_blockmap[undo_zone];
731         bzero(blockmap, sizeof(*blockmap));
732         blockmap->phys_offset = HAMMER_BLOCKMAP_UNAVAIL;
733         blockmap->first_offset = HAMMER_ZONE_ENCODE(undo_zone, 0);
734         blockmap->next_offset = blockmap->first_offset;
735         blockmap->alloc_offset = HAMMER_ZONE_ENCODE(undo_zone, undo_limit);
736         blockmap->entry_crc = crc32(blockmap, HAMMER_BLOCKMAP_CRCSIZE);
737
738         limit_index = undo_limit / HAMMER_BIGBLOCK_SIZE;
739         assert(limit_index <= HAMMER_UNDO_LAYER2);
740
741         for (n = 0; n < limit_index; ++n) {
742                 ondisk->vol0_undo_array[n] = alloc_bigblock(NULL,
743                                                         HAMMER_ZONE_UNDO_INDEX);
744         }
745         while (n < HAMMER_UNDO_LAYER2) {
746                 ondisk->vol0_undo_array[n++] = HAMMER_BLOCKMAP_UNAVAIL;
747         }
748
749         /*
750          * Pre-initialize the UNDO blocks (HAMMER version 4+)
751          */
752         printf("initializing the undo map (%jd MB)\n",
753                 (intmax_t)(blockmap->alloc_offset & HAMMER_OFF_LONG_MASK) /
754                 (1024 * 1024));
755
756         scan = blockmap->first_offset;
757         seqno = 0;
758
759         while (scan < blockmap->alloc_offset) {
760                 hammer_fifo_head_t head;
761                 hammer_fifo_tail_t tail;
762                 int isnew;
763                 int bytes = HAMMER_UNDO_ALIGN;
764
765                 isnew = ((scan & HAMMER_BUFMASK64) == 0);
766                 head = get_buffer_data(scan, &buffer, isnew);
767                 buffer->cache.modified = 1;
768                 tail = (void *)((char *)head + bytes - sizeof(*tail));
769
770                 bzero(head, bytes);
771                 head->hdr_signature = HAMMER_HEAD_SIGNATURE;
772                 head->hdr_type = HAMMER_HEAD_TYPE_DUMMY;
773                 head->hdr_size = bytes;
774                 head->hdr_seq = seqno++;
775
776                 tail->tail_signature = HAMMER_TAIL_SIGNATURE;
777                 tail->tail_type = HAMMER_HEAD_TYPE_DUMMY;
778                 tail->tail_size = bytes;
779
780                 head->hdr_crc = crc32(head, HAMMER_FIFO_HEAD_CRCOFF) ^
781                                 crc32(head + 1, bytes - sizeof(*head));
782
783                 scan += bytes;
784         }
785         rel_buffer(buffer);
786 }
787
788 /*
789  * Format a new blockmap.  This is mostly a degenerate case because
790  * all allocations are now actually done from the freemap.
791  */
792 void
793 format_blockmap(hammer_blockmap_t blockmap, int zone, hammer_off_t offset)
794 {
795         hammer_off_t zone_base = HAMMER_ZONE_ENCODE(zone, offset);
796
797         bzero(blockmap, sizeof(*blockmap));
798         blockmap->phys_offset = 0;
799         blockmap->first_offset = zone_base;
800         blockmap->next_offset = zone_base;
801         blockmap->alloc_offset = HAMMER_ENCODE(zone, 255, -1);
802         blockmap->entry_crc = crc32(blockmap, HAMMER_BLOCKMAP_CRCSIZE);
803 }
804
805 /*
806  * Flush various tracking structures to disk
807  */
808 void
809 flush_all_volumes(void)
810 {
811         struct volume_info *vol;
812
813         TAILQ_FOREACH(vol, &VolList, entry)
814                 flush_volume(vol);
815 }
816
817 void
818 flush_volume(struct volume_info *volume)
819 {
820         struct buffer_info *buffer;
821         int i;
822
823         for (i = 0; i < HAMMER_BUFLISTS; ++i) {
824                 TAILQ_FOREACH(buffer, &volume->buffer_lists[i], entry)
825                         flush_buffer(buffer);
826         }
827         if (writehammerbuf(volume, volume->ondisk, 0) == -1)
828                 err(1, "Write volume %d (%s)", volume->vol_no, volume->name);
829         volume->cache.modified = 0;
830 }
831
832 void
833 flush_buffer(struct buffer_info *buffer)
834 {
835         struct volume_info *vol;
836
837         vol = buffer->volume;
838         if (writehammerbuf(vol, buffer->ondisk, buffer->raw_offset) == -1)
839                 err(1, "Write volume %d (%s)", vol->vol_no, vol->name);
840         buffer->cache.modified = 0;
841 }
842
843 /*
844  * Core I/O operations
845  */
846 static int
847 readhammerbuf(struct volume_info *vol, void *data, int64_t offset)
848 {
849         ssize_t n;
850
851         n = pread(vol->fd, data, HAMMER_BUFSIZE, offset);
852         if (n != HAMMER_BUFSIZE)
853                 return(-1);
854         return(0);
855 }
856
857 static int
858 writehammerbuf(struct volume_info *vol, const void *data, int64_t offset)
859 {
860         ssize_t n;
861
862         n = pwrite(vol->fd, data, HAMMER_BUFSIZE, offset);
863         if (n != HAMMER_BUFSIZE)
864                 return(-1);
865         return(0);
866 }
867
868 int64_t init_boot_area_size(int64_t value, off_t avg_vol_size)
869 {
870         if (value == 0) {
871                 value = HAMMER_BOOT_NOMBYTES;
872                 while (value > avg_vol_size / HAMMER_MAX_VOLUMES)
873                         value >>= 1;
874                 if (value < HAMMER_BOOT_MINBYTES)
875                         value = 0;
876         } else if (value < HAMMER_BOOT_MINBYTES) {
877                 value = HAMMER_BOOT_MINBYTES;
878         }
879
880         return(value);
881 }
882
883 int64_t init_mem_area_size(int64_t value, off_t avg_vol_size)
884 {
885         if (value == 0) {
886                 value = HAMMER_MEM_NOMBYTES;
887                 while (value > avg_vol_size / HAMMER_MAX_VOLUMES)
888                         value >>= 1;
889                 if (value < HAMMER_MEM_MINBYTES)
890                         value = 0;
891         } else if (value < HAMMER_MEM_MINBYTES) {
892                 value = HAMMER_MEM_MINBYTES;
893         }
894
895         return(value);
896 }