sbin/hammer: Move COLLECT_XXX macros to cmd_blockmap.c
[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/types.h>
36 #include <assert.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <stdarg.h>
40 #include <string.h>
41 #include <unistd.h>
42 #include <stddef.h>
43 #include <err.h>
44 #include <fcntl.h>
45 #include "hammer_util.h"
46
47 static void *alloc_blockmap(int zone, int bytes, hammer_off_t *result_offp,
48                         struct buffer_info **bufferp);
49 static hammer_off_t alloc_bigblock(struct volume_info *volume, int zone);
50 static void get_buffer_readahead(struct buffer_info *base);
51 static __inline void *get_ondisk(hammer_off_t buf_offset,
52                         struct buffer_info **bufferp, int isnew);
53 #if 0
54 static void init_fifo_head(hammer_fifo_head_t head, u_int16_t hdr_type);
55 static void readhammerbuf(struct volume_info *vol, void *data,
56                         int64_t offset);
57 #endif
58 static void writehammerbuf(struct volume_info *vol, const void *data,
59                         int64_t offset);
60
61 int DebugOpt;
62
63 uuid_t Hammer_FSType;
64 uuid_t Hammer_FSId;
65 int64_t BootAreaSize;
66 int64_t MemAreaSize;
67 int64_t UndoBufferSize;
68 int     UsingSuperClusters;
69 int     NumVolumes;
70 int     RootVolNo = -1;
71 int     UseReadBehind = -4;
72 int     UseReadAhead = 4;
73 int     AssertOnFailure = 1;
74 struct volume_list VolList = TAILQ_HEAD_INITIALIZER(VolList);
75
76 static __inline
77 int
78 buffer_hash(hammer_off_t buf_offset)
79 {
80         int hi;
81
82         hi = (int)(buf_offset / HAMMER_BUFSIZE) & HAMMER_BUFLISTMASK;
83         return(hi);
84 }
85
86 /*
87  * Lookup the requested information structure and related on-disk buffer.
88  * Missing structures are created.
89  */
90 struct volume_info *
91 setup_volume(int32_t vol_no, const char *filename, int isnew, int oflags)
92 {
93         struct volume_info *vol;
94         struct volume_info *scan;
95         struct hammer_volume_ondisk *ondisk;
96         int i, n;
97
98         /*
99          * Allocate the volume structure
100          */
101         vol = malloc(sizeof(*vol));
102         bzero(vol, sizeof(*vol));
103         for (i = 0; i < HAMMER_BUFLISTS; ++i)
104                 TAILQ_INIT(&vol->buffer_lists[i]);
105         vol->name = strdup(filename);
106         vol->fd = open(filename, oflags);
107         if (vol->fd < 0) {
108                 free(vol->name);
109                 free(vol);
110                 err(1, "setup_volume: %s: Open failed", filename);
111         }
112
113         /*
114          * Read or initialize the volume header
115          */
116         vol->ondisk = ondisk = malloc(HAMMER_BUFSIZE);
117         if (isnew > 0) {
118                 bzero(ondisk, HAMMER_BUFSIZE);
119         } else {
120                 n = pread(vol->fd, ondisk, HAMMER_BUFSIZE, 0);
121                 if (n != HAMMER_BUFSIZE) {
122                         err(1, "setup_volume: %s: Read failed at offset 0",
123                             filename);
124                 }
125                 vol_no = ondisk->vol_no;
126                 if (RootVolNo < 0) {
127                         RootVolNo = ondisk->vol_rootvol;
128                 } else if (RootVolNo != (int)ondisk->vol_rootvol) {
129                         errx(1, "setup_volume: %s: root volume disagreement: "
130                                 "%d vs %d",
131                                 vol->name, RootVolNo, ondisk->vol_rootvol);
132                 }
133
134                 if (bcmp(&Hammer_FSType, &ondisk->vol_fstype, sizeof(Hammer_FSType)) != 0) {
135                         errx(1, "setup_volume: %s: Header does not indicate "
136                                 "that this is a hammer volume", vol->name);
137                 }
138                 if (TAILQ_EMPTY(&VolList)) {
139                         Hammer_FSId = vol->ondisk->vol_fsid;
140                 } else if (bcmp(&Hammer_FSId, &ondisk->vol_fsid, sizeof(Hammer_FSId)) != 0) {
141                         errx(1, "setup_volume: %s: FSId does match other "
142                                 "volumes!", vol->name);
143                 }
144         }
145         vol->vol_no = vol_no;
146
147         if (isnew > 0) {
148                 /*init_fifo_head(&ondisk->head, HAMMER_HEAD_TYPE_VOL);*/
149                 vol->cache.modified = 1;
150         }
151
152         /*
153          * Link the volume structure in
154          */
155         TAILQ_FOREACH(scan, &VolList, entry) {
156                 if (scan->vol_no == vol_no) {
157                         errx(1, "setup_volume %s: Duplicate volume number %d "
158                                 "against %s", filename, vol_no, scan->name);
159                 }
160         }
161         TAILQ_INSERT_TAIL(&VolList, vol, entry);
162         return(vol);
163 }
164
165 struct volume_info *
166 test_volume(int32_t vol_no)
167 {
168         struct volume_info *vol;
169
170         TAILQ_FOREACH(vol, &VolList, entry) {
171                 if (vol->vol_no == vol_no)
172                         break;
173         }
174         if (vol == NULL)
175                 return(NULL);
176         ++vol->cache.refs;
177         /* not added to or removed from hammer cache */
178         return(vol);
179 }
180
181 struct volume_info *
182 get_volume(int32_t vol_no)
183 {
184         struct volume_info *vol;
185
186         TAILQ_FOREACH(vol, &VolList, entry) {
187                 if (vol->vol_no == vol_no)
188                         break;
189         }
190         if (vol == NULL)
191                 errx(1, "get_volume: Volume %d does not exist!", vol_no);
192         ++vol->cache.refs;
193         /* not added to or removed from hammer cache */
194         return(vol);
195 }
196
197 void
198 rel_volume(struct volume_info *volume)
199 {
200         /* not added to or removed from hammer cache */
201         --volume->cache.refs;
202 }
203
204 /*
205  * Acquire the specified buffer.
206  */
207 struct buffer_info *
208 get_buffer(hammer_off_t buf_offset, int isnew)
209 {
210         void *ondisk;
211         struct buffer_info *buf;
212         struct volume_info *volume;
213         hammer_off_t orig_offset = buf_offset;
214         int vol_no;
215         int zone;
216         int hi, n;
217         int dora = 0;
218
219         zone = HAMMER_ZONE_DECODE(buf_offset);
220         if (zone > HAMMER_ZONE_RAW_BUFFER_INDEX) {
221                 buf_offset = blockmap_lookup(buf_offset, NULL, NULL, NULL);
222         }
223         if (buf_offset == HAMMER_OFF_BAD)
224                 return(NULL);
225
226         if (AssertOnFailure) {
227                 assert((buf_offset & HAMMER_OFF_ZONE_MASK) ==
228                        HAMMER_ZONE_RAW_BUFFER);
229         }
230         vol_no = HAMMER_VOL_DECODE(buf_offset);
231         volume = test_volume(vol_no);
232         if (volume == NULL) {
233                 if (AssertOnFailure)
234                         errx(1, "get_buffer: Volume %d not found!", vol_no);
235                 return(NULL);
236         }
237
238         buf_offset &= ~HAMMER_BUFMASK64;
239
240         hi = buffer_hash(buf_offset);
241
242         TAILQ_FOREACH(buf, &volume->buffer_lists[hi], entry) {
243                 if (buf->buf_offset == buf_offset)
244                         break;
245         }
246         if (buf == NULL) {
247                 buf = malloc(sizeof(*buf));
248                 bzero(buf, sizeof(*buf));
249                 if (DebugOpt) {
250                         fprintf(stderr, "get_buffer: %016llx %016llx at %p\n",
251                                 (long long)orig_offset, (long long)buf_offset,
252                                 buf);
253                 }
254                 buf->buf_offset = buf_offset;
255                 buf->raw_offset = volume->ondisk->vol_buf_beg +
256                                   (buf_offset & HAMMER_OFF_SHORT_MASK);
257                 buf->volume = volume;
258                 TAILQ_INSERT_TAIL(&volume->buffer_lists[hi], buf, entry);
259                 ++volume->cache.refs;
260                 buf->cache.u.buffer = buf;
261                 hammer_cache_add(&buf->cache, ISBUFFER);
262                 dora = (isnew == 0);
263                 if (isnew < 0)
264                         buf->flags |= HAMMER_BUFINFO_READAHEAD;
265         } else {
266                 if (DebugOpt) {
267                         fprintf(stderr, "get_buffer: %016llx %016llx at %p *\n",
268                                 (long long)orig_offset, (long long)buf_offset,
269                                 buf);
270                 }
271                 if (isnew >= 0) {
272                         buf->flags &= ~HAMMER_BUFINFO_READAHEAD;
273                         hammer_cache_used(&buf->cache);
274                 }
275                 ++buf->use_count;
276         }
277         ++buf->cache.refs;
278         hammer_cache_flush();
279         if ((ondisk = buf->ondisk) == NULL) {
280                 buf->ondisk = ondisk = malloc(HAMMER_BUFSIZE);
281                 if (isnew <= 0) {
282                         n = pread(volume->fd, ondisk, HAMMER_BUFSIZE,
283                                   buf->raw_offset);
284                         if (n != HAMMER_BUFSIZE) {
285                                 if (AssertOnFailure)
286                                         err(1, "get_buffer: %s:%016llx "
287                                             "Read failed at offset %016llx",
288                                             volume->name,
289                                             (long long)buf->buf_offset,
290                                             (long long)buf->raw_offset);
291                                 bzero(ondisk, HAMMER_BUFSIZE);
292                         }
293                 }
294         }
295         if (isnew > 0) {
296                 bzero(ondisk, HAMMER_BUFSIZE);
297                 buf->cache.modified = 1;
298         }
299         if (dora)
300                 get_buffer_readahead(buf);
301         return(buf);
302 }
303
304 static void
305 get_buffer_readahead(struct buffer_info *base)
306 {
307         struct buffer_info *buf;
308         struct volume_info *vol;
309         hammer_off_t buf_offset;
310         int64_t raw_offset;
311         int ri = UseReadBehind;
312         int re = UseReadAhead;
313         int hi;
314
315         raw_offset = base->raw_offset + ri * HAMMER_BUFSIZE;
316         vol = base->volume;
317
318         while (ri < re) {
319                 if (raw_offset >= vol->ondisk->vol_buf_end)
320                         break;
321                 if (raw_offset < vol->ondisk->vol_buf_beg) {
322                         ++ri;
323                         raw_offset += HAMMER_BUFSIZE;
324                         continue;
325                 }
326                 buf_offset = HAMMER_VOL_ENCODE(vol->vol_no) |
327                              HAMMER_ZONE_RAW_BUFFER |
328                              (raw_offset - vol->ondisk->vol_buf_beg);
329                 hi = buffer_hash(raw_offset);
330                 TAILQ_FOREACH(buf, &vol->buffer_lists[hi], entry) {
331                         if (buf->raw_offset == raw_offset)
332                                 break;
333                 }
334                 if (buf == NULL) {
335                         buf = get_buffer(buf_offset, -1);
336                         rel_buffer(buf);
337                 }
338                 ++ri;
339                 raw_offset += HAMMER_BUFSIZE;
340         }
341 }
342
343 void
344 rel_buffer(struct buffer_info *buffer)
345 {
346         struct volume_info *volume;
347         int hi;
348
349         assert(buffer->cache.refs > 0);
350         if (--buffer->cache.refs == 0) {
351                 if (buffer->cache.delete) {
352                         hi = buffer_hash(buffer->buf_offset);
353                         volume = buffer->volume;
354                         if (buffer->cache.modified)
355                                 flush_buffer(buffer);
356                         TAILQ_REMOVE(&volume->buffer_lists[hi], buffer, entry);
357                         hammer_cache_del(&buffer->cache);
358                         free(buffer->ondisk);
359                         free(buffer);
360                         rel_volume(volume);
361                 }
362         }
363 }
364
365 /*
366  * Retrieve a pointer to a buffer data given a buffer offset.  The underlying
367  * bufferp is freed if isnew or the offset is out of range of the cached data.
368  * If bufferp is freed a referenced buffer is loaded into it.
369  */
370 void *
371 get_buffer_data(hammer_off_t buf_offset, struct buffer_info **bufferp,
372                 int isnew)
373 {
374         if (*bufferp != NULL) {
375                 if (isnew > 0 ||
376                     (((*bufferp)->buf_offset ^ buf_offset) & ~HAMMER_BUFMASK64)) {
377                         rel_buffer(*bufferp);
378                         *bufferp = NULL;
379                 }
380         }
381         return(get_ondisk(buf_offset, bufferp, isnew));
382 }
383
384 /*
385  * Retrieve a pointer to a B-Tree node given a cluster offset.  The underlying
386  * bufferp is freed if non-NULL and a referenced buffer is loaded into it.
387  */
388 hammer_node_ondisk_t
389 get_node(hammer_off_t node_offset, struct buffer_info **bufferp)
390 {
391         if (*bufferp != NULL) {
392                 rel_buffer(*bufferp);
393                 *bufferp = NULL;
394         }
395         return(get_ondisk(node_offset, bufferp, 0));
396 }
397
398 /*
399  * Return a pointer to a buffer data given a buffer offset.
400  * If *bufferp is NULL acquire the buffer otherwise use that buffer.
401  */
402 static __inline
403 void *
404 get_ondisk(hammer_off_t buf_offset, struct buffer_info **bufferp,
405         int isnew)
406 {
407         struct buffer_info *buffer;
408
409         buffer = *bufferp;
410         if (buffer == NULL) {
411                 buffer = *bufferp = get_buffer(buf_offset, isnew);
412                 if (buffer == NULL)
413                         return(NULL);
414         }
415
416         return((char *)buffer->ondisk +
417                 ((int32_t)buf_offset & HAMMER_BUFMASK));
418 }
419
420 /*
421  * Allocate HAMMER elements - btree nodes, data storage
422  */
423 void *
424 alloc_btree_element(hammer_off_t *offp)
425 {
426         struct buffer_info *buffer = NULL;
427         hammer_node_ondisk_t node;
428
429         node = alloc_blockmap(HAMMER_ZONE_BTREE_INDEX, sizeof(*node),
430                               offp, &buffer);
431         bzero(node, sizeof(*node));
432         /* XXX buffer not released, pointer remains valid */
433         return(node);
434 }
435
436 void *
437 alloc_data_element(hammer_off_t *offp, int32_t data_len,
438                    struct buffer_info **data_bufferp)
439 {
440         void *data;
441
442         if (data_len >= HAMMER_BUFSIZE) {
443                 assert(data_len <= HAMMER_BUFSIZE); /* just one buffer */
444                 data = alloc_blockmap(HAMMER_ZONE_LARGE_DATA_INDEX, data_len,
445                                       offp, data_bufferp);
446                 bzero(data, data_len);
447         } else if (data_len) {
448                 data = alloc_blockmap(HAMMER_ZONE_SMALL_DATA_INDEX, data_len,
449                                       offp, data_bufferp);
450                 bzero(data, data_len);
451         } else {
452                 data = NULL;
453         }
454         return (data);
455 }
456
457 /*
458  * Format a new freemap.  Set all layer1 entries to UNAVAIL.  The initialize
459  * code will load each volume's freemap.
460  */
461 void
462 format_freemap(struct volume_info *root_vol, hammer_blockmap_t blockmap)
463 {
464         struct buffer_info *buffer = NULL;
465         hammer_off_t layer1_offset;
466         struct hammer_blockmap_layer1 *layer1;
467         int i, isnew;
468
469         layer1_offset = alloc_bigblock(root_vol, HAMMER_ZONE_FREEMAP_INDEX);
470         for (i = 0; i < (int)HAMMER_BLOCKMAP_RADIX1; ++i) {
471                 isnew = ((i % HAMMER_BLOCKMAP_RADIX1_PERBUFFER) == 0);
472                 layer1 = get_buffer_data(layer1_offset + i * sizeof(*layer1),
473                                          &buffer, isnew);
474                 bzero(layer1, sizeof(*layer1));
475                 layer1->phys_offset = HAMMER_BLOCKMAP_UNAVAIL;
476                 layer1->blocks_free = 0;
477                 layer1->layer1_crc = crc32(layer1, HAMMER_LAYER1_CRCSIZE);
478         }
479         rel_buffer(buffer);
480
481         blockmap = &root_vol->ondisk->vol0_blockmap[HAMMER_ZONE_FREEMAP_INDEX];
482         blockmap->phys_offset = layer1_offset;
483         blockmap->alloc_offset = HAMMER_ENCODE_RAW_BUFFER(255, -1);
484         blockmap->next_offset = HAMMER_ENCODE_RAW_BUFFER(0, 0);
485         blockmap->reserved01 = 0;
486         blockmap->entry_crc = crc32(blockmap, HAMMER_BLOCKMAP_CRCSIZE);
487         root_vol->cache.modified = 1;
488 }
489
490 /*
491  * Load the volume's remaining free space into the freemap.
492  *
493  * Returns the number of bigblocks available.
494  */
495 int64_t
496 initialize_freemap(struct volume_info *vol)
497 {
498         struct volume_info *root_vol;
499         struct buffer_info *buffer1 = NULL;
500         struct buffer_info *buffer2 = NULL;
501         struct hammer_blockmap_layer1 *layer1;
502         struct hammer_blockmap_layer2 *layer2;
503         hammer_off_t layer1_base;
504         hammer_off_t layer1_offset;
505         hammer_off_t layer2_offset;
506         hammer_off_t phys_offset;
507         hammer_off_t aligned_vol_free_end;
508         int64_t count = 0;
509         int modified1 = 0;
510
511         root_vol = get_volume(RootVolNo);
512         aligned_vol_free_end = (vol->vol_free_end + HAMMER_BLOCKMAP_LAYER2_MASK)
513                                 & ~HAMMER_BLOCKMAP_LAYER2_MASK;
514
515         printf("initialize freemap volume %d\n", vol->vol_no);
516
517         /*
518          * Initialize the freemap.  First preallocate the bigblocks required
519          * to implement layer2.   This preallocation is a bootstrap allocation
520          * using blocks from the target volume.
521          */
522         layer1_base = root_vol->ondisk->vol0_blockmap[
523                                         HAMMER_ZONE_FREEMAP_INDEX].phys_offset;
524         for (phys_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no, 0);
525              phys_offset < aligned_vol_free_end;
526              phys_offset += HAMMER_BLOCKMAP_LAYER2) {
527                 layer1_offset = layer1_base +
528                                 HAMMER_BLOCKMAP_LAYER1_OFFSET(phys_offset);
529                 layer1 = get_buffer_data(layer1_offset, &buffer1, 0);
530                 if (layer1->phys_offset == HAMMER_BLOCKMAP_UNAVAIL) {
531                         layer1->phys_offset = alloc_bigblock(vol,
532                                                 HAMMER_ZONE_FREEMAP_INDEX);
533                         layer1->blocks_free = 0;
534                         buffer1->cache.modified = 1;
535                         layer1->layer1_crc = crc32(layer1,
536                                                    HAMMER_LAYER1_CRCSIZE);
537                 }
538         }
539
540         /*
541          * Now fill everything in.
542          */
543         for (phys_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no, 0);
544              phys_offset < aligned_vol_free_end;
545              phys_offset += HAMMER_BIGBLOCK_SIZE) {
546                 modified1 = 0;
547                 layer1_offset = layer1_base +
548                                 HAMMER_BLOCKMAP_LAYER1_OFFSET(phys_offset);
549                 layer1 = get_buffer_data(layer1_offset, &buffer1, 0);
550
551                 assert(layer1->phys_offset != HAMMER_BLOCKMAP_UNAVAIL);
552                 layer2_offset = layer1->phys_offset +
553                                 HAMMER_BLOCKMAP_LAYER2_OFFSET(phys_offset);
554
555                 layer2 = get_buffer_data(layer2_offset, &buffer2, 0);
556                 bzero(layer2, sizeof(*layer2));
557                 if (phys_offset < vol->vol_free_off) {
558                         /*
559                          * Fixups XXX - bigblocks already allocated as part
560                          * of the freemap bootstrap.
561                          */
562                         if (layer2->zone == 0) {
563                                 layer2->zone = HAMMER_ZONE_FREEMAP_INDEX;
564                                 layer2->append_off = HAMMER_BIGBLOCK_SIZE;
565                                 layer2->bytes_free = 0;
566                         }
567                 } else if (phys_offset < vol->vol_free_end) {
568                         ++layer1->blocks_free;
569                         buffer1->cache.modified = 1;
570                         layer2->zone = 0;
571                         layer2->append_off = 0;
572                         layer2->bytes_free = HAMMER_BIGBLOCK_SIZE;
573                         ++count;
574                         modified1 = 1;
575                 } else {
576                         layer2->zone = HAMMER_ZONE_UNAVAIL_INDEX;
577                         layer2->append_off = HAMMER_BIGBLOCK_SIZE;
578                         layer2->bytes_free = 0;
579                 }
580                 layer2->entry_crc = crc32(layer2, HAMMER_LAYER2_CRCSIZE);
581                 buffer2->cache.modified = 1;
582
583                 /*
584                  * Finish-up layer 1
585                  */
586                 if (modified1) {
587                         layer1->layer1_crc = crc32(layer1,
588                                                    HAMMER_LAYER1_CRCSIZE);
589                         buffer1->cache.modified = 1;
590                 }
591         }
592         rel_buffer(buffer1);
593         rel_buffer(buffer2);
594         rel_volume(root_vol);
595         return(count);
596 }
597
598 /*
599  * Allocate big-blocks using our poor-man's volume->vol_free_off.
600  *
601  * If the zone is HAMMER_ZONE_FREEMAP_INDEX we are bootstrapping the freemap
602  * itself and cannot update it yet.
603  */
604 hammer_off_t
605 alloc_bigblock(struct volume_info *volume, int zone)
606 {
607         struct buffer_info *buffer1 = NULL;
608         struct buffer_info *buffer2 = NULL;
609         struct volume_info *root_vol;
610         hammer_off_t result_offset;
611         hammer_off_t layer_offset;
612         struct hammer_blockmap_layer1 *layer1;
613         struct hammer_blockmap_layer2 *layer2;
614         int didget;
615
616         if (volume == NULL) {
617                 volume = get_volume(RootVolNo);
618                 didget = 1;
619         } else {
620                 didget = 0;
621         }
622         result_offset = volume->vol_free_off;
623         if (result_offset >= volume->vol_free_end)
624                 panic("alloc_bigblock: Ran out of room, filesystem too small");
625         volume->vol_free_off += HAMMER_BIGBLOCK_SIZE;
626
627         /*
628          * Update the freemap.
629          */
630         if (zone != HAMMER_ZONE_FREEMAP_INDEX) {
631                 root_vol = get_volume(RootVolNo);
632                 layer_offset = root_vol->ondisk->vol0_blockmap[
633                                         HAMMER_ZONE_FREEMAP_INDEX].phys_offset;
634                 layer_offset += HAMMER_BLOCKMAP_LAYER1_OFFSET(result_offset);
635                 layer1 = get_buffer_data(layer_offset, &buffer1, 0);
636                 assert(layer1->phys_offset != HAMMER_BLOCKMAP_UNAVAIL);
637                 --layer1->blocks_free;
638                 layer1->layer1_crc = crc32(layer1, HAMMER_LAYER1_CRCSIZE);
639                 buffer1->cache.modified = 1;
640                 layer_offset = layer1->phys_offset +
641                                HAMMER_BLOCKMAP_LAYER2_OFFSET(result_offset);
642                 layer2 = get_buffer_data(layer_offset, &buffer2, 0);
643                 assert(layer2->zone == 0);
644                 layer2->zone = zone;
645                 layer2->append_off = HAMMER_BIGBLOCK_SIZE;
646                 layer2->bytes_free = 0;
647                 layer2->entry_crc = crc32(layer2, HAMMER_LAYER2_CRCSIZE);
648                 buffer2->cache.modified = 1;
649
650                 --root_vol->ondisk->vol0_stat_freebigblocks;
651                 root_vol->cache.modified = 1;
652
653                 rel_buffer(buffer1);
654                 rel_buffer(buffer2);
655                 rel_volume(root_vol);
656         }
657
658         if (didget)
659                 rel_volume(volume);
660         return(result_offset);
661 }
662
663 /*
664  * Format the undo-map for the root volume.
665  */
666 void
667 format_undomap(hammer_volume_ondisk_t ondisk)
668 {
669         const int undo_zone = HAMMER_ZONE_UNDO_INDEX;
670         hammer_off_t undo_limit;
671         hammer_blockmap_t blockmap;
672         struct buffer_info *buffer = NULL;
673         hammer_off_t scan;
674         int n;
675         int limit_index;
676         u_int32_t seqno;
677
678         /*
679          * Size the undo buffer in multiples of HAMMER_BIGBLOCK_SIZE,
680          * up to HAMMER_UNDO_LAYER2 big blocks.  Size to approximately
681          * 0.1% of the disk.
682          *
683          * The minimum UNDO fifo size is 500MB, or approximately 1% of
684          * the recommended 50G disk.
685          *
686          * Changing this minimum is rather dangerous as complex filesystem
687          * operations can cause the UNDO FIFO to fill up otherwise.
688          */
689         undo_limit = UndoBufferSize;
690         if (undo_limit == 0) {
691                 undo_limit = (ondisk->vol_buf_end - ondisk->vol_buf_beg) / 1000;
692                 if (undo_limit < 500*1024*1024)
693                         undo_limit = 500*1024*1024;
694         }
695         undo_limit = (undo_limit + HAMMER_BIGBLOCK_MASK64) &
696                      ~HAMMER_BIGBLOCK_MASK64;
697         if (undo_limit < HAMMER_BIGBLOCK_SIZE)
698                 undo_limit = HAMMER_BIGBLOCK_SIZE;
699         if (undo_limit > HAMMER_BIGBLOCK_SIZE * HAMMER_UNDO_LAYER2)
700                 undo_limit = HAMMER_BIGBLOCK_SIZE * HAMMER_UNDO_LAYER2;
701         UndoBufferSize = undo_limit;
702
703         blockmap = &ondisk->vol0_blockmap[undo_zone];
704         bzero(blockmap, sizeof(*blockmap));
705         blockmap->phys_offset = HAMMER_BLOCKMAP_UNAVAIL;
706         blockmap->first_offset = HAMMER_ZONE_ENCODE(undo_zone, 0);
707         blockmap->next_offset = blockmap->first_offset;
708         blockmap->alloc_offset = HAMMER_ZONE_ENCODE(undo_zone, undo_limit);
709         blockmap->entry_crc = crc32(blockmap, HAMMER_BLOCKMAP_CRCSIZE);
710
711         n = 0;
712         scan = blockmap->next_offset;
713         limit_index = undo_limit / HAMMER_BIGBLOCK_SIZE;
714
715         assert(limit_index <= HAMMER_UNDO_LAYER2);
716
717         for (n = 0; n < limit_index; ++n) {
718                 ondisk->vol0_undo_array[n] = alloc_bigblock(NULL,
719                                                         HAMMER_ZONE_UNDO_INDEX);
720                 scan += HAMMER_BIGBLOCK_SIZE;
721         }
722         while (n < HAMMER_UNDO_LAYER2) {
723                 ondisk->vol0_undo_array[n] = HAMMER_BLOCKMAP_UNAVAIL;
724                 ++n;
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)(blockmap->alloc_offset & HAMMER_OFF_LONG_MASK) /
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                 head->hdr_crc = crc32(head, HAMMER_FIFO_HEAD_CRCOFF) ^
759                                 crc32(head + 1, bytes - sizeof(*head));
760
761                 scan += bytes;
762         }
763         if (buffer)
764                 rel_buffer(buffer);
765 }
766
767 /*
768  * Format a new blockmap.  This is mostly a degenerate case because
769  * all allocations are now actually done from the freemap.
770  */
771 void
772 format_blockmap(hammer_blockmap_t blockmap, hammer_off_t zone_base)
773 {
774         blockmap->phys_offset = 0;
775         blockmap->alloc_offset = zone_base | HAMMER_VOL_ENCODE(255) |
776                                  HAMMER_SHORT_OFF_ENCODE(-1);
777         blockmap->first_offset = zone_base;
778         blockmap->next_offset = zone_base;
779         blockmap->entry_crc = crc32(blockmap, HAMMER_BLOCKMAP_CRCSIZE);
780 }
781
782 /*
783  * Allocate a chunk of data out of a blockmap.  This is a simplified
784  * version which uses next_offset as a simple allocation iterator.
785  */
786 static
787 void *
788 alloc_blockmap(int zone, int bytes, hammer_off_t *result_offp,
789                struct buffer_info **bufferp)
790 {
791         struct buffer_info *buffer1 = NULL;
792         struct buffer_info *buffer2 = NULL;
793         struct volume_info *volume;
794         hammer_blockmap_t blockmap;
795         hammer_blockmap_t freemap;
796         struct hammer_blockmap_layer1 *layer1;
797         struct hammer_blockmap_layer2 *layer2;
798         hammer_off_t layer1_offset;
799         hammer_off_t layer2_offset;
800         hammer_off_t zone2_offset;
801         void *ptr;
802
803         volume = get_volume(RootVolNo);
804
805         blockmap = &volume->ondisk->vol0_blockmap[zone];
806         freemap = &volume->ondisk->vol0_blockmap[HAMMER_ZONE_FREEMAP_INDEX];
807
808         /*
809          * Alignment and buffer-boundary issues.  If the allocation would
810          * cross a buffer boundary we have to skip to the next buffer.
811          */
812         bytes = (bytes + 15) & ~15;
813
814 again:
815         if ((blockmap->next_offset ^ (blockmap->next_offset + bytes - 1)) &
816             ~HAMMER_BUFMASK64) {
817                 volume->cache.modified = 1;
818                 blockmap->next_offset = (blockmap->next_offset + bytes) &
819                                         ~HAMMER_BUFMASK64;
820         }
821
822         /*
823          * Dive layer 1.  For now we can't allocate data outside of volume 0.
824          */
825         layer1_offset = freemap->phys_offset +
826                         HAMMER_BLOCKMAP_LAYER1_OFFSET(blockmap->next_offset);
827
828         layer1 = get_buffer_data(layer1_offset, &buffer1, 0);
829
830         if (layer1->phys_offset == HAMMER_BLOCKMAP_UNAVAIL) {
831                 fprintf(stderr, "alloc_blockmap: ran out of space!\n");
832                 exit(1);
833         }
834
835         /*
836          * Dive layer 2
837          */
838         layer2_offset = layer1->phys_offset +
839                         HAMMER_BLOCKMAP_LAYER2_OFFSET(blockmap->next_offset);
840
841         layer2 = get_buffer_data(layer2_offset, &buffer2, 0);
842
843         if (layer2->zone == HAMMER_ZONE_UNAVAIL_INDEX) {
844                 fprintf(stderr, "alloc_blockmap: ran out of space!\n");
845                 exit(1);
846         }
847
848         /*
849          * If we are entering a new bigblock assign ownership to our
850          * zone.  If the bigblock is owned by another zone skip it.
851          */
852         if (layer2->zone == 0) {
853                 --layer1->blocks_free;
854                 layer2->zone = zone;
855                 assert(layer2->bytes_free == HAMMER_BIGBLOCK_SIZE);
856                 assert(layer2->append_off == 0);
857         }
858         if (layer2->zone != zone) {
859                 blockmap->next_offset = (blockmap->next_offset + HAMMER_BIGBLOCK_SIZE) &
860                                         ~HAMMER_BIGBLOCK_MASK64;
861                 goto again;
862         }
863
864         buffer1->cache.modified = 1;
865         buffer2->cache.modified = 1;
866         volume->cache.modified = 1;
867         assert(layer2->append_off ==
868                (blockmap->next_offset & HAMMER_BIGBLOCK_MASK));
869         layer2->bytes_free -= bytes;
870         *result_offp = blockmap->next_offset;
871         blockmap->next_offset += bytes;
872         layer2->append_off = (int)blockmap->next_offset &
873                               HAMMER_BIGBLOCK_MASK;
874
875         layer1->layer1_crc = crc32(layer1, HAMMER_LAYER1_CRCSIZE);
876         layer2->entry_crc = crc32(layer2, HAMMER_LAYER2_CRCSIZE);
877
878         zone2_offset = (*result_offp & ~HAMMER_OFF_ZONE_MASK) |
879                         HAMMER_ZONE_ENCODE(zone, 0);
880
881         ptr = get_buffer_data(zone2_offset, bufferp, 0);
882         (*bufferp)->cache.modified = 1;
883
884         if (buffer1)
885                 rel_buffer(buffer1);
886         if (buffer2)
887                 rel_buffer(buffer2);
888
889         rel_volume(volume);
890         return(ptr);
891 }
892
893 /*
894  * Flush various tracking structures to disk
895  */
896
897 /*
898  * Flush various tracking structures to disk
899  */
900 void
901 flush_all_volumes(void)
902 {
903         struct volume_info *vol;
904
905         TAILQ_FOREACH(vol, &VolList, entry)
906                 flush_volume(vol);
907 }
908
909 void
910 flush_volume(struct volume_info *volume)
911 {
912         struct buffer_info *buffer;
913         int i;
914
915         for (i = 0; i < HAMMER_BUFLISTS; ++i) {
916                 TAILQ_FOREACH(buffer, &volume->buffer_lists[i], entry)
917                         flush_buffer(buffer);
918         }
919         writehammerbuf(volume, volume->ondisk, 0);
920         volume->cache.modified = 0;
921 }
922
923 void
924 flush_buffer(struct buffer_info *buffer)
925 {
926         writehammerbuf(buffer->volume, buffer->ondisk, buffer->raw_offset);
927         buffer->cache.modified = 0;
928 }
929
930 #if 0
931 /*
932  * Generic buffer initialization
933  */
934 static void
935 init_fifo_head(hammer_fifo_head_t head, u_int16_t hdr_type)
936 {
937         head->hdr_signature = HAMMER_HEAD_SIGNATURE;
938         head->hdr_type = hdr_type;
939         head->hdr_size = 0;
940         head->hdr_crc = 0;
941         head->hdr_seq = 0;
942 }
943
944 #endif
945
946 #if 0
947 /*
948  * Core I/O operations
949  */
950 static void
951 readhammerbuf(struct volume_info *vol, void *data, int64_t offset)
952 {
953         ssize_t n;
954
955         n = pread(vol->fd, data, HAMMER_BUFSIZE, offset);
956         if (n != HAMMER_BUFSIZE)
957                 err(1, "Read volume %d (%s)", vol->vol_no, vol->name);
958 }
959
960 #endif
961
962 static void
963 writehammerbuf(struct volume_info *vol, const void *data, int64_t offset)
964 {
965         ssize_t n;
966
967         n = pwrite(vol->fd, data, HAMMER_BUFSIZE, offset);
968         if (n != HAMMER_BUFSIZE)
969                 err(1, "Write volume %d (%s)", vol->vol_no, vol->name);
970 }
971
972 void
973 panic(const char *ctl, ...)
974 {
975         va_list va;
976
977         va_start(va, ctl);
978         vfprintf(stderr, ctl, va);
979         va_end(va);
980         fprintf(stderr, "\n");
981         exit(1);
982 }
983