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