tdb2: allow multiple chain locks.
[ccan] / ccan / tdb2 / test / run-30-exhaust-before-expand.c
1 #include <ccan/tdb2/tdb.c>
2 #include <ccan/tdb2/open.c>
3 #include <ccan/tdb2/free.c>
4 #include <ccan/tdb2/lock.c>
5 #include <ccan/tdb2/io.c>
6 #include <ccan/tdb2/check.c>
7 #include <ccan/tdb2/hash.c>
8 #include <ccan/tdb2/transaction.c>
9 #include <ccan/tap/tap.h>
10 #include <err.h>
11 #include "logging.h"
12
13 static bool empty_freetable(struct tdb_context *tdb)
14 {
15         struct tdb_freetable ftab;
16         unsigned int i;
17
18         /* Now, free table should be completely exhausted in zone 0 */
19         if (tdb_read_convert(tdb, tdb->ftable_off, &ftab, sizeof(ftab)) != 0)
20                 abort();
21
22         for (i = 0; i < sizeof(ftab.buckets)/sizeof(ftab.buckets[0]); i++) {
23                 if (ftab.buckets[i])
24                         return false;
25         }
26         return true;
27 }
28
29
30 int main(int argc, char *argv[])
31 {
32         unsigned int i, j;
33         struct tdb_context *tdb;
34         int flags[] = { TDB_INTERNAL, TDB_DEFAULT, TDB_NOMMAP,
35                         TDB_INTERNAL|TDB_CONVERT, TDB_CONVERT,
36                         TDB_NOMMAP|TDB_CONVERT };
37
38         plan_tests(sizeof(flags) / sizeof(flags[0]) * 9 + 1);
39
40         for (i = 0; i < sizeof(flags) / sizeof(flags[0]); i++) {
41                 TDB_DATA k;
42                 uint64_t size;
43                 bool was_empty = false;
44
45                 k.dptr = (void *)&j;
46                 k.dsize = sizeof(j);
47
48                 tdb = tdb_open("run-30-exhaust-before-expand.tdb", flags[i],
49                                O_RDWR|O_CREAT|O_TRUNC, 0600, &tap_log_attr);
50                 ok1(tdb);
51                 if (!tdb)
52                         continue;
53
54                 ok1(empty_freetable(tdb));
55                 /* Need some hash lock for expand. */
56                 ok1(tdb_lock_hashes(tdb, 0, 1, F_WRLCK, TDB_LOCK_WAIT) == 0);
57                 /* Create some free space. */
58                 ok1(tdb_expand(tdb, 1) == 0);
59                 ok1(tdb_unlock_hashes(tdb, 0, 1, F_WRLCK) == 0);
60                 ok1(tdb_check(tdb, NULL, NULL) == 0);
61                 ok1(!empty_freetable(tdb));
62
63                 size = tdb->file->map_size;
64                 /* Insert minimal-length records until we expand. */
65                 for (j = 0; tdb->file->map_size == size; j++) {
66                         was_empty = empty_freetable(tdb);
67                         if (tdb_store(tdb, k, k, TDB_INSERT) != 0)
68                                 err(1, "Failed to store record %i", j);
69                 }
70
71                 /* Would have been empty before expansion, but no longer. */
72                 ok1(was_empty);
73                 ok1(!empty_freetable(tdb));
74                 tdb_close(tdb);
75         }
76
77         ok1(tap_log_messages == 0);
78         return exit_status();
79 }