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_find_start(struct op op[], unsigned int op_num, enum op_type type)
327 for (i = op_num-1; i > 0; i--) {
328 if (op[i].op == type && !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_find_start(op, op_num, OP_TDB_TRANSACTION_START);
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 static void op_analyze_traverse(const char *filename,
357 struct op op[], unsigned int op_num,
362 op[op_num].key = tdb_null;
364 /* = %u means traverse function terminated. */
366 if (!streq(words[2], "=") || !words[3] || words[4])
367 fail(filename, op_num+1, "expect = <num>");
368 op[op_num].ret = atoi(words[3]);
372 start = op_find_start(op, op_num, OP_TDB_TRAVERSE_START);
374 start = op_find_start(op, op_num, OP_TDB_TRAVERSE_READ_START);
376 fail(filename, op_num+1, "no traversal start found");
378 op[start].group_len = op_num - start;
380 for (i = start; i <= op_num; i++)
381 op[i].group_start = start;
384 /* Keep -Wmissing-declarations happy: */
385 const struct op_table *
386 find_keyword (register const char *str, register unsigned int len);
388 #include "keywords.c"
391 /* We can have more than one */
392 struct list_node pre_list;
393 struct list_node post_list;
394 unsigned int needs_file;
395 unsigned int needs_opnum;
396 unsigned int satisfies_file;
397 unsigned int satisfies_opnum;
400 static void check_deps(const char *filename, struct op op[], unsigned int num)
405 for (i = 1; i < num; i++)
406 if (!list_empty(&op[i].pre))
407 fail(filename, i+1, "Still has dependencies");
411 static void dump_pre(char *filename[], struct op *op[],
412 unsigned int file, unsigned int i)
416 printf("%s:%u (%u) still waiting for:\n", filename[file], i+1,
418 list_for_each(&op[file][i].pre, dep, pre_list)
419 printf(" %s:%u (%u)\n",
420 filename[dep->satisfies_file], dep->satisfies_opnum+1,
421 op[dep->satisfies_file][dep->satisfies_opnum].serial);
422 check_deps(filename[file], op[file], i);
425 /* We simply read/write pointers, since we all are children. */
426 static bool do_pre(struct tdb_context *tdb,
427 char *filename[], struct op *op[],
428 unsigned int file, int pre_fd, unsigned int i,
431 while (!list_empty(&op[file][i].pre)) {
435 printf("%s:%u:waiting for pre\n", filename[file], i+1);
442 while (read(pre_fd, &dep, sizeof(dep)) != sizeof(dep)) {
443 if (errno == EINTR) {
445 warnx("%s:%u:avoiding deadlock",
446 filename[file], i+1);
449 dump_pre(filename, op, file, i);
452 errx(1, "Reading from pipe");
457 printf("%s:%u:got pre %u from %s:%u\n", filename[file], i+1,
458 dep->needs_opnum+1, filename[dep->satisfies_file],
459 dep->satisfies_opnum+1);
462 /* This could be any op, not just this one. */
468 static void do_post(char *filename[], struct op *op[],
469 unsigned int file, unsigned int i)
473 list_for_each(&op[file][i].post, dep, post_list) {
475 printf("%s:%u:sending to file %s:%u\n", filename[file], i+1,
476 filename[dep->needs_file], dep->needs_opnum+1);
478 if (write(pipes[dep->needs_file].fd[1], &dep, sizeof(dep))
480 err(1, "%s:%u failed to tell file %s",
481 filename[file], i+1, filename[dep->needs_file]);
485 static int get_len(TDB_DATA key, TDB_DATA data, void *private_data)
490 static unsigned run_ops(struct tdb_context *tdb,
495 unsigned int start, unsigned int stop,
498 struct traverse_info {
507 /* More complex. Just do whatever's they did at the n'th entry. */
508 static int nontrivial_traverse(struct tdb_context *tdb,
509 TDB_DATA key, TDB_DATA data,
512 struct traverse_info *tinfo = _tinfo;
513 unsigned int trav_len = tinfo->op[tinfo->file][tinfo->start].group_len;
514 bool avoid_deadlock = false;
516 if (tinfo->i == tinfo->start + trav_len) {
517 /* This can happen if traverse expects to be empty. */
520 fail(tinfo->filename[tinfo->file], tinfo->start + 1,
521 "traverse did not terminate");
524 if (tinfo->op[tinfo->file][tinfo->i].op != OP_TDB_TRAVERSE)
525 fail(tinfo->filename[tinfo->file], tinfo->start + 1,
526 "%s:%u:traverse terminated early");
528 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
529 avoid_deadlock = true;
532 /* Run any normal ops. */
533 tinfo->i = run_ops(tdb, tinfo->pre_fd, tinfo->filename, tinfo->op,
534 tinfo->file, tinfo->i+1, tinfo->start + trav_len,
537 /* We backed off, or we hit OP_TDB_TRAVERSE_END. */
538 if (tinfo->op[tinfo->file][tinfo->i].op != OP_TDB_TRAVERSE)
544 static unsigned op_traverse(struct tdb_context *tdb,
548 int (*traversefn)(struct tdb_context *,
549 tdb_traverse_func, void *),
553 struct traverse_info tinfo = { op, filename, file, pre_fd,
556 traversefn(tdb, nontrivial_traverse, &tinfo);
558 /* Traversing in wrong order can have strange effects: eg. if
559 * original traverse went A (delete A), B, we might do B
560 * (delete A). So if we have ops left over, we do it now. */
561 while (tinfo.i != start + op[file][start].group_len) {
562 if (op[file][tinfo.i].op == OP_TDB_TRAVERSE)
565 tinfo.i = run_ops(tdb, pre_fd, filename, op, file,
567 start + op[file][start].group_len,
574 static void break_out(int sig)
578 static __attribute__((noinline))
579 unsigned run_ops(struct tdb_context *tdb,
584 unsigned int start, unsigned int stop,
590 sa.sa_handler = break_out;
593 sigaction(SIGALRM, &sa, NULL);
594 for (i = start; i < stop; i++) {
595 if (!do_pre(tdb, filename, op, file, pre_fd, i, backoff))
598 switch (op[file][i].op) {
600 try(tdb_lockall(tdb), op[file][i].ret);
602 case OP_TDB_LOCKALL_MARK:
603 try(tdb_lockall_mark(tdb), op[file][i].ret);
605 case OP_TDB_LOCKALL_UNMARK:
606 try(tdb_lockall_unmark(tdb), op[file][i].ret);
608 case OP_TDB_LOCKALL_NONBLOCK:
609 unreliable(tdb_lockall_nonblock(tdb), op[file][i].ret,
610 tdb_lockall(tdb), tdb_unlockall(tdb));
612 case OP_TDB_UNLOCKALL:
613 try(tdb_unlockall(tdb), op[file][i].ret);
615 case OP_TDB_LOCKALL_READ:
616 try(tdb_lockall_read(tdb), op[file][i].ret);
618 case OP_TDB_LOCKALL_READ_NONBLOCK:
619 unreliable(tdb_lockall_read_nonblock(tdb),
621 tdb_lockall_read(tdb),
622 tdb_unlockall_read(tdb));
624 case OP_TDB_UNLOCKALL_READ:
625 try(tdb_unlockall_read(tdb), op[file][i].ret);
627 case OP_TDB_CHAINLOCK:
628 try(tdb_chainlock(tdb, op[file][i].key),
631 case OP_TDB_CHAINLOCK_NONBLOCK:
632 unreliable(tdb_chainlock_nonblock(tdb, op[file][i].key),
634 tdb_chainlock(tdb, op[file][i].key),
635 tdb_chainunlock(tdb, op[file][i].key));
637 case OP_TDB_CHAINLOCK_MARK:
638 try(tdb_chainlock_mark(tdb, op[file][i].key),
641 case OP_TDB_CHAINLOCK_UNMARK:
642 try(tdb_chainlock_unmark(tdb, op[file][i].key),
645 case OP_TDB_CHAINUNLOCK:
646 try(tdb_chainunlock(tdb, op[file][i].key),
649 case OP_TDB_CHAINLOCK_READ:
650 try(tdb_chainlock_read(tdb, op[file][i].key),
653 case OP_TDB_CHAINUNLOCK_READ:
654 try(tdb_chainunlock_read(tdb, op[file][i].key),
657 case OP_TDB_PARSE_RECORD:
658 try(tdb_parse_record(tdb, op[file][i].key, get_len,
663 try(tdb_exists(tdb, op[file][i].key), op[file][i].ret);
666 try(tdb_store(tdb, op[file][i].key, op[file][i].data,
671 try(tdb_append(tdb, op[file][i].key, op[file][i].data),
674 case OP_TDB_GET_SEQNUM:
675 try(tdb_get_seqnum(tdb), op[file][i].ret);
677 case OP_TDB_WIPE_ALL:
678 try(tdb_wipe_all(tdb), op[file][i].ret);
680 case OP_TDB_TRANSACTION_START:
681 try(tdb_transaction_start(tdb), op[file][i].ret);
683 case OP_TDB_TRANSACTION_CANCEL:
684 try(tdb_transaction_cancel(tdb), op[file][i].ret);
686 case OP_TDB_TRANSACTION_COMMIT:
687 try(tdb_transaction_commit(tdb), op[file][i].ret);
689 case OP_TDB_TRAVERSE_READ_START:
690 i = op_traverse(tdb, pre_fd, filename, file,
691 tdb_traverse_read, op, i);
693 case OP_TDB_TRAVERSE_START:
694 i = op_traverse(tdb, pre_fd, filename, file,
695 tdb_traverse, op, i);
697 case OP_TDB_TRAVERSE:
698 /* Terminate: we're in a traverse, and we've
701 case OP_TDB_TRAVERSE_END:
702 fail(filename[file], i+1, "unexpected end traverse");
703 /* FIXME: These must be treated like traverse. */
704 case OP_TDB_FIRSTKEY:
705 if (!key_eq(tdb_firstkey(tdb), op[file][i].data))
706 fail(filename[file], i+1, "bad firstkey");
709 if (!key_eq(tdb_nextkey(tdb, op[file][i].key),
711 fail(filename[file], i+1, "bad nextkey");
714 TDB_DATA f = tdb_fetch(tdb, op[file][i].key);
715 if (!key_eq(f, op[file][i].data))
716 fail(filename[file], i+1, "bad fetch %u",
721 try(tdb_delete(tdb, op[file][i].key), op[file][i].ret);
724 do_post(filename, op, file, i);
729 /* tdbtorture, in particular, can do a tdb_close with a transaction in
731 static struct op *maybe_cancel_transaction(const char *filename,
732 struct op *op, unsigned int *num)
734 unsigned int start = op_find_start(op, *num, OP_TDB_TRANSACTION_START);
737 char *words[] = { "<unknown>", "tdb_close", NULL };
738 add_op(filename, &op, *num, op[start].serial,
739 OP_TDB_TRANSACTION_CANCEL);
740 op_analyze_transaction(filename, op, *num, words);
746 static struct op *load_tracefile(const char *filename, unsigned int *num,
747 unsigned int *hashsize,
748 unsigned int *tdb_flags,
749 unsigned int *open_flags)
752 struct op *op = talloc_array(NULL, struct op, 1);
757 file = grab_file(NULL, filename, NULL);
759 err(1, "Reading %s", filename);
761 lines = strsplit(file, file, "\n", NULL);
763 errx(1, "%s is empty", filename);
765 words = strsplit(lines, lines[0], " ", NULL);
766 if (!streq(words[1], "tdb_open"))
767 fail(filename, 1, "does not start with tdb_open");
769 *hashsize = atoi(words[2]);
770 *tdb_flags = strtoul(words[3], NULL, 0);
771 *open_flags = strtoul(words[4], NULL, 0);
773 for (i = 1; lines[i]; i++) {
774 const struct op_table *opt;
776 words = strsplit(lines, lines[i], " ", NULL);
777 if (!words[0] || !words[1])
778 fail(filename, i+1, "Expected serial number and op");
780 opt = find_keyword(words[1], strlen(words[1]));
782 if (streq(words[1], "tdb_close")) {
785 "lines after tdb_close");
788 return maybe_cancel_transaction(filename,
791 fail(filename, i+1, "Unknown operation '%s'", words[1]);
794 add_op(filename, &op, i, atoi(words[0]), opt->type);
795 opt->enhance_op(filename, op, i, words);
798 fprintf(stderr, "%s:%u:last operation is not tdb_close: incomplete?",
802 return maybe_cancel_transaction(filename, op, num);
805 /* We remember all the keys we've ever seen, and who has them. */
813 unsigned int num_users;
814 struct key_user *user;
817 static const TDB_DATA must_not_exist;
818 static const TDB_DATA must_exist;
819 static const TDB_DATA not_exists_or_empty;
821 /* NULL means doesn't care if it exists or not, &must_exist means
822 * it must exist but we don't care what, &must_not_exist means it must
823 * not exist, otherwise the data it needs. */
824 static const TDB_DATA *needs(const struct op *op)
827 /* FIXME: Pull forward deps, since we can deadlock */
828 case OP_TDB_CHAINLOCK:
829 case OP_TDB_CHAINLOCK_NONBLOCK:
830 case OP_TDB_CHAINLOCK_MARK:
831 case OP_TDB_CHAINLOCK_UNMARK:
832 case OP_TDB_CHAINUNLOCK:
833 case OP_TDB_CHAINLOCK_READ:
834 case OP_TDB_CHAINUNLOCK_READ:
838 if (op->append.pre.dsize == 0)
839 return ¬_exists_or_empty;
840 return &op->append.pre;
843 if (op->flag == TDB_INSERT) {
847 return &must_not_exist;
848 } else if (op->flag == TDB_MODIFY) {
850 return &must_not_exist;
854 /* No flags? Don't care */
861 return &must_not_exist;
863 case OP_TDB_PARSE_RECORD:
865 return &must_not_exist;
868 /* FIXME: handle these. */
869 case OP_TDB_WIPE_ALL:
870 case OP_TDB_FIRSTKEY:
872 case OP_TDB_GET_SEQNUM:
873 case OP_TDB_TRAVERSE:
874 case OP_TDB_TRANSACTION_COMMIT:
875 case OP_TDB_TRANSACTION_CANCEL:
876 case OP_TDB_TRANSACTION_START:
881 return &must_not_exist;
886 return &must_not_exist;
890 errx(1, "Unexpected op %i", op->op);
895 static bool starts_transaction(const struct op *op)
897 return op->op == OP_TDB_TRANSACTION_START;
900 static bool in_transaction(const struct op op[], unsigned int i)
902 return op[i].group_start && starts_transaction(&op[op[i].group_start]);
905 static bool starts_traverse(const struct op *op)
907 return op->op == OP_TDB_TRAVERSE_START
908 || op->op == OP_TDB_TRAVERSE_READ_START;
911 static bool in_traverse(const struct op op[], unsigned int i)
913 return op[i].group_start && starts_traverse(&op[op[i].group_start]);
916 /* What's the data after this op? pre if nothing changed. */
917 static const TDB_DATA *gives(const TDB_DATA *key, const TDB_DATA *pre,
920 if (starts_transaction(op)) {
923 /* Cancelled transactions don't change anything. */
924 if (op[op->group_len].op == OP_TDB_TRANSACTION_CANCEL)
926 assert(op[op->group_len].op == OP_TDB_TRANSACTION_COMMIT);
928 for (i = 1; i < op->group_len; i++) {
929 /* This skips nested transactions, too */
930 if (key_eq(op[i].key, *key))
931 pre = gives(key, pre, &op[i]);
936 /* Failed ops don't change state of db. */
940 if (op->op == OP_TDB_DELETE || op->op == OP_TDB_WIPE_ALL)
943 if (op->op == OP_TDB_APPEND)
944 return &op->append.post;
946 if (op->op == OP_TDB_STORE)
952 static struct keyinfo *hash_ops(struct op *op[], unsigned int num_ops[],
955 unsigned int i, j, h;
956 struct keyinfo *hash;
958 hash = talloc_zero_array(op[0], struct keyinfo, total_keys*2);
959 for (i = 0; i < num; i++) {
960 for (j = 1; j < num_ops[i]; j++) {
961 /* We can't do this on allocation, due to realloc. */
962 list_head_init(&op[i][j].post);
963 list_head_init(&op[i][j].pre);
965 if (!op[i][j].key.dptr)
968 h = hash_key(&op[i][j].key) % (total_keys * 2);
969 while (!key_eq(hash[h].key, op[i][j].key)) {
970 if (!hash[h].key.dptr) {
971 hash[h].key = op[i][j].key;
974 h = (h + 1) % (total_keys * 2);
976 /* Might as well save some memory if we can. */
977 if (op[i][j].key.dptr != hash[h].key.dptr) {
978 talloc_free(op[i][j].key.dptr);
979 op[i][j].key.dptr = hash[h].key.dptr;
981 hash[h].user = talloc_realloc(hash, hash[h].user,
983 hash[h].num_users+1);
985 /* If it's in a transaction, it's the transaction which
986 * matters from an analysis POV. */
987 if (in_transaction(op[i], j)) {
988 unsigned start = op[i][j].group_start;
990 /* Don't include twice. */
991 if (hash[h].num_users
992 && hash[h].user[hash[h].num_users-1].file
994 && hash[h].user[hash[h].num_users-1].op_num
998 hash[h].user[hash[h].num_users].op_num = start;
1000 hash[h].user[hash[h].num_users].op_num = j;
1001 hash[h].user[hash[h].num_users].file = i;
1002 hash[h].num_users++;
1009 static bool satisfies(const TDB_DATA *key, const TDB_DATA *data,
1010 const struct op *op)
1012 const TDB_DATA *need = NULL;
1014 if (starts_transaction(op)) {
1017 /* Look through for an op in this transaction which
1018 * needs this key. */
1019 for (i = 1; i < op->group_len; i++) {
1020 if (key_eq(op[i].key, *key)) {
1021 need = needs(&op[i]);
1022 /* tdb_exists() is special: there might be
1023 * something in the transaction with more
1024 * specific requirements. Other ops don't have
1025 * specific requirements (eg. store or delete),
1026 * but they change the value so we can't get
1027 * more information from future ops. */
1028 if (op[i].op != OP_TDB_EXISTS)
1035 /* Don't need anything? Cool. */
1039 /* This should be tdb_null or a real value. */
1040 assert(data != &must_exist);
1041 assert(data != &must_not_exist);
1042 assert(data != ¬_exists_or_empty);
1044 /* Must not exist? data must not exist. */
1045 if (need == &must_not_exist)
1046 return data == &tdb_null;
1049 if (need == &must_exist)
1050 return data != &tdb_null;
1052 /* Either noexist or empty. */
1053 if (need == ¬_exists_or_empty)
1054 return data->dsize == 0;
1056 /* Needs something specific. */
1057 return key_eq(*data, *need);
1060 static void move_to_front(struct key_user res[], unsigned off, unsigned elem)
1063 struct key_user tmp = res[elem];
1064 memmove(res + off + 1, res + off, (elem - off)*sizeof(res[0]));
1069 static void restore_to_pos(struct key_user res[], unsigned off, unsigned elem)
1072 struct key_user tmp = res[off];
1073 memmove(res + off, res + off + 1, (elem - off)*sizeof(res[0]));
1078 static bool sort_deps(char *filename[], struct op *op[],
1079 struct key_user res[],
1080 unsigned off, unsigned num,
1081 const TDB_DATA *key, const TDB_DATA *data,
1082 unsigned num_files, unsigned fuzz)
1084 unsigned int i, files_done;
1086 bool done[num_files];
1088 /* None left? We're sorted. */
1092 /* Does this make serial numbers go backwards? Allow a little fuzz. */
1094 int serial1 = op[res[off-1].file][res[off-1].op_num].serial;
1095 int serial2 = op[res[off].file][res[off].op_num].serial;
1097 if (serial1 - serial2 > (int)fuzz) {
1099 printf("Serial jump too far (%u -> %u)\n",
1106 memset(done, 0, sizeof(done));
1108 /* Since ops within a trace file are ordered, we just need to figure
1109 * out which file to try next. Since we don't take into account
1110 * inter-key relationships (which exist by virtue of trace file order),
1111 * we minimize the chance of harm by trying to keep in serial order. */
1112 for (files_done = 0, i = off; i < num && files_done < num_files; i++) {
1113 if (done[res[i].file])
1116 this_op = &op[res[i].file][res[i].op_num];
1118 /* Is what we have good enough for this op? */
1119 if (satisfies(key, data, this_op)) {
1120 move_to_front(res, off, i);
1121 if (sort_deps(filename, op, res, off+1, num,
1122 key, gives(key, data, this_op),
1125 restore_to_pos(res, off, i);
1127 done[res[i].file] = true;
1131 /* No combination worked. */
1135 static void check_dep_sorting(struct key_user user[], unsigned num_users,
1140 unsigned minima[num_files];
1142 memset(minima, 0, sizeof(minima));
1143 for (i = 0; i < num_users; i++) {
1144 assert(minima[user[i].file] < user[i].op_num);
1145 minima[user[i].file] = user[i].op_num;
1150 /* All these ops happen on the same key. Which comes first?
1152 * This can happen both because read ops or failed write ops don't
1153 * change serial number, and also due to race since we access the
1154 * number unlocked (the race can cause less detectable ordering problems,
1155 * in which case we'll deadlock and report: fix manually in that case).
1157 static void figure_deps(char *filename[], struct op *op[],
1158 const TDB_DATA *key, struct key_user user[],
1159 unsigned num_users, unsigned num_files)
1161 /* We assume database starts empty. */
1162 const struct TDB_DATA *data = &tdb_null;
1165 /* We prefer to keep strict serial order if possible: it's the
1166 * most likely. We get more lax if that fails. */
1167 for (fuzz = 0; fuzz < 100; fuzz = (fuzz + 1)*2) {
1168 if (sort_deps(filename, op, user, 0, num_users, key, data,
1174 fail(filename[user[0].file], user[0].op_num+1,
1175 "Could not resolve inter-dependencies");
1177 check_dep_sorting(user, num_users, num_files);
1180 static void sort_ops(struct keyinfo hash[], char *filename[], struct op *op[],
1185 /* Gcc nexted function extension. How cool is this? */
1186 int compare_serial(const void *_a, const void *_b)
1188 const struct key_user *a = _a, *b = _b;
1190 /* First, maintain order within any trace file. */
1191 if (a->file == b->file)
1192 return a->op_num - b->op_num;
1194 /* Otherwise, arrange by serial order. */
1195 return op[a->file][a->op_num].serial
1196 - op[b->file][b->op_num].serial;
1199 /* Now sort into serial order. */
1200 for (h = 0; h < total_keys * 2; h++) {
1201 struct key_user *user = hash[h].user;
1203 qsort(user, hash[h].num_users, sizeof(user[0]), compare_serial);
1204 figure_deps(filename, op, &hash[h].key, user, hash[h].num_users,
1209 static int destroy_depend(struct depend *dep)
1211 list_del(&dep->pre_list);
1212 list_del(&dep->post_list);
1216 static void add_dependency(void *ctx,
1219 unsigned int needs_file,
1220 unsigned int needs_opnum,
1221 unsigned int satisfies_file,
1222 unsigned int satisfies_opnum)
1226 /* We don't depend on ourselves. */
1227 if (needs_file == satisfies_file) {
1228 assert(satisfies_opnum < needs_opnum);
1233 printf("%s:%u: depends on %s:%u\n",
1234 filename[needs_file], needs_opnum+1,
1235 filename[satisfies_file], satisfies_opnum+1);
1238 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
1239 /* If something in a traverse depends on something in another
1240 * traverse/transaction, it creates a dependency between the
1242 if ((in_traverse(op[satisfies_file], satisfies_opnum)
1243 && op[needs_file][needs_opnum].group_start)
1244 || (in_traverse(op[needs_file], needs_opnum)
1245 && op[satisfies_file][satisfies_opnum].group_start)) {
1248 /* We are satisfied by end of group. */
1249 sat = op[satisfies_file][satisfies_opnum].group_start;
1250 satisfies_opnum = sat + op[satisfies_file][sat].group_len;
1251 /* And we need that done by start of our group. */
1252 needs_opnum = op[needs_file][needs_opnum].group_start;
1255 /* There is also this case:
1256 * <traverse> <read foo> ...
1257 * <transaction> ... </transaction> <create foo>
1258 * Where if we start the traverse then wait, we could block
1259 * the transaction and deadlock.
1261 * We try to address this by ensuring that where seqnum indicates it's
1262 * possible, we wait for <create foo> before *starting* traverse.
1264 else if (in_traverse(op[needs_file], needs_opnum)) {
1265 struct op *need = &op[needs_file][needs_opnum];
1266 if (op[needs_file][need->group_start].serial >
1267 op[satisfies_file][satisfies_opnum].serial) {
1268 needs_opnum = need->group_start;
1273 /* If you depend on a transaction, you actually depend on it ending. */
1274 if (starts_transaction(&op[satisfies_file][satisfies_opnum])) {
1276 += op[satisfies_file][satisfies_opnum].group_len;
1278 printf("-> Actually end of transaction %s:%u\n",
1279 filename[satisfies_file], satisfies_opnum+1);
1282 /* We should never create a dependency from middle of
1284 assert(!in_transaction(op[satisfies_file], satisfies_opnum)
1285 || op[satisfies_file][satisfies_opnum].op
1286 == OP_TDB_TRANSACTION_COMMIT
1287 || op[satisfies_file][satisfies_opnum].op
1288 == OP_TDB_TRANSACTION_CANCEL);
1290 assert(op[needs_file][needs_opnum].op != OP_TDB_TRAVERSE);
1291 assert(op[satisfies_file][satisfies_opnum].op != OP_TDB_TRAVERSE);
1293 dep = talloc(ctx, struct depend);
1294 dep->needs_file = needs_file;
1295 dep->needs_opnum = needs_opnum;
1296 dep->satisfies_file = satisfies_file;
1297 dep->satisfies_opnum = satisfies_opnum;
1298 list_add(&op[satisfies_file][satisfies_opnum].post, &dep->post_list);
1299 list_add(&op[needs_file][needs_opnum].pre, &dep->pre_list);
1300 talloc_set_destructor(dep, destroy_depend);
1303 static bool changes_db(const TDB_DATA *key, const struct op *op)
1305 return gives(key, NULL, op) != NULL;
1308 static void depend_on_previous(struct op *op[],
1311 struct key_user user[],
1321 if (prev == i - 1) {
1322 /* Just depend on previous. */
1323 add_dependency(NULL, op, filename,
1324 user[i].file, user[i].op_num,
1325 user[prev].file, user[prev].op_num);
1329 /* We have to wait for the readers. Find last one in *each* file. */
1330 memset(deps, 0, sizeof(deps));
1331 deps[user[i].file] = true;
1332 for (j = i - 1; j > prev; j--) {
1333 if (!deps[user[j].file]) {
1334 add_dependency(NULL, op, filename,
1335 user[i].file, user[i].op_num,
1336 user[j].file, user[j].op_num);
1337 deps[user[j].file] = true;
1342 /* This is simple, but not complete. We don't take into account
1343 * indirect dependencies. */
1344 static void optimize_dependencies(struct op *op[], unsigned int num_ops[],
1349 /* There can only be one real dependency on each file */
1350 for (i = 0; i < num; i++) {
1351 for (j = 1; j < num_ops[i]; j++) {
1352 struct depend *dep, *next;
1353 struct depend *prev[num];
1355 memset(prev, 0, sizeof(prev));
1357 list_for_each_safe(&op[i][j].pre, dep, next, pre_list) {
1358 if (!prev[dep->satisfies_file]) {
1359 prev[dep->satisfies_file] = dep;
1362 if (prev[dep->satisfies_file]->satisfies_opnum
1363 < dep->satisfies_opnum) {
1364 talloc_free(prev[dep->satisfies_file]);
1365 prev[dep->satisfies_file] = dep;
1372 for (i = 0; i < num; i++) {
1375 for (j = 0; j < num; j++)
1378 for (j = 1; j < num_ops[i]; j++) {
1379 struct depend *dep, *next;
1381 list_for_each_safe(&op[i][j].pre, dep, next, pre_list) {
1382 if (deps[dep->satisfies_file]
1383 >= (int)dep->satisfies_opnum)
1386 deps[dep->satisfies_file]
1387 = dep->satisfies_opnum;
1393 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
1394 struct traverse_dep {
1396 unsigned int op_num;
1399 /* Force an order among the traversals, so they don't deadlock (as much) */
1400 static void make_traverse_depends(char *filename[],
1401 struct op *op[], unsigned int num_ops[],
1404 unsigned int i, num_traversals = 0;
1406 struct traverse_dep *dep;
1408 /* Sort by which one runs first. */
1409 int compare_traverse_dep(const void *_a, const void *_b)
1411 const struct traverse_dep *ta = _a, *tb = _b;
1412 const struct op *a = &op[ta->file][ta->op_num],
1413 *b = &op[tb->file][tb->op_num];
1415 if (a->serial != b->serial)
1416 return a->serial - b->serial;
1418 /* If they have same serial, it means one didn't make any
1419 * changes. Thus sort by end in that case. */
1420 return a[a->group_len].serial - b[b->group_len].serial;
1423 dep = talloc_array(NULL, struct traverse_dep, 1);
1426 for (i = 0; i < num; i++) {
1427 for (j = 1; j < num_ops[i]; j++) {
1428 /* Traverse start (ignore those in
1429 * transactions; they're already covered by
1430 * transaction dependencies). */
1431 if (starts_traverse(&op[i][j])
1432 && !in_transaction(op[i], j)) {
1433 dep = talloc_realloc(NULL, dep,
1434 struct traverse_dep,
1436 dep[num_traversals].file = i;
1437 dep[num_traversals].op_num = j;
1442 qsort(dep, num_traversals, sizeof(dep[0]), compare_traverse_dep);
1444 for (i = 1; i < num_traversals; i++) {
1445 const struct op *prev = &op[dep[i-1].file][dep[i-1].op_num];
1446 const struct op *curr = &op[dep[i].file][dep[i].op_num];
1448 /* Read traverses don't depend on each other (read lock). */
1449 if (prev->op == OP_TDB_TRAVERSE_READ_START
1450 && curr->op == OP_TDB_TRAVERSE_READ_START)
1453 /* Only make dependency if it's clear. */
1454 if (compare_traverse_dep(&dep[i], &dep[i-1])) {
1455 /* i depends on end of traverse i-1. */
1456 add_dependency(NULL, op, filename,
1457 dep[i].file, dep[i].op_num,
1458 dep[i-1].file, dep[i-1].op_num
1466 static void derive_dependencies(char *filename[],
1467 struct op *op[], unsigned int num_ops[],
1470 struct keyinfo *hash;
1473 /* Create hash table for faster key lookup. */
1474 hash = hash_ops(op, num_ops, num);
1476 /* Sort them by serial number. */
1477 sort_ops(hash, filename, op, num);
1479 /* Create dependencies back to the last change, rather than
1480 * creating false dependencies by naively making each one
1481 * depend on the previous. This has two purposes: it makes
1482 * later optimization simpler, and it also avoids deadlock with
1483 * same sequence number ops inside traversals (if one
1484 * traversal doesn't write anything, two ops can have the same
1485 * sequence number yet we can create a traversal dependency
1486 * the other way). */
1487 for (h = 0; h < total_keys * 2; h++) {
1490 if (hash[h].num_users < 2)
1493 for (i = 0; i < hash[h].num_users; i++) {
1494 if (changes_db(&hash[h].key, &op[hash[h].user[i].file]
1495 [hash[h].user[i].op_num])) {
1496 depend_on_previous(op, filename, num,
1497 hash[h].user, i, prev);
1499 } else if (prev >= 0)
1500 add_dependency(hash, op, filename,
1501 hash[h].user[i].file,
1502 hash[h].user[i].op_num,
1503 hash[h].user[prev].file,
1504 hash[h].user[prev].op_num);
1508 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
1509 make_traverse_depends(filename, op, num_ops, num);
1512 optimize_dependencies(op, num_ops, num);
1515 int main(int argc, char *argv[])
1517 struct timeval start, end;
1518 unsigned int i, num_ops[argc], hashsize[argc], tdb_flags[argc], open_flags[argc];
1519 struct op *op[argc];
1525 errx(1, "Usage: %s <tdbfile> <tracefile>...", argv[0]);
1527 pipes = talloc_array(NULL, struct pipe, argc - 2);
1528 for (i = 0; i < argc - 2; i++) {
1529 printf("Loading tracefile %s...", argv[2+i]);
1531 op[i] = load_tracefile(argv[2+i], &num_ops[i], &hashsize[i],
1532 &tdb_flags[i], &open_flags[i]);
1533 if (pipe(pipes[i].fd) != 0)
1534 err(1, "creating pipe");
1538 printf("Calculating inter-dependencies...");
1540 derive_dependencies(argv+2, op, num_ops, i);
1543 /* Don't fork for single arg case: simple debugging. */
1545 struct tdb_context *tdb;
1546 tdb = tdb_open_ex(argv[1], hashsize[0], tdb_flags[0]|TDB_NOSYNC,
1547 open_flags[0], 0600, NULL, hash_key);
1548 printf("Single threaded run...");
1551 run_ops(tdb, pipes[0].fd[0], argv+2, op, 0, 1, num_ops[0],
1553 check_deps(argv[2], op[0], num_ops[0]);
1560 err(1, "creating pipe");
1562 for (i = 0; i < argc - 2; i++) {
1563 struct tdb_context *tdb;
1567 err(1, "fork failed");
1570 tdb = tdb_open_ex(argv[1], hashsize[i],
1571 tdb_flags[i]|TDB_NOSYNC,
1572 open_flags[i], 0600, NULL, hash_key);
1574 err(1, "Opening tdb %s", argv[1]);
1576 /* This catches parent exiting. */
1577 if (read(fds[0], &c, 1) != 1)
1579 run_ops(tdb, pipes[i].fd[0], argv+2, op, i, 1,
1581 check_deps(argv[2+i], op[i], num_ops[i]);
1588 /* Let everything settle. */
1591 printf("Starting run...");
1593 gettimeofday(&start, NULL);
1594 /* Tell them all to go! Any write of sufficient length will do. */
1595 if (write(fds[1], hashsize, i) != i)
1596 err(1, "Writing to wakeup pipe");
1598 for (i = 0; i < argc - 2; i++) {
1601 if (!WIFEXITED(status)) {
1602 warnx("Child died with signal %i", WTERMSIG(status));
1604 } else if (WEXITSTATUS(status) != 0)
1605 /* Assume child spat out error. */
1611 gettimeofday(&end, NULL);
1614 end.tv_sec -= start.tv_sec;
1615 printf("Time replaying: %lu usec\n",
1616 end.tv_sec * 1000000UL + (end.tv_usec - start.tv_usec));