sbin/hammer: Rename alloc_btree_element() to alloc_btree_node()
[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(struct volume_info *volume, hammer_off_t buf_offset)
69 {
70         int hi;
71         struct buffer_info *buf;
72
73         hi = buffer_hash(buf_offset);
74         TAILQ_FOREACH(buf, &volume->buffer_lists[hi], entry)
75                 if (buf->buf_offset == buf_offset)
76                         return(buf);
77         return(NULL);
78 }
79
80 static
81 struct volume_info *
82 __alloc_volume(const char *volname, int oflags)
83 {
84         struct volume_info *vol;
85         int i;
86
87         vol = malloc(sizeof(*vol));
88         if (vol == NULL)
89                 err(1, "alloc_volume");
90         bzero(vol, sizeof(*vol));
91
92         vol->vol_no = -1;
93         vol->rdonly = (oflags == O_RDONLY);
94         vol->name = strdup(volname);
95         vol->fd = open(vol->name, oflags);
96         if (vol->fd < 0)
97                 err(1, "alloc_volume: Failed to open %s", vol->name);
98         check_volume(vol);
99
100         vol->ondisk = malloc(HAMMER_BUFSIZE);
101         if (vol->ondisk == NULL)
102                 err(1, "alloc_volume");
103         bzero(vol->ondisk, HAMMER_BUFSIZE);
104
105         for (i = 0; i < HAMMER_BUFLISTS; ++i)
106                 TAILQ_INIT(&vol->buffer_lists[i]);
107
108         return(vol);
109 }
110
111 static void
112 __add_volume(struct volume_info *vol)
113 {
114         struct volume_info *scan;
115         struct stat st1, st2;
116
117         if (fstat(vol->fd, &st1) != 0)
118                 errx(1, "add_volume: %s: Failed to stat", vol->name);
119
120         TAILQ_FOREACH(scan, &VolList, entry) {
121                 if (scan->vol_no == vol->vol_no) {
122                         errx(1, "add_volume: %s: Duplicate volume number %d "
123                                 "against %s",
124                                 vol->name, vol->vol_no, scan->name);
125                 }
126                 if (fstat(scan->fd, &st2) != 0) {
127                         errx(1, "add_volume: %s: Failed to stat %s",
128                                 vol->name, scan->name);
129                 }
130                 if ((st1.st_ino == st2.st_ino) && (st1.st_dev == st2.st_dev)) {
131                         errx(1, "add_volume: %s: Specified more than once",
132                                 vol->name);
133                 }
134         }
135
136         TAILQ_INSERT_TAIL(&VolList, vol, entry);
137 }
138
139 /*
140  * Initialize a volume structure and ondisk vol_no field.
141  */
142 struct volume_info *
143 init_volume(int32_t vol_no, const char *filename, int oflags)
144 {
145         struct volume_info *vol;
146
147         vol = __alloc_volume(filename, oflags);
148         vol->vol_no = vol->ondisk->vol_no = vol_no;
149
150         __add_volume(vol);
151
152         return(vol);
153 }
154
155 /*
156  * Initialize a volume structure and read ondisk volume header.
157  */
158 struct volume_info*
159 load_volume(const char *filename, int oflags)
160 {
161         struct volume_info *vol;
162         hammer_volume_ondisk_t ondisk;
163         int n;
164
165         vol = __alloc_volume(filename, oflags);
166
167         n = readhammervol(vol);
168         if (n == -1) {
169                 err(1, "load_volume: %s: Read failed at offset 0", vol->name);
170         }
171         ondisk = vol->ondisk;
172         vol->vol_no = ondisk->vol_no;
173
174         if (ondisk->vol_rootvol != HAMMER_ROOT_VOLNO) {
175                 errx(1, "load_volume: Invalid root volume# %d",
176                         ondisk->vol_rootvol);
177         }
178
179         if (bcmp(&Hammer_FSType, &ondisk->vol_fstype, sizeof(Hammer_FSType))) {
180                 errx(1, "load_volume: %s: Header does not indicate "
181                         "that this is a hammer volume", vol->name);
182         }
183
184         if (valid_hammer_volumes++ == 0) {
185                 Hammer_FSId = ondisk->vol_fsid;
186         } else if (bcmp(&Hammer_FSId, &ondisk->vol_fsid, sizeof(Hammer_FSId))) {
187                 errx(1, "load_volume: %s: FSId does match other volumes!",
188                         vol->name);
189         }
190
191         __add_volume(vol);
192
193         return(vol);
194 }
195
196 /*
197  * Check basic volume characteristics.
198  */
199 static void
200 check_volume(struct volume_info *vol)
201 {
202         struct partinfo pinfo;
203         struct stat st;
204
205         /*
206          * Get basic information about the volume
207          */
208         if (ioctl(vol->fd, DIOCGPART, &pinfo) < 0) {
209                 /*
210                  * Allow the formatting of regular files as HAMMER volumes
211                  */
212                 if (fstat(vol->fd, &st) < 0)
213                         err(1, "Unable to stat %s", vol->name);
214                 vol->size = st.st_size;
215                 vol->type = "REGFILE";
216         } else {
217                 /*
218                  * When formatting a block device as a HAMMER volume the
219                  * sector size must be compatible.  HAMMER uses 16384 byte
220                  * filesystem buffers.
221                  */
222                 if (pinfo.reserved_blocks) {
223                         errx(1, "HAMMER cannot be placed in a partition "
224                                 "which overlaps the disklabel or MBR");
225                 }
226                 if (pinfo.media_blksize > HAMMER_BUFSIZE ||
227                     HAMMER_BUFSIZE % pinfo.media_blksize) {
228                         errx(1, "A media sector size of %d is not supported",
229                              pinfo.media_blksize);
230                 }
231
232                 vol->size = pinfo.media_size;
233                 vol->device_offset = pinfo.media_offset;
234                 vol->type = "DEVICE";
235         }
236 }
237
238 void
239 assert_volume_offset(struct volume_info *vol)
240 {
241         assert(hammer_is_zone_raw_buffer(vol->vol_free_off));
242         assert(hammer_is_zone_raw_buffer(vol->vol_free_end));
243 }
244
245 struct volume_info *
246 get_volume(int32_t vol_no)
247 {
248         struct volume_info *vol;
249
250         TAILQ_FOREACH(vol, &VolList, entry) {
251                 if (vol->vol_no == vol_no)
252                         break;
253         }
254
255         return(vol);
256 }
257
258 struct volume_info *
259 get_root_volume(void)
260 {
261         struct volume_info *root_vol;
262
263         root_vol = get_volume(HAMMER_ROOT_VOLNO);
264         assert(root_vol != NULL);
265
266         return(root_vol);
267 }
268
269 /*
270  * Acquire the specified buffer.  isnew is -1 only when called
271  * via get_buffer_readahead() to prevent another readahead.
272  */
273 static struct buffer_info *
274 get_buffer(hammer_off_t buf_offset, int isnew)
275 {
276         struct buffer_info *buf;
277         struct volume_info *volume;
278         int vol_no;
279         int zone;
280         int hi;
281         int dora = 0;
282         int error = 0;
283
284         zone = HAMMER_ZONE_DECODE(buf_offset);
285         if (zone > HAMMER_ZONE_RAW_BUFFER_INDEX)
286                 buf_offset = blockmap_lookup(buf_offset, NULL, NULL, &error);
287         if (error || buf_offset == HAMMER_OFF_BAD)
288                 return(NULL);
289         assert(hammer_is_zone_raw_buffer(buf_offset));
290
291         vol_no = HAMMER_VOL_DECODE(buf_offset);
292         volume = get_volume(vol_no);
293         assert(volume != NULL);
294
295         buf_offset &= ~HAMMER_BUFMASK64;
296         buf = find_buffer(volume, buf_offset);
297
298         if (buf == NULL) {
299                 buf = malloc(sizeof(*buf));
300                 bzero(buf, sizeof(*buf));
301                 buf->buf_offset = buf_offset;
302                 buf->raw_offset = hammer_xlate_to_phys(volume->ondisk,
303                                                         buf_offset);
304                 buf->volume = volume;
305                 buf->ondisk = malloc(HAMMER_BUFSIZE);
306                 if (isnew <= 0) {
307                         if (readhammerbuf(buf) == -1) {
308                                 err(1, "get_buffer: %s:%016jx "
309                                     "Read failed at offset %016jx",
310                                     volume->name,
311                                     (intmax_t)buf->buf_offset,
312                                     (intmax_t)buf->raw_offset);
313                         }
314                 }
315
316                 hi = buffer_hash(buf_offset);
317                 TAILQ_INSERT_TAIL(&volume->buffer_lists[hi], buf, entry);
318                 hammer_cache_add(&buf->cache);
319                 dora = (isnew == 0);
320         } else {
321                 assert(buf->ondisk != NULL);
322                 assert(isnew != -1);
323                 hammer_cache_used(&buf->cache);
324         }
325
326         ++buf->cache.refs;
327         hammer_cache_flush();
328
329         if (isnew > 0) {
330                 assert(buf->cache.modified == 0);
331                 bzero(buf->ondisk, HAMMER_BUFSIZE);
332                 buf->cache.modified = 1;
333         }
334         if (dora)
335                 get_buffer_readahead(buf);
336         return(buf);
337 }
338
339 static void
340 get_buffer_readahead(struct buffer_info *base)
341 {
342         struct buffer_info *buf;
343         struct volume_info *vol;
344         hammer_off_t buf_offset;
345         int64_t raw_offset;
346         int ri = UseReadBehind;
347         int re = UseReadAhead;
348
349         raw_offset = base->raw_offset + ri * HAMMER_BUFSIZE;
350         vol = base->volume;
351
352         while (ri < re) {
353                 if (raw_offset >= vol->ondisk->vol_buf_end)
354                         break;
355                 if (raw_offset < vol->ondisk->vol_buf_beg || ri == 0) {
356                         ++ri;
357                         raw_offset += HAMMER_BUFSIZE;
358                         continue;
359                 }
360                 buf_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no,
361                         raw_offset - vol->ondisk->vol_buf_beg);
362                 buf = find_buffer(vol, buf_offset);
363                 if (buf == NULL) {
364                         buf = get_buffer(buf_offset, -1);
365                         rel_buffer(buf);
366                 }
367                 ++ri;
368                 raw_offset += HAMMER_BUFSIZE;
369         }
370 }
371
372 void
373 rel_buffer(struct buffer_info *buffer)
374 {
375         struct volume_info *volume;
376         int hi;
377
378         if (buffer == NULL)
379                 return;
380         assert(buffer->cache.refs > 0);
381         if (--buffer->cache.refs == 0) {
382                 if (buffer->cache.delete) {
383                         hi = buffer_hash(buffer->buf_offset);
384                         volume = buffer->volume;
385                         if (buffer->cache.modified)
386                                 flush_buffer(buffer);
387                         TAILQ_REMOVE(&volume->buffer_lists[hi], buffer, entry);
388                         hammer_cache_del(&buffer->cache);
389                         free(buffer->ondisk);
390                         free(buffer);
391                 }
392         }
393 }
394
395 /*
396  * Retrieve a pointer to a buffer data given a buffer offset.  The underlying
397  * bufferp is freed if isnew or the offset is out of range of the cached data.
398  * If bufferp is freed a referenced buffer is loaded into it.
399  */
400 void *
401 get_buffer_data(hammer_off_t buf_offset, struct buffer_info **bufferp,
402                 int isnew)
403 {
404         if (*bufferp != NULL) {
405                 if (isnew > 0 ||
406                     (((*bufferp)->buf_offset ^ buf_offset) & ~HAMMER_BUFMASK64)) {
407                         rel_buffer(*bufferp);
408                         *bufferp = NULL;
409                 }
410         }
411
412         if (*bufferp == NULL) {
413                 *bufferp = get_buffer(buf_offset, isnew);
414                 if (*bufferp == NULL)
415                         return(NULL);
416         }
417
418         return(((char *)(*bufferp)->ondisk) +
419                 ((int32_t)buf_offset & HAMMER_BUFMASK));
420 }
421
422 /*
423  * Allocate HAMMER elements - B-Tree nodes
424  */
425 hammer_node_ondisk_t
426 alloc_btree_node(hammer_off_t *offp, struct buffer_info **data_bufferp)
427 {
428         hammer_node_ondisk_t node;
429
430         node = alloc_blockmap(HAMMER_ZONE_BTREE_INDEX, sizeof(*node),
431                               offp, data_bufferp);
432         bzero(node, sizeof(*node));
433         return(node);
434 }
435
436 /*
437  * Allocate HAMMER elements - meta data (inode, direntry, PFS, etc)
438  */
439 void *
440 alloc_meta_element(hammer_off_t *offp, int32_t data_len,
441                    struct buffer_info **data_bufferp)
442 {
443         void *data;
444
445         data = alloc_blockmap(HAMMER_ZONE_META_INDEX, data_len,
446                               offp, data_bufferp);
447         bzero(data, data_len);
448         return(data);
449 }
450
451 /*
452  * Allocate HAMMER elements - data storage
453  *
454  * The only data_len supported by HAMMER userspace for large data zone
455  * (zone 10) is HAMMER_BUFSIZE which is 16KB.  >16KB data does not fit
456  * in a buffer allocated by get_buffer().  Also alloc_blockmap() does
457  * not consider >16KB buffer size.
458  */
459 void *
460 alloc_data_element(hammer_off_t *offp, int32_t data_len,
461                    struct buffer_info **data_bufferp)
462 {
463         void *data;
464         int zone;
465
466         if (data_len == 0)
467                 return(NULL);
468
469         zone = hammer_data_zone_index(data_len);
470         assert(data_len <= HAMMER_BUFSIZE); /* just one buffer */
471         assert(zone == HAMMER_ZONE_LARGE_DATA_INDEX ||
472                zone == HAMMER_ZONE_SMALL_DATA_INDEX);
473
474         data = alloc_blockmap(zone, data_len, offp, data_bufferp);
475         bzero(data, data_len);
476         return(data);
477 }
478
479 /*
480  * Format a new blockmap.  This is mostly a degenerate case because
481  * all allocations are now actually done from the freemap.
482  */
483 void
484 format_blockmap(struct volume_info *root_vol, int zone, hammer_off_t offset)
485 {
486         hammer_blockmap_t blockmap;
487         hammer_off_t zone_base;
488
489         /* Only root volume needs formatting */
490         assert(root_vol->vol_no == HAMMER_ROOT_VOLNO);
491
492         assert(hammer_is_zone2_mapped_index(zone));
493
494         blockmap = &root_vol->ondisk->vol0_blockmap[zone];
495         zone_base = HAMMER_ZONE_ENCODE(zone, offset);
496
497         bzero(blockmap, sizeof(*blockmap));
498         blockmap->phys_offset = 0;
499         blockmap->first_offset = zone_base;
500         blockmap->next_offset = zone_base;
501         blockmap->alloc_offset = HAMMER_ENCODE(zone, 255, -1);
502         hammer_crc_set_blockmap(blockmap);
503 }
504
505 /*
506  * Format a new freemap.  Set all layer1 entries to UNAVAIL.  The initialize
507  * code will load each volume's freemap.
508  */
509 void
510 format_freemap(struct volume_info *root_vol)
511 {
512         struct buffer_info *buffer = NULL;
513         hammer_off_t layer1_offset;
514         hammer_blockmap_t blockmap;
515         hammer_blockmap_layer1_t layer1;
516         int i, isnew;
517
518         /* Only root volume needs formatting */
519         assert(root_vol->vol_no == HAMMER_ROOT_VOLNO);
520
521         layer1_offset = alloc_bigblock(root_vol, HAMMER_ZONE_FREEMAP_INDEX);
522         for (i = 0; i < HAMMER_BIGBLOCK_SIZE; i += sizeof(*layer1)) {
523                 isnew = ((i % HAMMER_BUFSIZE) == 0);
524                 layer1 = get_buffer_data(layer1_offset + i, &buffer, isnew);
525                 bzero(layer1, sizeof(*layer1));
526                 layer1->phys_offset = HAMMER_BLOCKMAP_UNAVAIL;
527                 layer1->blocks_free = 0;
528                 hammer_crc_set_layer1(layer1);
529         }
530         assert(i == HAMMER_BIGBLOCK_SIZE);
531         rel_buffer(buffer);
532
533         blockmap = &root_vol->ondisk->vol0_blockmap[HAMMER_ZONE_FREEMAP_INDEX];
534         bzero(blockmap, sizeof(*blockmap));
535         blockmap->phys_offset = layer1_offset;
536         blockmap->first_offset = 0;
537         blockmap->next_offset = HAMMER_ENCODE_RAW_BUFFER(0, 0);
538         blockmap->alloc_offset = HAMMER_ENCODE_RAW_BUFFER(255, -1);
539         hammer_crc_set_blockmap(blockmap);
540 }
541
542 /*
543  * Load the volume's remaining free space into the freemap.
544  *
545  * Returns the number of big-blocks available.
546  */
547 int64_t
548 initialize_freemap(struct volume_info *vol)
549 {
550         struct volume_info *root_vol;
551         struct buffer_info *buffer1 = NULL;
552         struct buffer_info *buffer2 = NULL;
553         hammer_blockmap_layer1_t layer1;
554         hammer_blockmap_layer2_t layer2;
555         hammer_off_t layer1_offset;
556         hammer_off_t layer2_offset;
557         hammer_off_t phys_offset;
558         hammer_off_t block_offset;
559         hammer_off_t aligned_vol_free_end;
560         hammer_blockmap_t freemap;
561         int64_t count = 0;
562         int64_t layer1_count = 0;
563
564         root_vol = get_root_volume();
565
566         assert_volume_offset(vol);
567         aligned_vol_free_end = (vol->vol_free_end + HAMMER_BLOCKMAP_LAYER2_MASK)
568                                 & ~HAMMER_BLOCKMAP_LAYER2_MASK;
569
570         printf("initialize freemap volume %d\n", vol->vol_no);
571
572         /*
573          * Initialize the freemap.  First preallocate the big-blocks required
574          * to implement layer2.   This preallocation is a bootstrap allocation
575          * using blocks from the target volume.
576          */
577         freemap = &root_vol->ondisk->vol0_blockmap[HAMMER_ZONE_FREEMAP_INDEX];
578
579         for (phys_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no, 0);
580              phys_offset < aligned_vol_free_end;
581              phys_offset += HAMMER_BLOCKMAP_LAYER2) {
582                 layer1_offset = freemap->phys_offset +
583                                 HAMMER_BLOCKMAP_LAYER1_OFFSET(phys_offset);
584                 layer1 = get_buffer_data(layer1_offset, &buffer1, 0);
585                 if (layer1->phys_offset == HAMMER_BLOCKMAP_UNAVAIL) {
586                         layer1->phys_offset = alloc_bigblock(vol,
587                                                 HAMMER_ZONE_FREEMAP_INDEX);
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                                  * Fixups XXX - 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 = (vol->vol_free_end + HAMMER_BLOCKMAP_LAYER2_MASK)
663                                 & ~HAMMER_BLOCKMAP_LAYER2_MASK;
664
665         if (vol->vol_no == HAMMER_ROOT_VOLNO)
666                 vol_free_off += HAMMER_BIGBLOCK_SIZE;
667
668         for (phys_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no, 0);
669              phys_offset < aligned_vol_free_end;
670              phys_offset += HAMMER_BLOCKMAP_LAYER2) {
671                 vol_free_off += HAMMER_BIGBLOCK_SIZE;
672         }
673
674         for (phys_offset = HAMMER_ENCODE_RAW_BUFFER(vol->vol_no, 0);
675              phys_offset < aligned_vol_free_end;
676              phys_offset += HAMMER_BIGBLOCK_SIZE) {
677                 if (phys_offset < vol_free_off) {
678                         ;
679                 } else if (phys_offset < vol->vol_free_end) {
680                         ++count;
681                 }
682         }
683
684         return(count);
685 }
686
687 /*
688  * Format the undomap for the root volume.
689  */
690 void
691 format_undomap(struct volume_info *root_vol, int64_t *undo_buffer_size)
692 {
693         const int undo_zone = HAMMER_ZONE_UNDO_INDEX;
694         hammer_off_t undo_limit;
695         hammer_blockmap_t blockmap;
696         hammer_volume_ondisk_t ondisk;
697         struct buffer_info *buffer = NULL;
698         hammer_off_t scan;
699         int n;
700         int limit_index;
701         uint32_t seqno;
702
703         /* Only root volume needs formatting */
704         assert(root_vol->vol_no == HAMMER_ROOT_VOLNO);
705         ondisk = root_vol->ondisk;
706
707         /*
708          * Size the undo buffer in multiples of HAMMER_BIGBLOCK_SIZE,
709          * up to HAMMER_UNDO_LAYER2 big-blocks.  Size to approximately
710          * 0.1% of the disk.
711          *
712          * The minimum UNDO fifo size is 500MB, or approximately 1% of
713          * the recommended 50G disk.
714          *
715          * Changing this minimum is rather dangerous as complex filesystem
716          * operations can cause the UNDO FIFO to fill up otherwise.
717          */
718         undo_limit = *undo_buffer_size;
719         if (undo_limit == 0) {
720                 undo_limit = HAMMER_VOL_BUF_SIZE(ondisk) / 1000;
721                 if (undo_limit < 500*1024*1024)
722                         undo_limit = 500*1024*1024;
723         }
724         undo_limit = (undo_limit + HAMMER_BIGBLOCK_MASK64) &
725                      ~HAMMER_BIGBLOCK_MASK64;
726         if (undo_limit < HAMMER_BIGBLOCK_SIZE)
727                 undo_limit = HAMMER_BIGBLOCK_SIZE;
728         if (undo_limit > HAMMER_BIGBLOCK_SIZE * HAMMER_UNDO_LAYER2)
729                 undo_limit = HAMMER_BIGBLOCK_SIZE * HAMMER_UNDO_LAYER2;
730         *undo_buffer_size = undo_limit;
731
732         blockmap = &ondisk->vol0_blockmap[undo_zone];
733         bzero(blockmap, sizeof(*blockmap));
734         blockmap->phys_offset = HAMMER_BLOCKMAP_UNAVAIL;
735         blockmap->first_offset = HAMMER_ZONE_ENCODE(undo_zone, 0);
736         blockmap->next_offset = blockmap->first_offset;
737         blockmap->alloc_offset = HAMMER_ZONE_ENCODE(undo_zone, undo_limit);
738         hammer_crc_set_blockmap(blockmap);
739
740         limit_index = undo_limit / HAMMER_BIGBLOCK_SIZE;
741         assert(limit_index <= HAMMER_UNDO_LAYER2);
742
743         for (n = 0; n < limit_index; ++n) {
744                 ondisk->vol0_undo_array[n] = alloc_bigblock(root_vol,
745                                                         HAMMER_ZONE_UNDO_INDEX);
746         }
747         while (n < HAMMER_UNDO_LAYER2) {
748                 ondisk->vol0_undo_array[n++] = HAMMER_BLOCKMAP_UNAVAIL;
749         }
750
751         /*
752          * Pre-initialize the UNDO blocks (HAMMER version 4+)
753          */
754         printf("initializing the undo map (%jd MB)\n",
755                 (intmax_t)(blockmap->alloc_offset & HAMMER_OFF_LONG_MASK) /
756                 (1024 * 1024));
757
758         scan = blockmap->first_offset;
759         seqno = 0;
760
761         while (scan < blockmap->alloc_offset) {
762                 hammer_fifo_head_t head;
763                 hammer_fifo_tail_t tail;
764                 int isnew;
765                 int bytes = HAMMER_UNDO_ALIGN;
766
767                 isnew = ((scan & HAMMER_BUFMASK64) == 0);
768                 head = get_buffer_data(scan, &buffer, isnew);
769                 buffer->cache.modified = 1;
770                 tail = (void *)((char *)head + bytes - sizeof(*tail));
771
772                 bzero(head, bytes);
773                 head->hdr_signature = HAMMER_HEAD_SIGNATURE;
774                 head->hdr_type = HAMMER_HEAD_TYPE_DUMMY;
775                 head->hdr_size = bytes;
776                 head->hdr_seq = seqno++;
777
778                 tail->tail_signature = HAMMER_TAIL_SIGNATURE;
779                 tail->tail_type = HAMMER_HEAD_TYPE_DUMMY;
780                 tail->tail_size = bytes;
781
782                 hammer_crc_set_fifo_head(head, bytes);
783
784                 scan += bytes;
785         }
786         rel_buffer(buffer);
787 }
788
789 const char *zone_labels[] = {
790         "",             /* 0 */
791         "raw_volume",   /* 1 */
792         "raw_buffer",   /* 2 */
793         "undo",         /* 3 */
794         "freemap",      /* 4 */
795         "",             /* 5 */
796         "",             /* 6 */
797         "",             /* 7 */
798         "btree",        /* 8 */
799         "meta",         /* 9 */
800         "large_data",   /* 10 */
801         "small_data",   /* 11 */
802         "",             /* 12 */
803         "",             /* 13 */
804         "",             /* 14 */
805         "unavail",      /* 15 */
806 };
807
808 void
809 print_blockmap(const struct volume_info *root_vol)
810 {
811         hammer_blockmap_t blockmap;
812         hammer_volume_ondisk_t ondisk;
813         int64_t size, used;
814         int i;
815 #define INDENT ""
816
817         ondisk = root_vol->ondisk;
818         printf(INDENT"vol_label\t%s\n", ondisk->vol_label);
819         printf(INDENT"vol_count\t%d\n", ondisk->vol_count);
820         printf(INDENT"vol_bot_beg\t%s\n", sizetostr(ondisk->vol_bot_beg));
821         printf(INDENT"vol_mem_beg\t%s\n", sizetostr(ondisk->vol_mem_beg));
822         printf(INDENT"vol_buf_beg\t%s\n", sizetostr(ondisk->vol_buf_beg));
823         printf(INDENT"vol_buf_end\t%s\n", sizetostr(ondisk->vol_buf_end));
824         printf(INDENT"vol0_next_tid\t%016jx\n",
825                (uintmax_t)ondisk->vol0_next_tid);
826
827         blockmap = &ondisk->vol0_blockmap[HAMMER_ZONE_UNDO_INDEX];
828         size = blockmap->alloc_offset & HAMMER_OFF_LONG_MASK;
829         if (blockmap->first_offset <= blockmap->next_offset)
830                 used = blockmap->next_offset - blockmap->first_offset;
831         else
832                 used = blockmap->alloc_offset - blockmap->first_offset +
833                         (blockmap->next_offset & HAMMER_OFF_LONG_MASK);
834         printf(INDENT"undo_size\t%s\n", sizetostr(size));
835         printf(INDENT"undo_used\t%s\n", sizetostr(used));
836
837         printf(INDENT"zone #             "
838                "phys             first            next             alloc\n");
839         for (i = 0; i < HAMMER_MAX_ZONES; i++) {
840                 blockmap = &ondisk->vol0_blockmap[i];
841                 printf(INDENT"zone %-2d %-10s %016jx %016jx %016jx %016jx\n",
842                         i, zone_labels[i],
843                         (uintmax_t)blockmap->phys_offset,
844                         (uintmax_t)blockmap->first_offset,
845                         (uintmax_t)blockmap->next_offset,
846                         (uintmax_t)blockmap->alloc_offset);
847         }
848 }
849
850 /*
851  * Flush various tracking structures to disk
852  */
853 void
854 flush_all_volumes(void)
855 {
856         struct volume_info *vol;
857
858         TAILQ_FOREACH(vol, &VolList, entry)
859                 flush_volume(vol);
860 }
861
862 void
863 flush_volume(struct volume_info *volume)
864 {
865         struct buffer_info *buffer;
866         int i;
867
868         for (i = 0; i < HAMMER_BUFLISTS; ++i) {
869                 TAILQ_FOREACH(buffer, &volume->buffer_lists[i], entry)
870                         flush_buffer(buffer);
871         }
872         if (writehammervol(volume) == -1)
873                 err(1, "Write volume %d (%s)", volume->vol_no, volume->name);
874 }
875
876 void
877 flush_buffer(struct buffer_info *buffer)
878 {
879         struct volume_info *vol;
880
881         vol = buffer->volume;
882         if (writehammerbuf(buffer) == -1)
883                 err(1, "Write volume %d (%s)", vol->vol_no, vol->name);
884         buffer->cache.modified = 0;
885 }
886
887 /*
888  * Core I/O operations
889  */
890 static int
891 __read(struct volume_info *vol, void *data, int64_t offset, int size)
892 {
893         ssize_t n;
894
895         n = pread(vol->fd, data, size, offset);
896         if (n != size)
897                 return(-1);
898         return(0);
899 }
900
901 static __inline int
902 readhammervol(struct volume_info *vol)
903 {
904         return(__read(vol, vol->ondisk, 0, HAMMER_BUFSIZE));
905 }
906
907 static __inline int
908 readhammerbuf(struct buffer_info *buf)
909 {
910         return(__read(buf->volume, buf->ondisk, buf->raw_offset, HAMMER_BUFSIZE));
911 }
912
913 static int
914 __write(struct volume_info *vol, const void *data, int64_t offset, int size)
915 {
916         ssize_t n;
917
918         if (vol->rdonly)
919                 return(0);
920
921         n = pwrite(vol->fd, data, size, offset);
922         if (n != size)
923                 return(-1);
924         return(0);
925 }
926
927 static __inline int
928 writehammervol(struct volume_info *vol)
929 {
930         return(__write(vol, vol->ondisk, 0, HAMMER_BUFSIZE));
931 }
932
933 static __inline int
934 writehammerbuf(struct buffer_info *buf)
935 {
936         return(__write(buf->volume, buf->ondisk, buf->raw_offset, HAMMER_BUFSIZE));
937 }
938
939 int64_t init_boot_area_size(int64_t value, off_t avg_vol_size)
940 {
941         if (value == 0) {
942                 value = HAMMER_BOOT_NOMBYTES;
943                 while (value > avg_vol_size / HAMMER_MAX_VOLUMES)
944                         value >>= 1;
945                 if (value < HAMMER_BOOT_MINBYTES)
946                         value = 0;
947         } else if (value < HAMMER_BOOT_MINBYTES) {
948                 value = HAMMER_BOOT_MINBYTES;
949         }
950
951         return(value);
952 }
953
954 int64_t init_mem_area_size(int64_t value, off_t avg_vol_size)
955 {
956         if (value == 0) {
957                 value = HAMMER_MEM_NOMBYTES;
958                 while (value > avg_vol_size / HAMMER_MAX_VOLUMES)
959                         value >>= 1;
960                 if (value < HAMMER_MEM_MINBYTES)
961                         value = 0;
962         } else if (value < HAMMER_MEM_MINBYTES) {
963                 value = HAMMER_MEM_MINBYTES;
964         }
965
966         return(value);
967 }