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