1 #include <ccan/tdb/tdb.h>
2 #include <ccan/grab_file/grab_file.h>
3 #include <ccan/hash/hash.h>
4 #include <ccan/talloc/talloc.h>
5 #include <ccan/str_talloc/str_talloc.h>
6 #include <ccan/str/str.h>
7 #include <ccan/list/list.h>
12 #include <sys/types.h>
19 #define STRINGIFY2(x) #x
20 #define STRINGIFY(x) STRINGIFY2(x)
22 /* Avoid mod by zero */
23 static unsigned int total_keys = 1;
25 /* #define DEBUG_DEPS 1 */
27 /* Traversals block transactions in the current implementation. */
28 #define TRAVERSALS_TAKE_TRANSACTION_LOCK 1
33 static struct pipe *pipes;
35 static void __attribute__((noreturn)) fail(const char *filename,
42 fprintf(stderr, "%s:%u: FAIL: ", filename, line);
43 vfprintf(stderr, fmt, ap);
44 fprintf(stderr, "\n");
50 #define try(expr, expect) \
53 if (ret != (expect)) \
54 fail(filename[file], i+1, \
55 STRINGIFY(expr) "= %i", ret); \
58 /* Try or imitate results. */
59 #define unreliable(expr, expect, force, undo) \
62 if (ret != expect) { \
63 fprintf(stderr, "%s:%u: %s gave %i not %i", \
64 filename[file], i+1, STRINGIFY(expr), \
73 static bool key_eq(TDB_DATA a, TDB_DATA b)
75 if (a.dsize != b.dsize)
77 return memcmp(a.dptr, b.dptr, a.dsize) == 0;
80 /* This is based on the hash algorithm from gdbm */
81 static unsigned int hash_key(TDB_DATA *key)
83 uint32_t value; /* Used to compute the hash value. */
84 uint32_t i; /* Used to cycle through random values. */
86 /* Set the initial value from the key size. */
87 for (value = 0x238F13AF ^ key->dsize, i=0; i < key->dsize; i++)
88 value = (value + (key->dptr[i] << (i*5 % 24)));
90 return (1103515243 * value + 12345);
96 OP_TDB_LOCKALL_UNMARK,
97 OP_TDB_LOCKALL_NONBLOCK,
100 OP_TDB_LOCKALL_READ_NONBLOCK,
101 OP_TDB_UNLOCKALL_READ,
103 OP_TDB_CHAINLOCK_NONBLOCK,
104 OP_TDB_CHAINLOCK_MARK,
105 OP_TDB_CHAINLOCK_UNMARK,
107 OP_TDB_CHAINLOCK_READ,
108 OP_TDB_CHAINUNLOCK_READ,
115 OP_TDB_TRANSACTION_START,
116 OP_TDB_TRANSACTION_CANCEL,
117 OP_TDB_TRANSACTION_COMMIT,
118 OP_TDB_TRAVERSE_READ_START,
119 OP_TDB_TRAVERSE_START,
135 /* Who is waiting for us? */
136 struct list_head post;
137 /* What are we waiting for? */
138 struct list_head pre;
140 /* If I'm part of a group (traverse/transaction) where is
141 * start? (Otherwise, 0) */
142 unsigned int group_start;
145 int flag; /* open and store */
146 struct { /* append */
150 unsigned int group_len; /* transaction/traverse start */
154 static unsigned char hex_char(const char *filename, unsigned int line, char c)
157 if (c >= 'A' && c <= 'F')
159 if (c >= '0' && c <= '9')
161 fail(filename, line, "invalid hex character '%c'", c);
164 /* TDB data is <size>:<%02x>* */
165 static TDB_DATA make_tdb_data(const void *ctx,
166 const char *filename, unsigned int line,
173 if (streq(word, "NULL"))
176 data.dsize = atoi(word);
177 data.dptr = talloc_array(ctx, unsigned char, data.dsize);
178 p = strchr(word, ':');
180 fail(filename, line, "invalid tdb data '%s'", word);
182 for (i = 0; i < data.dsize; i++)
183 data.dptr[i] = hex_char(filename, line, p[i*2])*16
184 + hex_char(filename, line, p[i*2+1]);
189 static void add_op(const char *filename, struct op **op, unsigned int i,
190 unsigned int serial, enum op_type type)
193 *op = talloc_realloc(NULL, *op, struct op, i+1);
196 new->serial = serial;
198 new->group_start = 0;
201 static void op_add_nothing(const char *filename,
202 struct op op[], unsigned int op_num, char *words[])
205 fail(filename, op_num+1, "Expected no arguments");
206 op[op_num].key = tdb_null;
209 static void op_add_key(const char *filename,
210 struct op op[], unsigned int op_num, char *words[])
212 if (words[2] == NULL || words[3])
213 fail(filename, op_num+1, "Expected just a key");
215 op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
219 static void op_add_key_ret(const char *filename,
220 struct op op[], unsigned int op_num, char *words[])
222 if (!words[2] || !words[3] || !words[4] || words[5]
223 || !streq(words[3], "="))
224 fail(filename, op_num+1, "Expected <key> = <ret>");
225 op[op_num].ret = atoi(words[4]);
226 op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
227 /* May only be a unique key if it fails */
228 if (op[op_num].ret != 0)
232 static void op_add_key_data(const char *filename,
233 struct op op[], unsigned int op_num, char *words[])
235 if (!words[2] || !words[3] || !words[4] || words[5]
236 || !streq(words[3], "="))
237 fail(filename, op_num+1, "Expected <key> = <data>");
238 op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
239 op[op_num].data = make_tdb_data(op, filename, op_num+1, words[4]);
240 /* May only be a unique key if it fails */
241 if (!op[op_num].data.dptr)
245 /* We don't record the keys or data for a traverse, as we don't use them. */
246 static void op_add_traverse(const char *filename,
247 struct op op[], unsigned int op_num, char *words[])
249 if (!words[2] || !words[3] || !words[4] || words[5]
250 || !streq(words[3], "="))
251 fail(filename, op_num+1, "Expected <key> = <data>");
252 op[op_num].key = tdb_null;
255 /* <serial> tdb_store <rec> <rec> <flag> = <ret> */
256 static void op_add_store(const char *filename,
257 struct op op[], unsigned int op_num, char *words[])
259 if (!words[2] || !words[3] || !words[4] || !words[5] || !words[6]
260 || words[7] || !streq(words[5], "="))
261 fail(filename, op_num+1, "Expect <key> <data> <flag> = <ret>");
263 op[op_num].flag = strtoul(words[4], NULL, 0);
264 op[op_num].ret = atoi(words[6]);
265 op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
266 op[op_num].data = make_tdb_data(op, filename, op_num+1, words[3]);
270 /* <serial> tdb_append <rec> <rec> = <rec> */
271 static void op_add_append(const char *filename,
272 struct op op[], unsigned int op_num, char *words[])
274 if (!words[2] || !words[3] || !words[4] || !words[5] || words[6]
275 || !streq(words[4], "="))
276 fail(filename, op_num+1, "Expect <key> <data> = <rec>");
278 op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
279 op[op_num].data = make_tdb_data(op, filename, op_num+1, words[3]);
281 op[op_num].append.post
282 = make_tdb_data(op, filename, op_num+1, words[5]);
284 /* By subtraction, figure out what previous data was. */
285 op[op_num].append.pre.dptr = op[op_num].append.post.dptr;
286 op[op_num].append.pre.dsize
287 = op[op_num].append.post.dsize - op[op_num].data.dsize;
291 /* <serial> tdb_get_seqnum = <ret> */
292 static void op_add_seqnum(const char *filename,
293 struct op op[], unsigned int op_num, char *words[])
295 if (!words[2] || !words[3] || words[4] || !streq(words[2], "="))
296 fail(filename, op_num+1, "Expect = <ret>");
298 op[op_num].key = tdb_null;
299 op[op_num].ret = atoi(words[3]);
302 static void op_add_traverse_start(const char *filename,
304 unsigned int op_num, char *words[])
307 fail(filename, op_num+1, "Expect no arguments");
309 op[op_num].key = tdb_null;
310 op[op_num].group_len = 0;
313 static void op_add_transaction(const char *filename, struct op op[],
314 unsigned int op_num, char *words[])
317 fail(filename, op_num+1, "Expect no arguments");
319 op[op_num].key = tdb_null;
320 op[op_num].group_len = 0;
323 static int op_transaction_start(struct op op[], unsigned int op_num)
327 for (i = op_num-1; i > 0; i--) {
328 if (op[i].op == OP_TDB_TRANSACTION_START && !op[i].group_len)
334 static void op_analyze_transaction(const char *filename,
335 struct op op[], unsigned int op_num,
338 unsigned int start, i;
340 op[op_num].key = tdb_null;
343 fail(filename, op_num+1, "Expect no arguments");
345 start = op_transaction_start(op, op_num);
347 fail(filename, op_num+1, "no transaction start found");
349 op[start].group_len = op_num - start;
351 /* This rolls in nested transactions. I think that's right. */
352 for (i = start; i <= op_num; i++)
353 op[i].group_start = start;
356 struct traverse_hash {
361 static void op_analyze_traverse(const char *filename,
362 struct op op[], unsigned int op_num,
367 op[op_num].key = tdb_null;
369 /* = %u means traverse function terminated. */
371 if (!streq(words[2], "=") || !words[3] || words[4])
372 fail(filename, op_num+1, "expect = <num>");
373 op[op_num].ret = atoi(words[3]);
377 for (i = op_num-1; i >= 0; i--) {
378 if (op[i].op != OP_TDB_TRAVERSE_READ_START
379 && op[i].op != OP_TDB_TRAVERSE_START)
387 fail(filename, op_num+1, "no traversal start found");
390 op[start].group_len = op_num - start;
392 for (i = start; i <= op_num; i++)
393 op[i].group_start = start;
396 /* Keep -Wmissing-declarations happy: */
397 const struct op_table *
398 find_keyword (register const char *str, register unsigned int len);
400 #include "keywords.c"
403 /* We can have more than one */
404 struct list_node pre_list;
405 struct list_node post_list;
406 unsigned int needs_file;
407 unsigned int needs_opnum;
408 unsigned int satisfies_file;
409 unsigned int satisfies_opnum;
412 static void check_deps(const char *filename, struct op op[], unsigned int num)
417 for (i = 1; i < num; i++)
418 if (!list_empty(&op[i].pre))
419 fail(filename, i+1, "Still has dependencies");
423 static void dump_pre(char *filename[], struct op *op[],
424 unsigned int file, unsigned int i)
428 printf("%s:%u (%u) still waiting for:\n", filename[file], i+1,
430 list_for_each(&op[file][i].pre, dep, pre_list)
431 printf(" %s:%u (%u)\n",
432 filename[dep->satisfies_file], dep->satisfies_opnum+1,
433 op[dep->satisfies_file][dep->satisfies_opnum].serial);
434 check_deps(filename[file], op[file], i);
437 /* We simply read/write pointers, since we all are children. */
438 static bool do_pre(struct tdb_context *tdb,
439 char *filename[], struct op *op[],
440 unsigned int file, int pre_fd, unsigned int i,
443 while (!list_empty(&op[file][i].pre)) {
447 printf("%s:%u:waiting for pre\n", filename[file], i+1);
454 while (read(pre_fd, &dep, sizeof(dep)) != sizeof(dep)) {
455 if (errno == EINTR) {
457 warnx("%s:%u:avoiding deadlock",
458 filename[file], i+1);
461 dump_pre(filename, op, file, i);
464 errx(1, "Reading from pipe");
469 printf("%s:%u:got pre %u from %s:%u\n", filename[file], i+1,
470 dep->needs_opnum+1, filename[dep->satisfies_file],
471 dep->satisfies_opnum+1);
474 /* This could be any op, not just this one. */
480 static void do_post(char *filename[], struct op *op[],
481 unsigned int file, unsigned int i)
485 list_for_each(&op[file][i].post, dep, post_list) {
487 printf("%s:%u:sending to file %s:%u\n", filename[file], i+1,
488 filename[dep->needs_file], dep->needs_opnum+1);
490 if (write(pipes[dep->needs_file].fd[1], &dep, sizeof(dep))
492 err(1, "%s:%u failed to tell file %s",
493 filename[file], i+1, filename[dep->needs_file]);
497 static int get_len(TDB_DATA key, TDB_DATA data, void *private_data)
502 static unsigned run_ops(struct tdb_context *tdb,
507 unsigned int start, unsigned int stop,
510 struct traverse_info {
519 /* More complex. Just do whatever's they did at the n'th entry. */
520 static int nontrivial_traverse(struct tdb_context *tdb,
521 TDB_DATA key, TDB_DATA data,
524 struct traverse_info *tinfo = _tinfo;
525 unsigned int trav_len = tinfo->op[tinfo->file][tinfo->start].group_len;
526 bool avoid_deadlock = false;
528 if (tinfo->i == tinfo->start + trav_len) {
529 /* This can happen if traverse expects to be empty. */
532 fail(tinfo->filename[tinfo->file], tinfo->start + 1,
533 "traverse did not terminate");
536 if (tinfo->op[tinfo->file][tinfo->i].op != OP_TDB_TRAVERSE)
537 fail(tinfo->filename[tinfo->file], tinfo->start + 1,
538 "%s:%u:traverse terminated early");
540 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
541 avoid_deadlock = true;
544 /* Run any normal ops. */
545 tinfo->i = run_ops(tdb, tinfo->pre_fd, tinfo->filename, tinfo->op,
546 tinfo->file, tinfo->i+1, tinfo->start + trav_len,
549 /* We backed off, or we hit OP_TDB_TRAVERSE_END. */
550 if (tinfo->op[tinfo->file][tinfo->i].op != OP_TDB_TRAVERSE)
556 static unsigned op_traverse(struct tdb_context *tdb,
560 int (*traversefn)(struct tdb_context *,
561 tdb_traverse_func, void *),
565 struct traverse_info tinfo = { op, filename, file, pre_fd,
568 traversefn(tdb, nontrivial_traverse, &tinfo);
570 /* Traversing in wrong order can have strange effects: eg. if
571 * original traverse went A (delete A), B, we might do B
572 * (delete A). So if we have ops left over, we do it now. */
573 while (tinfo.i != start + op[file][start].group_len) {
574 if (op[file][tinfo.i].op == OP_TDB_TRAVERSE)
577 tinfo.i = run_ops(tdb, pre_fd, filename, op, file,
579 start + op[file][start].group_len,
586 static void break_out(int sig)
590 static __attribute__((noinline))
591 unsigned run_ops(struct tdb_context *tdb,
596 unsigned int start, unsigned int stop,
602 sa.sa_handler = break_out;
605 sigaction(SIGALRM, &sa, NULL);
606 for (i = start; i < stop; i++) {
607 if (!do_pre(tdb, filename, op, file, pre_fd, i, backoff))
610 switch (op[file][i].op) {
612 try(tdb_lockall(tdb), op[file][i].ret);
614 case OP_TDB_LOCKALL_MARK:
615 try(tdb_lockall_mark(tdb), op[file][i].ret);
617 case OP_TDB_LOCKALL_UNMARK:
618 try(tdb_lockall_unmark(tdb), op[file][i].ret);
620 case OP_TDB_LOCKALL_NONBLOCK:
621 unreliable(tdb_lockall_nonblock(tdb), op[file][i].ret,
622 tdb_lockall(tdb), tdb_unlockall(tdb));
624 case OP_TDB_UNLOCKALL:
625 try(tdb_unlockall(tdb), op[file][i].ret);
627 case OP_TDB_LOCKALL_READ:
628 try(tdb_lockall_read(tdb), op[file][i].ret);
630 case OP_TDB_LOCKALL_READ_NONBLOCK:
631 unreliable(tdb_lockall_read_nonblock(tdb),
633 tdb_lockall_read(tdb),
634 tdb_unlockall_read(tdb));
636 case OP_TDB_UNLOCKALL_READ:
637 try(tdb_unlockall_read(tdb), op[file][i].ret);
639 case OP_TDB_CHAINLOCK:
640 try(tdb_chainlock(tdb, op[file][i].key),
643 case OP_TDB_CHAINLOCK_NONBLOCK:
644 unreliable(tdb_chainlock_nonblock(tdb, op[file][i].key),
646 tdb_chainlock(tdb, op[file][i].key),
647 tdb_chainunlock(tdb, op[file][i].key));
649 case OP_TDB_CHAINLOCK_MARK:
650 try(tdb_chainlock_mark(tdb, op[file][i].key),
653 case OP_TDB_CHAINLOCK_UNMARK:
654 try(tdb_chainlock_unmark(tdb, op[file][i].key),
657 case OP_TDB_CHAINUNLOCK:
658 try(tdb_chainunlock(tdb, op[file][i].key),
661 case OP_TDB_CHAINLOCK_READ:
662 try(tdb_chainlock_read(tdb, op[file][i].key),
665 case OP_TDB_CHAINUNLOCK_READ:
666 try(tdb_chainunlock_read(tdb, op[file][i].key),
669 case OP_TDB_PARSE_RECORD:
670 try(tdb_parse_record(tdb, op[file][i].key, get_len,
675 try(tdb_exists(tdb, op[file][i].key), op[file][i].ret);
678 try(tdb_store(tdb, op[file][i].key, op[file][i].data,
683 try(tdb_append(tdb, op[file][i].key, op[file][i].data),
686 case OP_TDB_GET_SEQNUM:
687 try(tdb_get_seqnum(tdb), op[file][i].ret);
689 case OP_TDB_WIPE_ALL:
690 try(tdb_wipe_all(tdb), op[file][i].ret);
692 case OP_TDB_TRANSACTION_START:
693 try(tdb_transaction_start(tdb), op[file][i].ret);
695 case OP_TDB_TRANSACTION_CANCEL:
696 try(tdb_transaction_cancel(tdb), op[file][i].ret);
698 case OP_TDB_TRANSACTION_COMMIT:
699 try(tdb_transaction_commit(tdb), op[file][i].ret);
701 case OP_TDB_TRAVERSE_READ_START:
702 i = op_traverse(tdb, pre_fd, filename, file,
703 tdb_traverse_read, op, i);
705 case OP_TDB_TRAVERSE_START:
706 i = op_traverse(tdb, pre_fd, filename, file,
707 tdb_traverse, op, i);
709 case OP_TDB_TRAVERSE:
710 /* Terminate: we're in a traverse, and we've
713 case OP_TDB_TRAVERSE_END:
714 fail(filename[file], i+1, "unexpected end traverse");
715 /* FIXME: These must be treated like traverse. */
716 case OP_TDB_FIRSTKEY:
717 if (!key_eq(tdb_firstkey(tdb), op[file][i].data))
718 fail(filename[file], i+1, "bad firstkey");
721 if (!key_eq(tdb_nextkey(tdb, op[file][i].key),
723 fail(filename[file], i+1, "bad nextkey");
726 TDB_DATA f = tdb_fetch(tdb, op[file][i].key);
727 if (!key_eq(f, op[file][i].data))
728 fail(filename[file], i+1, "bad fetch %u",
733 try(tdb_delete(tdb, op[file][i].key), op[file][i].ret);
736 do_post(filename, op, file, i);
741 /* tdbtorture, in particular, can do a tdb_close with a transaction in
743 static struct op *maybe_cancel_transaction(const char *filename,
744 struct op *op, unsigned int *num)
746 unsigned int start = op_transaction_start(op, *num);
749 char *words[] = { "<unknown>", "tdb_close", NULL };
750 add_op(filename, &op, *num, op[start].serial,
751 OP_TDB_TRANSACTION_CANCEL);
752 op_analyze_transaction(filename, op, *num, words);
758 static struct op *load_tracefile(const char *filename, unsigned int *num,
759 unsigned int *hashsize,
760 unsigned int *tdb_flags,
761 unsigned int *open_flags)
764 struct op *op = talloc_array(NULL, struct op, 1);
769 file = grab_file(NULL, filename, NULL);
771 err(1, "Reading %s", filename);
773 lines = strsplit(file, file, "\n", NULL);
775 errx(1, "%s is empty", filename);
777 words = strsplit(lines, lines[0], " ", NULL);
778 if (!streq(words[1], "tdb_open"))
779 fail(filename, 1, "does not start with tdb_open");
781 *hashsize = atoi(words[2]);
782 *tdb_flags = strtoul(words[3], NULL, 0);
783 *open_flags = strtoul(words[4], NULL, 0);
785 for (i = 1; lines[i]; i++) {
786 const struct op_table *opt;
788 words = strsplit(lines, lines[i], " ", NULL);
789 if (!words[0] || !words[1])
790 fail(filename, i+1, "Expected serial number and op");
792 opt = find_keyword(words[1], strlen(words[1]));
794 if (streq(words[1], "tdb_close")) {
797 "lines after tdb_close");
800 return maybe_cancel_transaction(filename,
803 fail(filename, i+1, "Unknown operation '%s'", words[1]);
806 add_op(filename, &op, i, atoi(words[0]), opt->type);
807 opt->enhance_op(filename, op, i, words);
810 fprintf(stderr, "%s:%u:last operation is not tdb_close: incomplete?",
814 return maybe_cancel_transaction(filename, op, num);
817 /* We remember all the keys we've ever seen, and who has them. */
825 unsigned int num_users;
826 struct key_user *user;
829 static const TDB_DATA must_not_exist;
830 static const TDB_DATA must_exist;
831 static const TDB_DATA not_exists_or_empty;
833 /* NULL means doesn't care if it exists or not, &must_exist means
834 * it must exist but we don't care what, &must_not_exist means it must
835 * not exist, otherwise the data it needs. */
836 static const TDB_DATA *needs(const struct op *op)
839 /* FIXME: Pull forward deps, since we can deadlock */
840 case OP_TDB_CHAINLOCK:
841 case OP_TDB_CHAINLOCK_NONBLOCK:
842 case OP_TDB_CHAINLOCK_MARK:
843 case OP_TDB_CHAINLOCK_UNMARK:
844 case OP_TDB_CHAINUNLOCK:
845 case OP_TDB_CHAINLOCK_READ:
846 case OP_TDB_CHAINUNLOCK_READ:
850 if (op->append.pre.dsize == 0)
851 return ¬_exists_or_empty;
852 return &op->append.pre;
855 if (op->flag == TDB_INSERT) {
859 return &must_not_exist;
860 } else if (op->flag == TDB_MODIFY) {
862 return &must_not_exist;
866 /* No flags? Don't care */
873 return &must_not_exist;
875 case OP_TDB_PARSE_RECORD:
877 return &must_not_exist;
880 /* FIXME: handle these. */
881 case OP_TDB_WIPE_ALL:
882 case OP_TDB_FIRSTKEY:
884 case OP_TDB_GET_SEQNUM:
885 case OP_TDB_TRAVERSE:
886 case OP_TDB_TRANSACTION_COMMIT:
887 case OP_TDB_TRANSACTION_CANCEL:
888 case OP_TDB_TRANSACTION_START:
893 return &must_not_exist;
898 return &must_not_exist;
902 errx(1, "Unexpected op %i", op->op);
907 static bool is_transaction(const struct op *op)
909 return op->op == OP_TDB_TRANSACTION_START;
912 /* What's the data after this op? pre if nothing changed. */
913 static const TDB_DATA *gives(const TDB_DATA *key, const TDB_DATA *pre,
916 if (is_transaction(op)) {
919 /* Cancelled transactions don't change anything. */
920 if (op[op->group_len].op == OP_TDB_TRANSACTION_CANCEL)
922 assert(op[op->group_len].op == OP_TDB_TRANSACTION_COMMIT);
924 for (i = 1; i < op->group_len; i++) {
925 /* This skips nested transactions, too */
926 if (key_eq(op[i].key, *key))
927 pre = gives(key, pre, &op[i]);
932 /* Failed ops don't change state of db. */
936 if (op->op == OP_TDB_DELETE || op->op == OP_TDB_WIPE_ALL)
939 if (op->op == OP_TDB_APPEND)
940 return &op->append.post;
942 if (op->op == OP_TDB_STORE)
948 static bool in_transaction(const struct op op[], unsigned int i)
950 return op[i].group_start && is_transaction(&op[op[i].group_start]);
953 static bool is_traverse(const struct op *op)
955 return op->op == OP_TDB_TRAVERSE_START
956 || op->op == OP_TDB_TRAVERSE_READ_START;
959 static bool in_traverse(const struct op op[], unsigned int i)
961 return op[i].group_start && is_traverse(&op[op[i].group_start]);
964 static struct keyinfo *hash_ops(struct op *op[], unsigned int num_ops[],
967 unsigned int i, j, h;
968 struct keyinfo *hash;
970 hash = talloc_zero_array(op[0], struct keyinfo, total_keys*2);
971 for (i = 0; i < num; i++) {
972 for (j = 1; j < num_ops[i]; j++) {
973 /* We can't do this on allocation, due to realloc. */
974 list_head_init(&op[i][j].post);
975 list_head_init(&op[i][j].pre);
977 if (!op[i][j].key.dptr)
980 h = hash_key(&op[i][j].key) % (total_keys * 2);
981 while (!key_eq(hash[h].key, op[i][j].key)) {
982 if (!hash[h].key.dptr) {
983 hash[h].key = op[i][j].key;
986 h = (h + 1) % (total_keys * 2);
988 /* Might as well save some memory if we can. */
989 if (op[i][j].key.dptr != hash[h].key.dptr) {
990 talloc_free(op[i][j].key.dptr);
991 op[i][j].key.dptr = hash[h].key.dptr;
993 hash[h].user = talloc_realloc(hash, hash[h].user,
995 hash[h].num_users+1);
997 /* If it's in a transaction, it's the transaction which
998 * matters from an analysis POV. */
999 if (in_transaction(op[i], j)) {
1000 unsigned start = op[i][j].group_start;
1002 /* Don't include twice. */
1003 if (hash[h].num_users
1004 && hash[h].user[hash[h].num_users-1].file
1006 && hash[h].user[hash[h].num_users-1].op_num
1010 hash[h].user[hash[h].num_users].op_num = start;
1012 hash[h].user[hash[h].num_users].op_num = j;
1013 hash[h].user[hash[h].num_users].file = i;
1014 hash[h].num_users++;
1021 static bool satisfies(const TDB_DATA *key, const TDB_DATA *data,
1022 const struct op *op)
1024 const TDB_DATA *need = NULL;
1026 if (is_transaction(op)) {
1029 /* Look through for an op in this transaction which
1030 * needs this key. */
1031 for (i = 1; i < op->group_len; i++) {
1032 if (key_eq(op[i].key, *key)) {
1033 need = needs(&op[i]);
1034 /* tdb_exists() is special: there might be
1035 * something in the transaction with more
1036 * specific requirements. Other ops don't have
1037 * specific requirements (eg. store or delete),
1038 * but they change the value so we can't get
1039 * more information from future ops. */
1040 if (op[i].op != OP_TDB_EXISTS)
1047 /* Don't need anything? Cool. */
1051 /* This should be tdb_null or a real value. */
1052 assert(data != &must_exist);
1053 assert(data != &must_not_exist);
1054 assert(data != ¬_exists_or_empty);
1056 /* Must not exist? data must not exist. */
1057 if (need == &must_not_exist)
1058 return data == &tdb_null;
1061 if (need == &must_exist)
1062 return data != &tdb_null;
1064 /* Either noexist or empty. */
1065 if (need == ¬_exists_or_empty)
1066 return data->dsize == 0;
1068 /* Needs something specific. */
1069 return key_eq(*data, *need);
1072 static void move_to_front(struct key_user res[], unsigned off, unsigned elem)
1075 struct key_user tmp = res[elem];
1076 memmove(res + off + 1, res + off, (elem - off)*sizeof(res[0]));
1081 static void restore_to_pos(struct key_user res[], unsigned off, unsigned elem)
1084 struct key_user tmp = res[off];
1085 memmove(res + off, res + off + 1, (elem - off)*sizeof(res[0]));
1090 static bool sort_deps(char *filename[], struct op *op[],
1091 struct key_user res[],
1092 unsigned off, unsigned num,
1093 const TDB_DATA *key, const TDB_DATA *data,
1094 unsigned num_files, unsigned fuzz)
1096 unsigned int i, files_done;
1098 bool done[num_files];
1100 /* None left? We're sorted. */
1104 /* Does this make serial numbers go backwards? Allow a little fuzz. */
1106 int serial1 = op[res[off-1].file][res[off-1].op_num].serial;
1107 int serial2 = op[res[off].file][res[off].op_num].serial;
1109 if (serial1 - serial2 > (int)fuzz) {
1111 printf("Serial jump too far (%u -> %u)\n",
1118 memset(done, 0, sizeof(done));
1120 /* Since ops within a trace file are ordered, we just need to figure
1121 * out which file to try next. Since we don't take into account
1122 * inter-key relationships (which exist by virtue of trace file order),
1123 * we minimize the chance of harm by trying to keep in serial order. */
1124 for (files_done = 0, i = off; i < num && files_done < num_files; i++) {
1125 if (done[res[i].file])
1128 this_op = &op[res[i].file][res[i].op_num];
1130 /* Is what we have good enough for this op? */
1131 if (satisfies(key, data, this_op)) {
1132 move_to_front(res, off, i);
1133 if (sort_deps(filename, op, res, off+1, num,
1134 key, gives(key, data, this_op),
1137 restore_to_pos(res, off, i);
1139 done[res[i].file] = true;
1143 /* No combination worked. */
1147 static void check_dep_sorting(struct key_user user[], unsigned num_users,
1152 unsigned minima[num_files];
1154 memset(minima, 0, sizeof(minima));
1155 for (i = 0; i < num_users; i++) {
1156 assert(minima[user[i].file] < user[i].op_num);
1157 minima[user[i].file] = user[i].op_num;
1162 /* All these ops happen on the same key. Which comes first?
1164 * This can happen both because read ops or failed write ops don't
1165 * change serial number, and also due to race since we access the
1166 * number unlocked (the race can cause less detectable ordering problems,
1167 * in which case we'll deadlock and report: fix manually in that case).
1169 static void figure_deps(char *filename[], struct op *op[],
1170 const TDB_DATA *key, struct key_user user[],
1171 unsigned num_users, unsigned num_files)
1173 /* We assume database starts empty. */
1174 const struct TDB_DATA *data = &tdb_null;
1177 /* We prefer to keep strict serial order if possible: it's the
1178 * most likely. We get more lax if that fails. */
1179 for (fuzz = 0; fuzz < 100; fuzz = (fuzz + 1)*2) {
1180 if (sort_deps(filename, op, user, 0, num_users, key, data,
1186 fail(filename[user[0].file], user[0].op_num+1,
1187 "Could not resolve inter-dependencies");
1189 check_dep_sorting(user, num_users, num_files);
1192 static void sort_ops(struct keyinfo hash[], char *filename[], struct op *op[],
1197 /* Gcc nexted function extension. How cool is this? */
1198 int compare_serial(const void *_a, const void *_b)
1200 const struct key_user *a = _a, *b = _b;
1202 /* First, maintain order within any trace file. */
1203 if (a->file == b->file)
1204 return a->op_num - b->op_num;
1206 /* Otherwise, arrange by serial order. */
1207 return op[a->file][a->op_num].serial
1208 - op[b->file][b->op_num].serial;
1211 /* Now sort into serial order. */
1212 for (h = 0; h < total_keys * 2; h++) {
1213 struct key_user *user = hash[h].user;
1215 qsort(user, hash[h].num_users, sizeof(user[0]), compare_serial);
1216 figure_deps(filename, op, &hash[h].key, user, hash[h].num_users,
1221 static int destroy_depend(struct depend *dep)
1223 list_del(&dep->pre_list);
1224 list_del(&dep->post_list);
1228 static void add_dependency(void *ctx,
1231 unsigned int needs_file,
1232 unsigned int needs_opnum,
1233 unsigned int satisfies_file,
1234 unsigned int satisfies_opnum)
1238 /* We don't depend on ourselves. */
1239 if (needs_file == satisfies_file) {
1240 assert(satisfies_opnum < needs_opnum);
1245 printf("%s:%u: depends on %s:%u\n",
1246 filename[needs_file], needs_opnum+1,
1247 filename[satisfies_file], satisfies_opnum+1);
1250 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
1251 /* If something in a traverse depends on something in another
1252 * traverse/transaction, it creates a dependency between the
1254 if ((in_traverse(op[satisfies_file], satisfies_opnum)
1255 && op[needs_file][needs_opnum].group_start)
1256 || (in_traverse(op[needs_file], needs_opnum)
1257 && op[satisfies_file][satisfies_opnum].group_start)) {
1260 /* We are satisfied by end of group. */
1261 sat = op[satisfies_file][satisfies_opnum].group_start;
1262 satisfies_opnum = sat + op[satisfies_file][sat].group_len;
1263 /* And we need that done by start of our group. */
1264 needs_opnum = op[needs_file][needs_opnum].group_start;
1267 /* There is also this case:
1268 * <traverse> <read foo> ...
1269 * <transaction> ... </transaction> <create foo>
1270 * Where if we start the traverse then wait, we could block
1271 * the transaction and deadlock.
1273 * We try to address this by ensuring that where seqnum indicates it's
1274 * possible, we wait for <create foo> before *starting* traverse.
1276 else if (in_traverse(op[needs_file], needs_opnum)) {
1277 struct op *need = &op[needs_file][needs_opnum];
1278 if (op[needs_file][need->group_start].serial >
1279 op[satisfies_file][satisfies_opnum].serial) {
1280 needs_opnum = need->group_start;
1285 /* If you depend on a transaction, you actually depend on it ending. */
1286 if (is_transaction(&op[satisfies_file][satisfies_opnum])) {
1288 += op[satisfies_file][satisfies_opnum].group_len;
1290 printf("-> Actually end of transaction %s:%u\n",
1291 filename[satisfies_file], satisfies_opnum+1);
1294 /* We should never create a dependency from middle of
1296 assert(!in_transaction(op[satisfies_file], satisfies_opnum)
1297 || op[satisfies_file][satisfies_opnum].op
1298 == OP_TDB_TRANSACTION_COMMIT
1299 || op[satisfies_file][satisfies_opnum].op
1300 == OP_TDB_TRANSACTION_CANCEL);
1302 assert(op[needs_file][needs_opnum].op != OP_TDB_TRAVERSE);
1303 assert(op[satisfies_file][satisfies_opnum].op != OP_TDB_TRAVERSE);
1305 dep = talloc(ctx, struct depend);
1306 dep->needs_file = needs_file;
1307 dep->needs_opnum = needs_opnum;
1308 dep->satisfies_file = satisfies_file;
1309 dep->satisfies_opnum = satisfies_opnum;
1310 list_add(&op[satisfies_file][satisfies_opnum].post, &dep->post_list);
1311 list_add(&op[needs_file][needs_opnum].pre, &dep->pre_list);
1312 talloc_set_destructor(dep, destroy_depend);
1315 static bool changes_db(const TDB_DATA *key, const struct op *op)
1317 return gives(key, NULL, op) != NULL;
1320 static void depend_on_previous(struct op *op[],
1323 struct key_user user[],
1333 if (prev == i - 1) {
1334 /* Just depend on previous. */
1335 add_dependency(NULL, op, filename,
1336 user[i].file, user[i].op_num,
1337 user[prev].file, user[prev].op_num);
1341 /* We have to wait for the readers. Find last one in *each* file. */
1342 memset(deps, 0, sizeof(deps));
1343 deps[user[i].file] = true;
1344 for (j = i - 1; j > prev; j--) {
1345 if (!deps[user[j].file]) {
1346 add_dependency(NULL, op, filename,
1347 user[i].file, user[i].op_num,
1348 user[j].file, user[j].op_num);
1349 deps[user[j].file] = true;
1354 /* This is simple, but not complete. We don't take into account
1355 * indirect dependencies. */
1356 static void optimize_dependencies(struct op *op[], unsigned int num_ops[],
1361 /* There can only be one real dependency on each file */
1362 for (i = 0; i < num; i++) {
1363 for (j = 1; j < num_ops[i]; j++) {
1364 struct depend *dep, *next;
1365 struct depend *prev[num];
1367 memset(prev, 0, sizeof(prev));
1369 list_for_each_safe(&op[i][j].pre, dep, next, pre_list) {
1370 if (!prev[dep->satisfies_file]) {
1371 prev[dep->satisfies_file] = dep;
1374 if (prev[dep->satisfies_file]->satisfies_opnum
1375 < dep->satisfies_opnum) {
1376 talloc_free(prev[dep->satisfies_file]);
1377 prev[dep->satisfies_file] = dep;
1384 for (i = 0; i < num; i++) {
1387 for (j = 0; j < num; j++)
1390 for (j = 1; j < num_ops[i]; j++) {
1391 struct depend *dep, *next;
1393 list_for_each_safe(&op[i][j].pre, dep, next, pre_list) {
1394 if (deps[dep->satisfies_file]
1395 >= (int)dep->satisfies_opnum)
1398 deps[dep->satisfies_file]
1399 = dep->satisfies_opnum;
1405 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
1406 struct traverse_dep {
1408 unsigned int op_num;
1411 /* Force an order among the traversals, so they don't deadlock (as much) */
1412 static void make_traverse_depends(char *filename[],
1413 struct op *op[], unsigned int num_ops[],
1416 unsigned int i, num_traversals = 0;
1418 struct traverse_dep *dep;
1420 /* Sort by which one runs first. */
1421 int compare_traverse_dep(const void *_a, const void *_b)
1423 const struct traverse_dep *ta = _a, *tb = _b;
1424 const struct op *a = &op[ta->file][ta->op_num],
1425 *b = &op[tb->file][tb->op_num];
1427 if (a->serial != b->serial)
1428 return a->serial - b->serial;
1430 /* If they have same serial, it means one didn't make any
1431 * changes. Thus sort by end in that case. */
1432 return a[a->group_len].serial - b[b->group_len].serial;
1435 dep = talloc_array(NULL, struct traverse_dep, 1);
1438 for (i = 0; i < num; i++) {
1439 for (j = 1; j < num_ops[i]; j++) {
1440 /* Traverse start (ignore those in
1441 * transactions; they're already covered by
1442 * transaction dependencies). */
1443 if (is_traverse(&op[i][j])
1444 && !in_transaction(op[i], j)) {
1445 dep = talloc_realloc(NULL, dep,
1446 struct traverse_dep,
1448 dep[num_traversals].file = i;
1449 dep[num_traversals].op_num = j;
1454 qsort(dep, num_traversals, sizeof(dep[0]), compare_traverse_dep);
1456 for (i = 1; i < num_traversals; i++) {
1457 const struct op *prev = &op[dep[i-1].file][dep[i-1].op_num];
1459 /* Only make dependency if it's clear. */
1460 if (compare_traverse_dep(&dep[i], &dep[i-1])) {
1461 /* i depends on end of traverse i-1. */
1462 add_dependency(NULL, op, filename,
1463 dep[i].file, dep[i].op_num,
1464 dep[i-1].file, dep[i-1].op_num
1472 static void derive_dependencies(char *filename[],
1473 struct op *op[], unsigned int num_ops[],
1476 struct keyinfo *hash;
1479 /* Create hash table for faster key lookup. */
1480 hash = hash_ops(op, num_ops, num);
1482 /* Sort them by serial number. */
1483 sort_ops(hash, filename, op, num);
1485 /* Create dependencies back to the last change, rather than
1486 * creating false dependencies by naively making each one
1487 * depend on the previous. This has two purposes: it makes
1488 * later optimization simpler, and it also avoids deadlock with
1489 * same sequence number ops inside traversals (if one
1490 * traversal doesn't write anything, two ops can have the same
1491 * sequence number yet we can create a traversal dependency
1492 * the other way). */
1493 for (h = 0; h < total_keys * 2; h++) {
1496 if (hash[h].num_users < 2)
1499 for (i = 0; i < hash[h].num_users; i++) {
1500 if (changes_db(&hash[h].key, &op[hash[h].user[i].file]
1501 [hash[h].user[i].op_num])) {
1502 depend_on_previous(op, filename, num,
1503 hash[h].user, i, prev);
1505 } else if (prev >= 0)
1506 add_dependency(hash, op, filename,
1507 hash[h].user[i].file,
1508 hash[h].user[i].op_num,
1509 hash[h].user[prev].file,
1510 hash[h].user[prev].op_num);
1514 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
1515 make_traverse_depends(filename, op, num_ops, num);
1518 optimize_dependencies(op, num_ops, num);
1521 int main(int argc, char *argv[])
1523 struct timeval start, end;
1524 unsigned int i, num_ops[argc], hashsize[argc], tdb_flags[argc], open_flags[argc];
1525 struct op *op[argc];
1531 errx(1, "Usage: %s <tdbfile> <tracefile>...", argv[0]);
1533 pipes = talloc_array(NULL, struct pipe, argc - 2);
1534 for (i = 0; i < argc - 2; i++) {
1535 printf("Loading tracefile %s...", argv[2+i]);
1537 op[i] = load_tracefile(argv[2+i], &num_ops[i], &hashsize[i],
1538 &tdb_flags[i], &open_flags[i]);
1539 if (pipe(pipes[i].fd) != 0)
1540 err(1, "creating pipe");
1544 printf("Calculating inter-dependencies...");
1546 derive_dependencies(argv+2, op, num_ops, i);
1549 /* Don't fork for single arg case: simple debugging. */
1551 struct tdb_context *tdb;
1552 tdb = tdb_open_ex(argv[1], hashsize[0], tdb_flags[0]|TDB_NOSYNC,
1553 open_flags[0], 0600, NULL, hash_key);
1554 printf("Single threaded run...");
1557 run_ops(tdb, pipes[0].fd[0], argv+2, op, 0, 1, num_ops[0],
1559 check_deps(argv[2], op[0], num_ops[0]);
1566 err(1, "creating pipe");
1568 for (i = 0; i < argc - 2; i++) {
1569 struct tdb_context *tdb;
1573 err(1, "fork failed");
1576 tdb = tdb_open_ex(argv[1], hashsize[i],
1577 tdb_flags[i]|TDB_NOSYNC,
1578 open_flags[i], 0600, NULL, hash_key);
1580 err(1, "Opening tdb %s", argv[1]);
1582 /* This catches parent exiting. */
1583 if (read(fds[0], &c, 1) != 1)
1585 run_ops(tdb, pipes[i].fd[0], argv+2, op, i, 1,
1587 check_deps(argv[2+i], op[i], num_ops[i]);
1594 /* Let everything settle. */
1597 printf("Starting run...");
1599 gettimeofday(&start, NULL);
1600 /* Tell them all to go! Any write of sufficient length will do. */
1601 if (write(fds[1], hashsize, i) != i)
1602 err(1, "Writing to wakeup pipe");
1604 for (i = 0; i < argc - 2; i++) {
1607 if (!WIFEXITED(status)) {
1608 warnx("Child died with signal %i", WTERMSIG(status));
1610 } else if (WEXITSTATUS(status) != 0)
1611 /* Assume child spat out error. */
1617 gettimeofday(&end, NULL);
1620 end.tv_sec -= start.tv_sec;
1621 printf("Time replaying: %lu usec\n",
1622 end.tv_sec * 1000000UL + (end.tv_usec - start.tv_usec));