sbin/hammer: Properly use calloc(3)
[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 static hammer_off_t
280 __blockmap_xlate_to_zone2(hammer_off_t zone_offset)
281 {
282         hammer_off_t buf_offset;
283         int error = 0;
284
285         if (hammer_is_zone_raw_buffer(zone_offset))
286                 buf_offset = zone_offset;
287         else
288                 buf_offset = blockmap_lookup(zone_offset, &error);
289
290         if (error)
291                 return(HAMMER_OFF_BAD);
292         assert(hammer_is_zone_raw_buffer(buf_offset));
293
294         return(buf_offset);
295 }
296
297 static struct buffer_info *
298 __alloc_buffer(hammer_off_t buf_offset, int isnew)
299 {
300         struct volume_info *volume;
301         struct buffer_info *buf;
302         int hi;
303
304         volume = get_volume(HAMMER_VOL_DECODE(buf_offset));
305         assert(volume != NULL);
306
307         buf = calloc(1, sizeof(*buf));
308         buf->buf_offset = buf_offset;
309         buf->raw_offset = hammer_xlate_to_phys(volume->ondisk, buf_offset);
310         buf->volume = volume;
311         buf->ondisk = calloc(1, HAMMER_BUFSIZE);
312
313         if (isnew <= 0) {
314                 if (readhammerbuf(buf) == -1) {
315                         err(1, "Failed to read %s:%016jx at %016jx",
316                             volume->name,
317                             (intmax_t)buf->buf_offset,
318                             (intmax_t)buf->raw_offset);
319                 }
320         }
321
322         hi = buffer_hash(buf_offset);
323         TAILQ_INSERT_TAIL(&volume->buffer_lists[hi], buf, entry);
324         hammer_cache_add(&buf->cache);
325
326         return(buf);
327 }
328
329 /*
330  * Acquire the 16KB buffer for specified zone offset.
331  */
332 static struct buffer_info *
333 get_buffer(hammer_off_t zone_offset, int isnew)
334 {
335         struct buffer_info *buf;
336         hammer_off_t buf_offset;
337         int dora = 0;
338
339         buf_offset = __blockmap_xlate_to_zone2(zone_offset);
340         if (buf_offset == HAMMER_OFF_BAD)
341                 return(NULL);
342
343         buf_offset &= ~HAMMER_BUFMASK64;
344         buf = find_buffer(buf_offset);
345
346         if (buf == NULL) {
347                 buf = __alloc_buffer(buf_offset, isnew);
348                 dora = (isnew == 0);
349         } else {
350                 assert(isnew != -1);
351                 hammer_cache_used(&buf->cache);
352         }
353         assert(buf->ondisk != NULL);
354
355         ++buf->cache.refs;
356         hammer_cache_flush();
357
358         if (isnew > 0) {
359                 assert(buf->cache.modified == 0);
360                 bzero(buf->ondisk, HAMMER_BUFSIZE);
361                 buf->cache.modified = 1;
362         }
363         if (dora)
364                 get_buffer_readahead(buf);
365         return(buf);
366 }
367
368 static void
369 get_buffer_readahead(struct buffer_info *base)
370 {
371         struct buffer_info *buf;
372         struct volume_info *vol;
373         hammer_off_t buf_offset;
374         int64_t raw_offset;
375         int ri = UseReadBehind;
376         int re = UseReadAhead;
377
378         raw_offset = base->raw_offset + ri * HAMMER_BUFSIZE;
379         vol = base->volume;
380
381         while (ri < re) {
382                 if (raw_offset >= vol->ondisk->vol_buf_end)
383                         break;
384                 if (raw_offset < vol->ondisk->vol_buf_beg || ri == 0) {
385                         ++ri;
386                         raw_offset += HAMMER_BUFSIZE;
387                         continue;
388                 }
389                 buf_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no,
390                         raw_offset - vol->ondisk->vol_buf_beg);
391                 buf = find_buffer(buf_offset);
392                 if (buf == NULL) {
393                         /* call with -1 to prevent another readahead */
394                         buf = get_buffer(buf_offset, -1);
395                         rel_buffer(buf);
396                 }
397                 ++ri;
398                 raw_offset += HAMMER_BUFSIZE;
399         }
400 }
401
402 void
403 rel_buffer(struct buffer_info *buffer)
404 {
405         struct volume_info *volume;
406         int hi;
407
408         if (buffer == NULL)
409                 return;
410         assert(buffer->cache.refs > 0);
411         if (--buffer->cache.refs == 0) {
412                 if (buffer->cache.delete) {
413                         hi = buffer_hash(buffer->buf_offset);
414                         volume = buffer->volume;
415                         if (buffer->cache.modified)
416                                 flush_buffer(buffer);
417                         TAILQ_REMOVE(&volume->buffer_lists[hi], buffer, entry);
418                         hammer_cache_del(&buffer->cache);
419                         free(buffer->ondisk);
420                         free(buffer);
421                 }
422         }
423 }
424
425 /*
426  * Retrieve a pointer to a buffer data given a buffer offset.  The underlying
427  * bufferp is freed if isnew or the offset is out of range of the cached data.
428  * If bufferp is freed a referenced buffer is loaded into it.
429  */
430 void *
431 get_buffer_data(hammer_off_t buf_offset, struct buffer_info **bufferp,
432                 int isnew)
433 {
434         if (*bufferp != NULL) {
435                 if (isnew > 0 ||
436                     (((*bufferp)->buf_offset ^ buf_offset) & ~HAMMER_BUFMASK64)) {
437                         rel_buffer(*bufferp);
438                         *bufferp = NULL;
439                 }
440         }
441
442         if (*bufferp == NULL) {
443                 *bufferp = get_buffer(buf_offset, isnew);
444                 if (*bufferp == NULL)
445                         return(NULL);
446         }
447
448         return(((char *)(*bufferp)->ondisk) +
449                 ((int32_t)buf_offset & HAMMER_BUFMASK));
450 }
451
452 /*
453  * Allocate HAMMER elements - B-Tree nodes
454  */
455 hammer_node_ondisk_t
456 alloc_btree_node(hammer_off_t *offp, struct buffer_info **data_bufferp)
457 {
458         hammer_node_ondisk_t node;
459
460         node = alloc_blockmap(HAMMER_ZONE_BTREE_INDEX, sizeof(*node),
461                               offp, data_bufferp);
462         bzero(node, sizeof(*node));
463         return(node);
464 }
465
466 /*
467  * Allocate HAMMER elements - meta data (inode, direntry, PFS, etc)
468  */
469 void *
470 alloc_meta_element(hammer_off_t *offp, int32_t data_len,
471                    struct buffer_info **data_bufferp)
472 {
473         void *data;
474
475         data = alloc_blockmap(HAMMER_ZONE_META_INDEX, data_len,
476                               offp, data_bufferp);
477         bzero(data, data_len);
478         return(data);
479 }
480
481 /*
482  * Format a new blockmap.  This is mostly a degenerate case because
483  * all allocations are now actually done from the freemap.
484  */
485 void
486 format_blockmap(struct volume_info *root_vol, int zone, hammer_off_t offset)
487 {
488         hammer_blockmap_t blockmap;
489         hammer_off_t zone_base;
490
491         /* Only root volume needs formatting */
492         assert(root_vol->vol_no == HAMMER_ROOT_VOLNO);
493
494         assert(hammer_is_zone2_mapped_index(zone));
495
496         blockmap = &root_vol->ondisk->vol0_blockmap[zone];
497         zone_base = HAMMER_ZONE_ENCODE(zone, offset);
498
499         bzero(blockmap, sizeof(*blockmap));
500         blockmap->phys_offset = 0;
501         blockmap->first_offset = zone_base;
502         blockmap->next_offset = zone_base;
503         blockmap->alloc_offset = HAMMER_ENCODE(zone, 255, -1);
504         hammer_crc_set_blockmap(blockmap);
505 }
506
507 /*
508  * Format a new freemap.  Set all layer1 entries to UNAVAIL.  The initialize
509  * code will load each volume's freemap.
510  */
511 void
512 format_freemap(struct volume_info *root_vol)
513 {
514         struct buffer_info *buffer = NULL;
515         hammer_off_t layer1_offset;
516         hammer_blockmap_t blockmap;
517         hammer_blockmap_layer1_t layer1;
518         int i, isnew;
519
520         /* Only root volume needs formatting */
521         assert(root_vol->vol_no == HAMMER_ROOT_VOLNO);
522
523         layer1_offset = bootstrap_bigblock(root_vol);
524         for (i = 0; i < HAMMER_BIGBLOCK_SIZE; i += sizeof(*layer1)) {
525                 isnew = ((i % HAMMER_BUFSIZE) == 0);
526                 layer1 = get_buffer_data(layer1_offset + i, &buffer, isnew);
527                 bzero(layer1, sizeof(*layer1));
528                 layer1->phys_offset = HAMMER_BLOCKMAP_UNAVAIL;
529                 layer1->blocks_free = 0;
530                 hammer_crc_set_layer1(layer1);
531         }
532         assert(i == HAMMER_BIGBLOCK_SIZE);
533         rel_buffer(buffer);
534
535         blockmap = &root_vol->ondisk->vol0_blockmap[HAMMER_ZONE_FREEMAP_INDEX];
536         bzero(blockmap, sizeof(*blockmap));
537         blockmap->phys_offset = layer1_offset;
538         blockmap->first_offset = 0;
539         blockmap->next_offset = HAMMER_ENCODE_RAW_BUFFER(0, 0);
540         blockmap->alloc_offset = HAMMER_ENCODE_RAW_BUFFER(255, -1);
541         hammer_crc_set_blockmap(blockmap);
542 }
543
544 /*
545  * Load the volume's remaining free space into the freemap.
546  *
547  * Returns the number of big-blocks available.
548  */
549 int64_t
550 initialize_freemap(struct volume_info *vol)
551 {
552         struct volume_info *root_vol;
553         struct buffer_info *buffer1 = NULL;
554         struct buffer_info *buffer2 = NULL;
555         hammer_blockmap_layer1_t layer1;
556         hammer_blockmap_layer2_t layer2;
557         hammer_off_t layer1_offset;
558         hammer_off_t layer2_offset;
559         hammer_off_t phys_offset;
560         hammer_off_t block_offset;
561         hammer_off_t aligned_vol_free_end;
562         hammer_blockmap_t freemap;
563         int64_t count = 0;
564         int64_t layer1_count = 0;
565
566         root_vol = get_root_volume();
567
568         assert_volume_offset(vol);
569         aligned_vol_free_end = HAMMER_BLOCKMAP_LAYER2_DOALIGN(vol->vol_free_end);
570
571         printf("initialize freemap volume %d\n", vol->vol_no);
572
573         /*
574          * Initialize the freemap.  First preallocate the big-blocks required
575          * to implement layer2.   This preallocation is a bootstrap allocation
576          * using blocks from the target volume.
577          */
578         freemap = &root_vol->ondisk->vol0_blockmap[HAMMER_ZONE_FREEMAP_INDEX];
579
580         for (phys_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no, 0);
581              phys_offset < aligned_vol_free_end;
582              phys_offset += HAMMER_BLOCKMAP_LAYER2) {
583                 layer1_offset = freemap->phys_offset +
584                                 HAMMER_BLOCKMAP_LAYER1_OFFSET(phys_offset);
585                 layer1 = get_buffer_data(layer1_offset, &buffer1, 0);
586                 if (layer1->phys_offset == HAMMER_BLOCKMAP_UNAVAIL) {
587                         layer1->phys_offset = bootstrap_bigblock(vol);
588                         layer1->blocks_free = 0;
589                         buffer1->cache.modified = 1;
590                         hammer_crc_set_layer1(layer1);
591                 }
592         }
593
594         /*
595          * Now fill everything in.
596          */
597         for (phys_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no, 0);
598              phys_offset < aligned_vol_free_end;
599              phys_offset += HAMMER_BLOCKMAP_LAYER2) {
600                 layer1_count = 0;
601                 layer1_offset = freemap->phys_offset +
602                                 HAMMER_BLOCKMAP_LAYER1_OFFSET(phys_offset);
603                 layer1 = get_buffer_data(layer1_offset, &buffer1, 0);
604                 assert(layer1->phys_offset != HAMMER_BLOCKMAP_UNAVAIL);
605
606                 for (block_offset = 0;
607                      block_offset < HAMMER_BLOCKMAP_LAYER2;
608                      block_offset += HAMMER_BIGBLOCK_SIZE) {
609                         layer2_offset = layer1->phys_offset +
610                                         HAMMER_BLOCKMAP_LAYER2_OFFSET(block_offset);
611                         layer2 = get_buffer_data(layer2_offset, &buffer2, 0);
612                         bzero(layer2, sizeof(*layer2));
613
614                         if (phys_offset + block_offset < vol->vol_free_off) {
615                                 /*
616                                  * Big-blocks already allocated as part
617                                  * of the freemap bootstrap.
618                                  */
619                                 layer2->zone = HAMMER_ZONE_FREEMAP_INDEX;
620                                 layer2->append_off = HAMMER_BIGBLOCK_SIZE;
621                                 layer2->bytes_free = 0;
622                         } else if (phys_offset + block_offset < vol->vol_free_end) {
623                                 layer2->zone = 0;
624                                 layer2->append_off = 0;
625                                 layer2->bytes_free = HAMMER_BIGBLOCK_SIZE;
626                                 ++count;
627                                 ++layer1_count;
628                         } else {
629                                 layer2->zone = HAMMER_ZONE_UNAVAIL_INDEX;
630                                 layer2->append_off = HAMMER_BIGBLOCK_SIZE;
631                                 layer2->bytes_free = 0;
632                         }
633                         hammer_crc_set_layer2(layer2);
634                         buffer2->cache.modified = 1;
635                 }
636
637                 layer1->blocks_free += layer1_count;
638                 hammer_crc_set_layer1(layer1);
639                 buffer1->cache.modified = 1;
640         }
641
642         rel_buffer(buffer1);
643         rel_buffer(buffer2);
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
661         assert_volume_offset(vol);
662         aligned_vol_free_end = HAMMER_BLOCKMAP_LAYER2_DOALIGN(vol->vol_free_end);
663
664         if (vol->vol_no == HAMMER_ROOT_VOLNO)
665                 vol_free_off += HAMMER_BIGBLOCK_SIZE;
666
667         for (phys_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no, 0);
668              phys_offset < aligned_vol_free_end;
669              phys_offset += HAMMER_BLOCKMAP_LAYER2) {
670                 vol_free_off += HAMMER_BIGBLOCK_SIZE;
671         }
672
673         for (phys_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no, 0);
674              phys_offset < aligned_vol_free_end;
675              phys_offset += HAMMER_BIGBLOCK_SIZE) {
676                 if (phys_offset < vol_free_off) {
677                         ;
678                 } else if (phys_offset < vol->vol_free_end) {
679                         ++count;
680                 }
681         }
682
683         return(count);
684 }
685
686 /*
687  * Format the undomap for the root volume.
688  */
689 void
690 format_undomap(struct volume_info *root_vol, int64_t *undo_buffer_size)
691 {
692         hammer_off_t undo_limit;
693         hammer_blockmap_t blockmap;
694         hammer_volume_ondisk_t 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 == HAMMER_ROOT_VOLNO);
703         ondisk = root_vol->ondisk;
704
705         /*
706          * Size the undo buffer in multiples of HAMMER_BIGBLOCK_SIZE,
707          * up to HAMMER_MAX_UNDO_BIGBLOCKS big-blocks.
708          * Size to approximately 0.1% of the disk.
709          *
710          * The minimum UNDO fifo size is 512MB, 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 = *undo_buffer_size;
717         if (undo_limit == 0) {
718                 undo_limit = HAMMER_VOL_BUF_SIZE(ondisk) / 1000;
719                 if (undo_limit < HAMMER_BIGBLOCK_SIZE * HAMMER_MIN_UNDO_BIGBLOCKS)
720                         undo_limit = HAMMER_BIGBLOCK_SIZE * HAMMER_MIN_UNDO_BIGBLOCKS;
721         }
722         undo_limit = HAMMER_BIGBLOCK_DOALIGN(undo_limit);
723         if (undo_limit < HAMMER_BIGBLOCK_SIZE)
724                 undo_limit = HAMMER_BIGBLOCK_SIZE;
725         if (undo_limit > HAMMER_BIGBLOCK_SIZE * HAMMER_MAX_UNDO_BIGBLOCKS)
726                 undo_limit = HAMMER_BIGBLOCK_SIZE * HAMMER_MAX_UNDO_BIGBLOCKS;
727         *undo_buffer_size = undo_limit;
728
729         blockmap = &ondisk->vol0_blockmap[HAMMER_ZONE_UNDO_INDEX];
730         bzero(blockmap, sizeof(*blockmap));
731         blockmap->phys_offset = HAMMER_BLOCKMAP_UNAVAIL;
732         blockmap->first_offset = HAMMER_ENCODE_UNDO(0);
733         blockmap->next_offset = blockmap->first_offset;
734         blockmap->alloc_offset = HAMMER_ENCODE_UNDO(undo_limit);
735         hammer_crc_set_blockmap(blockmap);
736
737         limit_index = undo_limit / HAMMER_BIGBLOCK_SIZE;
738         assert(limit_index <= HAMMER_MAX_UNDO_BIGBLOCKS);
739
740         for (n = 0; n < limit_index; ++n) {
741                 ondisk->vol0_undo_array[n] = alloc_undo_bigblock(root_vol);
742         }
743         while (n < HAMMER_MAX_UNDO_BIGBLOCKS) {
744                 ondisk->vol0_undo_array[n++] = HAMMER_BLOCKMAP_UNAVAIL;
745         }
746
747         /*
748          * Pre-initialize the UNDO blocks (HAMMER version 4+)
749          */
750         printf("initializing the undo map (%jd MB)\n",
751                 (intmax_t)HAMMER_OFF_LONG_ENCODE(blockmap->alloc_offset) /
752                 (1024 * 1024));
753
754         scan = blockmap->first_offset;
755         seqno = 0;
756
757         while (scan < blockmap->alloc_offset) {
758                 hammer_fifo_head_t head;
759                 hammer_fifo_tail_t tail;
760                 int isnew;
761                 int bytes = HAMMER_UNDO_ALIGN;
762
763                 isnew = ((scan & HAMMER_BUFMASK64) == 0);
764                 head = get_buffer_data(scan, &buffer, isnew);
765                 buffer->cache.modified = 1;
766                 tail = (void *)((char *)head + bytes - sizeof(*tail));
767
768                 bzero(head, bytes);
769                 head->hdr_signature = HAMMER_HEAD_SIGNATURE;
770                 head->hdr_type = HAMMER_HEAD_TYPE_DUMMY;
771                 head->hdr_size = bytes;
772                 head->hdr_seq = seqno++;
773
774                 tail->tail_signature = HAMMER_TAIL_SIGNATURE;
775                 tail->tail_type = HAMMER_HEAD_TYPE_DUMMY;
776                 tail->tail_size = bytes;
777
778                 hammer_crc_set_fifo_head(head, bytes);
779
780                 scan += bytes;
781         }
782         rel_buffer(buffer);
783 }
784
785 const char *zone_labels[] = {
786         "",             /* 0 */
787         "raw_volume",   /* 1 */
788         "raw_buffer",   /* 2 */
789         "undo",         /* 3 */
790         "freemap",      /* 4 */
791         "",             /* 5 */
792         "",             /* 6 */
793         "",             /* 7 */
794         "btree",        /* 8 */
795         "meta",         /* 9 */
796         "large_data",   /* 10 */
797         "small_data",   /* 11 */
798         "",             /* 12 */
799         "",             /* 13 */
800         "",             /* 14 */
801         "unavail",      /* 15 */
802 };
803
804 void
805 print_blockmap(const struct volume_info *vol)
806 {
807         hammer_blockmap_t blockmap;
808         hammer_volume_ondisk_t ondisk;
809         int64_t size, used;
810         int i;
811 #define INDENT ""
812
813         ondisk = vol->ondisk;
814         printf(INDENT"vol_label\t%s\n", ondisk->vol_label);
815         printf(INDENT"vol_count\t%d\n", ondisk->vol_count);
816         printf(INDENT"vol_bot_beg\t%s\n", sizetostr(ondisk->vol_bot_beg));
817         printf(INDENT"vol_mem_beg\t%s\n", sizetostr(ondisk->vol_mem_beg));
818         printf(INDENT"vol_buf_beg\t%s\n", sizetostr(ondisk->vol_buf_beg));
819         printf(INDENT"vol_buf_end\t%s\n", sizetostr(ondisk->vol_buf_end));
820         printf(INDENT"vol0_next_tid\t%016jx\n",
821                (uintmax_t)ondisk->vol0_next_tid);
822
823         blockmap = &ondisk->vol0_blockmap[HAMMER_ZONE_UNDO_INDEX];
824         size = HAMMER_OFF_LONG_ENCODE(blockmap->alloc_offset);
825         if (blockmap->first_offset <= blockmap->next_offset)
826                 used = blockmap->next_offset - blockmap->first_offset;
827         else
828                 used = blockmap->alloc_offset - blockmap->first_offset +
829                         HAMMER_OFF_LONG_ENCODE(blockmap->next_offset);
830         printf(INDENT"undo_size\t%s\n", sizetostr(size));
831         printf(INDENT"undo_used\t%s\n", sizetostr(used));
832
833         printf(INDENT"zone #             "
834                "phys             first            next             alloc\n");
835         for (i = 0; i < HAMMER_MAX_ZONES; i++) {
836                 blockmap = &ondisk->vol0_blockmap[i];
837                 printf(INDENT"zone %-2d %-10s %016jx %016jx %016jx %016jx\n",
838                         i, zone_labels[i],
839                         (uintmax_t)blockmap->phys_offset,
840                         (uintmax_t)blockmap->first_offset,
841                         (uintmax_t)blockmap->next_offset,
842                         (uintmax_t)blockmap->alloc_offset);
843         }
844 }
845
846 /*
847  * Flush various tracking structures to disk
848  */
849 void
850 flush_all_volumes(void)
851 {
852         struct volume_info *vol;
853
854         TAILQ_FOREACH(vol, &VolList, entry)
855                 flush_volume(vol);
856 }
857
858 void
859 flush_volume(struct volume_info *volume)
860 {
861         struct buffer_info *buffer;
862         int i;
863
864         for (i = 0; i < HAMMER_BUFLISTS; ++i) {
865                 TAILQ_FOREACH(buffer, &volume->buffer_lists[i], entry)
866                         flush_buffer(buffer);
867         }
868         if (writehammervol(volume) == -1)
869                 err(1, "Write volume %d (%s)", volume->vol_no, volume->name);
870 }
871
872 void
873 flush_buffer(struct buffer_info *buffer)
874 {
875         struct volume_info *vol;
876
877         vol = buffer->volume;
878         if (writehammerbuf(buffer) == -1)
879                 err(1, "Write volume %d (%s)", vol->vol_no, vol->name);
880         buffer->cache.modified = 0;
881 }
882
883 /*
884  * Core I/O operations
885  */
886 static int
887 __read(struct volume_info *vol, void *data, int64_t offset, int size)
888 {
889         ssize_t n;
890
891         n = pread(vol->fd, data, size, offset);
892         if (n != size)
893                 return(-1);
894         return(0);
895 }
896
897 static __inline int
898 readhammervol(struct volume_info *vol)
899 {
900         return(__read(vol, vol->ondisk, 0, HAMMER_BUFSIZE));
901 }
902
903 static __inline int
904 readhammerbuf(struct buffer_info *buf)
905 {
906         return(__read(buf->volume, buf->ondisk, buf->raw_offset, HAMMER_BUFSIZE));
907 }
908
909 static int
910 __write(struct volume_info *vol, const void *data, int64_t offset, int size)
911 {
912         ssize_t n;
913
914         if (vol->rdonly)
915                 return(0);
916
917         n = pwrite(vol->fd, data, size, offset);
918         if (n != size)
919                 return(-1);
920         return(0);
921 }
922
923 static __inline int
924 writehammervol(struct volume_info *vol)
925 {
926         return(__write(vol, vol->ondisk, 0, HAMMER_BUFSIZE));
927 }
928
929 static __inline int
930 writehammerbuf(struct buffer_info *buf)
931 {
932         return(__write(buf->volume, buf->ondisk, buf->raw_offset, HAMMER_BUFSIZE));
933 }
934
935 int64_t init_boot_area_size(int64_t value, off_t avg_vol_size)
936 {
937         if (value == 0) {
938                 value = HAMMER_BOOT_NOMBYTES;
939                 while (value > avg_vol_size / HAMMER_MAX_VOLUMES)
940                         value >>= 1;
941         }
942
943         if (value < HAMMER_BOOT_MINBYTES) {
944                 value = HAMMER_BOOT_MINBYTES;
945         } else if (value > HAMMER_BOOT_MAXBYTES) {
946                 value = HAMMER_BOOT_MAXBYTES;
947         }
948
949         return(value);
950 }
951
952 int64_t init_memory_log_size(int64_t value, off_t avg_vol_size)
953 {
954         if (value == 0) {
955                 value = HAMMER_MEM_NOMBYTES;
956                 while (value > avg_vol_size / HAMMER_MAX_VOLUMES)
957                         value >>= 1;
958         }
959
960         if (value < HAMMER_MEM_MINBYTES) {
961                 value = HAMMER_MEM_MINBYTES;
962         } else if (value > HAMMER_MEM_MAXBYTES) {
963                 value = HAMMER_MEM_MAXBYTES;
964         }
965
966         return(value);
967 }