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 /* transaction/traverse start/chainlock */
151 unsigned int group_len;
155 static unsigned char hex_char(const char *filename, unsigned int line, char c)
158 if (c >= 'A' && c <= 'F')
160 if (c >= '0' && c <= '9')
162 fail(filename, line, "invalid hex character '%c'", c);
165 /* TDB data is <size>:<%02x>* */
166 static TDB_DATA make_tdb_data(const void *ctx,
167 const char *filename, unsigned int line,
174 if (streq(word, "NULL"))
177 data.dsize = atoi(word);
178 data.dptr = talloc_array(ctx, unsigned char, data.dsize);
179 p = strchr(word, ':');
181 fail(filename, line, "invalid tdb data '%s'", word);
183 for (i = 0; i < data.dsize; i++)
184 data.dptr[i] = hex_char(filename, line, p[i*2])*16
185 + hex_char(filename, line, p[i*2+1]);
190 static void add_op(const char *filename, struct op **op, unsigned int i,
191 unsigned int serial, enum op_type type)
194 *op = talloc_realloc(NULL, *op, struct op, i+1);
197 new->serial = serial;
199 new->group_start = 0;
202 static void op_add_nothing(const char *filename,
203 struct op op[], unsigned int op_num, char *words[])
206 fail(filename, op_num+1, "Expected no arguments");
207 op[op_num].key = tdb_null;
210 static void op_add_key(const char *filename,
211 struct op op[], unsigned int op_num, char *words[])
213 if (words[2] == NULL || words[3])
214 fail(filename, op_num+1, "Expected just a key");
216 op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
220 static void op_add_key_ret(const char *filename,
221 struct op op[], unsigned int op_num, char *words[])
223 if (!words[2] || !words[3] || !words[4] || words[5]
224 || !streq(words[3], "="))
225 fail(filename, op_num+1, "Expected <key> = <ret>");
226 op[op_num].ret = atoi(words[4]);
227 op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
228 /* May only be a unique key if it fails */
229 if (op[op_num].ret != 0)
233 static void op_add_key_data(const char *filename,
234 struct op op[], unsigned int op_num, char *words[])
236 if (!words[2] || !words[3] || !words[4] || words[5]
237 || !streq(words[3], "="))
238 fail(filename, op_num+1, "Expected <key> = <data>");
239 op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
240 op[op_num].data = make_tdb_data(op, filename, op_num+1, words[4]);
241 /* May only be a unique key if it fails */
242 if (!op[op_num].data.dptr)
246 /* We don't record the keys or data for a traverse, as we don't use them. */
247 static void op_add_traverse(const char *filename,
248 struct op op[], unsigned int op_num, char *words[])
250 if (!words[2] || !words[3] || !words[4] || words[5]
251 || !streq(words[3], "="))
252 fail(filename, op_num+1, "Expected <key> = <data>");
253 op[op_num].key = tdb_null;
256 /* Full traverse info is useful for debugging, but changing it to
257 * "traversefn" without the data makes the traces *much* smaller! */
258 static void op_add_traversefn(const char *filename,
259 struct op op[], unsigned int op_num, char *words[])
262 fail(filename, op_num+1, "Expected no values");
263 op[op_num].key = tdb_null;
266 /* <serial> tdb_store <rec> <rec> <flag> = <ret> */
267 static void op_add_store(const char *filename,
268 struct op op[], unsigned int op_num, char *words[])
270 if (!words[2] || !words[3] || !words[4] || !words[5] || !words[6]
271 || words[7] || !streq(words[5], "="))
272 fail(filename, op_num+1, "Expect <key> <data> <flag> = <ret>");
274 op[op_num].flag = strtoul(words[4], NULL, 0);
275 op[op_num].ret = atoi(words[6]);
276 op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
277 op[op_num].data = make_tdb_data(op, filename, op_num+1, words[3]);
281 /* <serial> tdb_append <rec> <rec> = <rec> */
282 static void op_add_append(const char *filename,
283 struct op op[], unsigned int op_num, char *words[])
285 if (!words[2] || !words[3] || !words[4] || !words[5] || words[6]
286 || !streq(words[4], "="))
287 fail(filename, op_num+1, "Expect <key> <data> = <rec>");
289 op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
290 op[op_num].data = make_tdb_data(op, filename, op_num+1, words[3]);
292 op[op_num].append.post
293 = make_tdb_data(op, filename, op_num+1, words[5]);
295 /* By subtraction, figure out what previous data was. */
296 op[op_num].append.pre.dptr = op[op_num].append.post.dptr;
297 op[op_num].append.pre.dsize
298 = op[op_num].append.post.dsize - op[op_num].data.dsize;
302 /* <serial> tdb_get_seqnum = <ret> */
303 static void op_add_seqnum(const char *filename,
304 struct op op[], unsigned int op_num, char *words[])
306 if (!words[2] || !words[3] || words[4] || !streq(words[2], "="))
307 fail(filename, op_num+1, "Expect = <ret>");
309 op[op_num].key = tdb_null;
310 op[op_num].ret = atoi(words[3]);
313 static void op_add_traverse_start(const char *filename,
315 unsigned int op_num, char *words[])
318 fail(filename, op_num+1, "Expect no arguments");
320 op[op_num].key = tdb_null;
321 op[op_num].group_len = 0;
324 static void op_add_transaction(const char *filename, struct op op[],
325 unsigned int op_num, char *words[])
328 fail(filename, op_num+1, "Expect no arguments");
330 op[op_num].key = tdb_null;
331 op[op_num].group_len = 0;
334 static void op_add_chainlock(const char *filename,
335 struct op op[], unsigned int op_num, char *words[])
337 if (words[2] == NULL || words[3])
338 fail(filename, op_num+1, "Expected just a key");
340 /* A chainlock key isn't a key in the normal sense; it doesn't
341 * have to be in the db at all. Also, we don't want to hash this op. */
342 op[op_num].data = make_tdb_data(op, filename, op_num+1, words[2]);
343 op[op_num].key = tdb_null;
344 op[op_num].group_len = 0;
347 static void op_add_chainlock_ret(const char *filename,
348 struct op op[], unsigned int op_num,
351 if (!words[2] || !words[3] || !words[4] || words[5]
352 || !streq(words[3], "="))
353 fail(filename, op_num+1, "Expected <key> = <ret>");
354 op[op_num].ret = atoi(words[4]);
355 op[op_num].data = make_tdb_data(op, filename, op_num+1, words[2]);
356 op[op_num].key = tdb_null;
357 op[op_num].group_len = 0;
361 static int op_find_start(struct op op[], unsigned int op_num, enum op_type type)
365 for (i = op_num-1; i > 0; i--) {
366 if (op[i].op == type && !op[i].group_len)
372 static void op_analyze_transaction(const char *filename,
373 struct op op[], unsigned int op_num,
376 unsigned int start, i;
378 op[op_num].key = tdb_null;
381 fail(filename, op_num+1, "Expect no arguments");
383 start = op_find_start(op, op_num, OP_TDB_TRANSACTION_START);
385 fail(filename, op_num+1, "no transaction start found");
387 op[start].group_len = op_num - start;
389 /* This rolls in nested transactions. I think that's right. */
390 for (i = start; i <= op_num; i++)
391 op[i].group_start = start;
394 /* We treat chainlocks a lot like transactions, even though that's overkill */
395 static void op_analyze_chainlock(const char *filename,
396 struct op op[], unsigned int op_num,
399 unsigned int i, start;
401 if (words[2] == NULL || words[3])
402 fail(filename, op_num+1, "Expected just a key");
404 op[op_num].data = make_tdb_data(op, filename, op_num+1, words[2]);
405 op[op_num].key = tdb_null;
408 start = op_find_start(op, op_num, OP_TDB_CHAINLOCK);
410 start = op_find_start(op, op_num, OP_TDB_CHAINLOCK_READ);
412 fail(filename, op_num+1, "no initial chainlock found");
414 /* FIXME: We'd have to do something clever to make this work
416 if (!key_eq(op[start].data, op[op_num].data))
417 fail(filename, op_num+1, "nested chainlock calls?");
419 op[start].group_len = op_num - start;
420 for (i = start; i <= op_num; i++)
421 op[i].group_start = start;
424 static void op_analyze_traverse(const char *filename,
425 struct op op[], unsigned int op_num,
430 op[op_num].key = tdb_null;
432 /* = %u means traverse function terminated. */
434 if (!streq(words[2], "=") || !words[3] || words[4])
435 fail(filename, op_num+1, "expect = <num>");
436 op[op_num].ret = atoi(words[3]);
440 start = op_find_start(op, op_num, OP_TDB_TRAVERSE_START);
442 start = op_find_start(op, op_num, OP_TDB_TRAVERSE_READ_START);
444 fail(filename, op_num+1, "no traversal start found");
446 op[start].group_len = op_num - start;
448 /* Don't roll in nested traverse/chainlock */
449 for (i = start; i <= op_num; i++)
450 if (!op[i].group_start)
451 op[i].group_start = start;
454 /* Keep -Wmissing-declarations happy: */
455 const struct op_table *
456 find_keyword (register const char *str, register unsigned int len);
458 #include "keywords.c"
461 /* We can have more than one */
462 struct list_node pre_list;
463 struct list_node post_list;
464 unsigned int needs_file;
465 unsigned int needs_opnum;
466 unsigned int satisfies_file;
467 unsigned int satisfies_opnum;
470 static void check_deps(const char *filename, struct op op[], unsigned int num)
475 for (i = 1; i < num; i++)
476 if (!list_empty(&op[i].pre))
477 fail(filename, i+1, "Still has dependencies");
481 static void dump_pre(char *filename[], struct op *op[],
482 unsigned int file, unsigned int i)
486 printf("%s:%u (%u) still waiting for:\n", filename[file], i+1,
488 list_for_each(&op[file][i].pre, dep, pre_list)
489 printf(" %s:%u (%u)\n",
490 filename[dep->satisfies_file], dep->satisfies_opnum+1,
491 op[dep->satisfies_file][dep->satisfies_opnum].serial);
492 check_deps(filename[file], op[file], i);
495 /* We simply read/write pointers, since we all are children. */
496 static bool do_pre(struct tdb_context *tdb,
497 char *filename[], struct op *op[],
498 unsigned int file, int pre_fd, unsigned int i,
501 while (!list_empty(&op[file][i].pre)) {
505 printf("%s:%u:waiting for pre\n", filename[file], i+1);
512 while (read(pre_fd, &dep, sizeof(dep)) != sizeof(dep)) {
513 if (errno == EINTR) {
515 warnx("%s:%u:avoiding deadlock",
516 filename[file], i+1);
519 dump_pre(filename, op, file, i);
522 errx(1, "Reading from pipe");
527 printf("%s:%u:got pre %u from %s:%u\n", filename[file], i+1,
528 dep->needs_opnum+1, filename[dep->satisfies_file],
529 dep->satisfies_opnum+1);
532 /* This could be any op, not just this one. */
538 static void do_post(char *filename[], struct op *op[],
539 unsigned int file, unsigned int i)
543 list_for_each(&op[file][i].post, dep, post_list) {
545 printf("%s:%u:sending to file %s:%u\n", filename[file], i+1,
546 filename[dep->needs_file], dep->needs_opnum+1);
548 if (write(pipes[dep->needs_file].fd[1], &dep, sizeof(dep))
550 err(1, "%s:%u failed to tell file %s",
551 filename[file], i+1, filename[dep->needs_file]);
555 static int get_len(TDB_DATA key, TDB_DATA data, void *private_data)
560 static unsigned run_ops(struct tdb_context *tdb,
565 unsigned int start, unsigned int stop,
568 struct traverse_info {
577 /* More complex. Just do whatever's they did at the n'th entry. */
578 static int nontrivial_traverse(struct tdb_context *tdb,
579 TDB_DATA key, TDB_DATA data,
582 struct traverse_info *tinfo = _tinfo;
583 unsigned int trav_len = tinfo->op[tinfo->file][tinfo->start].group_len;
584 bool avoid_deadlock = false;
586 if (tinfo->i == tinfo->start + trav_len) {
587 /* This can happen if traverse expects to be empty. */
590 fail(tinfo->filename[tinfo->file], tinfo->start + 1,
591 "traverse did not terminate");
594 if (tinfo->op[tinfo->file][tinfo->i].op != OP_TDB_TRAVERSE)
595 fail(tinfo->filename[tinfo->file], tinfo->start + 1,
596 "%s:%u:traverse terminated early");
598 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
599 avoid_deadlock = true;
602 /* Run any normal ops. */
603 tinfo->i = run_ops(tdb, tinfo->pre_fd, tinfo->filename, tinfo->op,
604 tinfo->file, tinfo->i+1, tinfo->start + trav_len,
607 /* We backed off, or we hit OP_TDB_TRAVERSE_END. */
608 if (tinfo->op[tinfo->file][tinfo->i].op != OP_TDB_TRAVERSE)
614 static unsigned op_traverse(struct tdb_context *tdb,
618 int (*traversefn)(struct tdb_context *,
619 tdb_traverse_func, void *),
623 struct traverse_info tinfo = { op, filename, file, pre_fd,
626 traversefn(tdb, nontrivial_traverse, &tinfo);
628 /* Traversing in wrong order can have strange effects: eg. if
629 * original traverse went A (delete A), B, we might do B
630 * (delete A). So if we have ops left over, we do it now. */
631 while (tinfo.i != start + op[file][start].group_len) {
632 if (op[file][tinfo.i].op == OP_TDB_TRAVERSE)
635 tinfo.i = run_ops(tdb, pre_fd, filename, op, file,
637 start + op[file][start].group_len,
644 static void break_out(int sig)
648 static __attribute__((noinline))
649 unsigned run_ops(struct tdb_context *tdb,
654 unsigned int start, unsigned int stop,
660 sa.sa_handler = break_out;
663 sigaction(SIGALRM, &sa, NULL);
664 for (i = start; i < stop; i++) {
665 if (!do_pre(tdb, filename, op, file, pre_fd, i, backoff))
668 switch (op[file][i].op) {
670 try(tdb_lockall(tdb), op[file][i].ret);
672 case OP_TDB_LOCKALL_MARK:
673 try(tdb_lockall_mark(tdb), op[file][i].ret);
675 case OP_TDB_LOCKALL_UNMARK:
676 try(tdb_lockall_unmark(tdb), op[file][i].ret);
678 case OP_TDB_LOCKALL_NONBLOCK:
679 unreliable(tdb_lockall_nonblock(tdb), op[file][i].ret,
680 tdb_lockall(tdb), tdb_unlockall(tdb));
682 case OP_TDB_UNLOCKALL:
683 try(tdb_unlockall(tdb), op[file][i].ret);
685 case OP_TDB_LOCKALL_READ:
686 try(tdb_lockall_read(tdb), op[file][i].ret);
688 case OP_TDB_LOCKALL_READ_NONBLOCK:
689 unreliable(tdb_lockall_read_nonblock(tdb),
691 tdb_lockall_read(tdb),
692 tdb_unlockall_read(tdb));
694 case OP_TDB_UNLOCKALL_READ:
695 try(tdb_unlockall_read(tdb), op[file][i].ret);
697 case OP_TDB_CHAINLOCK:
698 try(tdb_chainlock(tdb, op[file][i].key),
701 case OP_TDB_CHAINLOCK_NONBLOCK:
702 unreliable(tdb_chainlock_nonblock(tdb, op[file][i].key),
704 tdb_chainlock(tdb, op[file][i].key),
705 tdb_chainunlock(tdb, op[file][i].key));
707 case OP_TDB_CHAINLOCK_MARK:
708 try(tdb_chainlock_mark(tdb, op[file][i].key),
711 case OP_TDB_CHAINLOCK_UNMARK:
712 try(tdb_chainlock_unmark(tdb, op[file][i].key),
715 case OP_TDB_CHAINUNLOCK:
716 try(tdb_chainunlock(tdb, op[file][i].key),
719 case OP_TDB_CHAINLOCK_READ:
720 try(tdb_chainlock_read(tdb, op[file][i].key),
723 case OP_TDB_CHAINUNLOCK_READ:
724 try(tdb_chainunlock_read(tdb, op[file][i].key),
727 case OP_TDB_PARSE_RECORD:
728 try(tdb_parse_record(tdb, op[file][i].key, get_len,
733 try(tdb_exists(tdb, op[file][i].key), op[file][i].ret);
736 try(tdb_store(tdb, op[file][i].key, op[file][i].data,
741 try(tdb_append(tdb, op[file][i].key, op[file][i].data),
744 case OP_TDB_GET_SEQNUM:
745 try(tdb_get_seqnum(tdb), op[file][i].ret);
747 case OP_TDB_WIPE_ALL:
748 try(tdb_wipe_all(tdb), op[file][i].ret);
750 case OP_TDB_TRANSACTION_START:
751 try(tdb_transaction_start(tdb), op[file][i].ret);
753 case OP_TDB_TRANSACTION_CANCEL:
754 try(tdb_transaction_cancel(tdb), op[file][i].ret);
756 case OP_TDB_TRANSACTION_COMMIT:
757 try(tdb_transaction_commit(tdb), op[file][i].ret);
759 case OP_TDB_TRAVERSE_READ_START:
760 i = op_traverse(tdb, pre_fd, filename, file,
761 tdb_traverse_read, op, i);
763 case OP_TDB_TRAVERSE_START:
764 i = op_traverse(tdb, pre_fd, filename, file,
765 tdb_traverse, op, i);
767 case OP_TDB_TRAVERSE:
768 /* Terminate: we're in a traverse, and we've
771 case OP_TDB_TRAVERSE_END:
772 fail(filename[file], i+1, "unexpected end traverse");
773 /* FIXME: These must be treated like traverse. */
774 case OP_TDB_FIRSTKEY:
775 if (!key_eq(tdb_firstkey(tdb), op[file][i].data))
776 fail(filename[file], i+1, "bad firstkey");
779 if (!key_eq(tdb_nextkey(tdb, op[file][i].key),
781 fail(filename[file], i+1, "bad nextkey");
784 TDB_DATA f = tdb_fetch(tdb, op[file][i].key);
785 if (!key_eq(f, op[file][i].data))
786 fail(filename[file], i+1, "bad fetch %u",
791 try(tdb_delete(tdb, op[file][i].key), op[file][i].ret);
794 do_post(filename, op, file, i);
799 /* tdbtorture, in particular, can do a tdb_close with a transaction in
801 static struct op *maybe_cancel_transaction(const char *filename,
802 struct op *op, unsigned int *num)
804 unsigned int start = op_find_start(op, *num, OP_TDB_TRANSACTION_START);
807 char *words[] = { "<unknown>", "tdb_close", NULL };
808 add_op(filename, &op, *num, op[start].serial,
809 OP_TDB_TRANSACTION_CANCEL);
810 op_analyze_transaction(filename, op, *num, words);
816 static struct op *load_tracefile(const char *filename, unsigned int *num,
817 unsigned int *hashsize,
818 unsigned int *tdb_flags,
819 unsigned int *open_flags)
822 struct op *op = talloc_array(NULL, struct op, 1);
827 file = grab_file(NULL, filename, NULL);
829 err(1, "Reading %s", filename);
831 lines = strsplit(file, file, "\n", NULL);
833 errx(1, "%s is empty", filename);
835 words = strsplit(lines, lines[0], " ", NULL);
836 if (!streq(words[1], "tdb_open"))
837 fail(filename, 1, "does not start with tdb_open");
839 *hashsize = atoi(words[2]);
840 *tdb_flags = strtoul(words[3], NULL, 0);
841 *open_flags = strtoul(words[4], NULL, 0);
843 for (i = 1; lines[i]; i++) {
844 const struct op_table *opt;
846 words = strsplit(lines, lines[i], " ", NULL);
847 if (!words[0] || !words[1])
848 fail(filename, i+1, "Expected serial number and op");
850 opt = find_keyword(words[1], strlen(words[1]));
852 if (streq(words[1], "tdb_close")) {
855 "lines after tdb_close");
858 return maybe_cancel_transaction(filename,
861 fail(filename, i+1, "Unknown operation '%s'", words[1]);
864 add_op(filename, &op, i, atoi(words[0]), opt->type);
865 opt->enhance_op(filename, op, i, words);
868 fprintf(stderr, "%s:%u:last operation is not tdb_close: incomplete?",
872 return maybe_cancel_transaction(filename, op, num);
875 /* We remember all the keys we've ever seen, and who has them. */
883 unsigned int num_users;
884 struct key_user *user;
887 static const TDB_DATA must_not_exist;
888 static const TDB_DATA must_exist;
889 static const TDB_DATA not_exists_or_empty;
891 /* NULL means doesn't care if it exists or not, &must_exist means
892 * it must exist but we don't care what, &must_not_exist means it must
893 * not exist, otherwise the data it needs. */
894 static const TDB_DATA *needs(const struct op *op)
897 /* FIXME: Pull forward deps, since we can deadlock */
898 case OP_TDB_CHAINLOCK:
899 case OP_TDB_CHAINLOCK_NONBLOCK:
900 case OP_TDB_CHAINLOCK_MARK:
901 case OP_TDB_CHAINLOCK_UNMARK:
902 case OP_TDB_CHAINUNLOCK:
903 case OP_TDB_CHAINLOCK_READ:
904 case OP_TDB_CHAINUNLOCK_READ:
908 if (op->append.pre.dsize == 0)
909 return ¬_exists_or_empty;
910 return &op->append.pre;
913 if (op->flag == TDB_INSERT) {
917 return &must_not_exist;
918 } else if (op->flag == TDB_MODIFY) {
920 return &must_not_exist;
924 /* No flags? Don't care */
931 return &must_not_exist;
933 case OP_TDB_PARSE_RECORD:
935 return &must_not_exist;
938 /* FIXME: handle these. */
939 case OP_TDB_WIPE_ALL:
940 case OP_TDB_FIRSTKEY:
942 case OP_TDB_GET_SEQNUM:
943 case OP_TDB_TRAVERSE:
944 case OP_TDB_TRANSACTION_COMMIT:
945 case OP_TDB_TRANSACTION_CANCEL:
946 case OP_TDB_TRANSACTION_START:
951 return &must_not_exist;
956 return &must_not_exist;
960 errx(1, "Unexpected op %i", op->op);
965 static bool starts_transaction(const struct op *op)
967 return op->op == OP_TDB_TRANSACTION_START;
970 static bool in_transaction(const struct op op[], unsigned int i)
972 return op[i].group_start && starts_transaction(&op[op[i].group_start]);
975 static bool successful_transaction(const struct op *op)
977 return starts_transaction(op)
978 && op[op->group_len].op == OP_TDB_TRANSACTION_COMMIT;
981 static bool starts_traverse(const struct op *op)
983 return op->op == OP_TDB_TRAVERSE_START
984 || op->op == OP_TDB_TRAVERSE_READ_START;
987 static bool in_traverse(const struct op op[], unsigned int i)
989 return op[i].group_start && starts_traverse(&op[op[i].group_start]);
992 static bool starts_chainlock(const struct op *op)
994 return op->op == OP_TDB_CHAINLOCK_READ || op->op == OP_TDB_CHAINLOCK;
997 static bool in_chainlock(const struct op op[], unsigned int i)
999 return op[i].group_start && starts_chainlock(&op[op[i].group_start]);
1002 /* What's the data after this op? pre if nothing changed. */
1003 static const TDB_DATA *gives(const TDB_DATA *key, const TDB_DATA *pre,
1004 const struct op *op)
1006 if (starts_transaction(op) || starts_chainlock(op)) {
1009 /* Cancelled transactions don't change anything. */
1010 if (op[op->group_len].op == OP_TDB_TRANSACTION_CANCEL)
1012 assert(op[op->group_len].op == OP_TDB_TRANSACTION_COMMIT
1013 || op[op->group_len].op == OP_TDB_CHAINUNLOCK_READ
1014 || op[op->group_len].op == OP_TDB_CHAINUNLOCK);
1016 for (i = 1; i < op->group_len; i++) {
1017 /* This skips nested transactions, too */
1018 if (key_eq(op[i].key, *key))
1019 pre = gives(key, pre, &op[i]);
1024 /* Failed ops don't change state of db. */
1028 if (op->op == OP_TDB_DELETE || op->op == OP_TDB_WIPE_ALL)
1031 if (op->op == OP_TDB_APPEND)
1032 return &op->append.post;
1034 if (op->op == OP_TDB_STORE)
1040 static struct keyinfo *hash_ops(struct op *op[], unsigned int num_ops[],
1043 unsigned int i, j, h;
1044 struct keyinfo *hash;
1046 hash = talloc_zero_array(op[0], struct keyinfo, total_keys*2);
1047 for (i = 0; i < num; i++) {
1048 for (j = 1; j < num_ops[i]; j++) {
1049 /* We can't do this on allocation, due to realloc. */
1050 list_head_init(&op[i][j].post);
1051 list_head_init(&op[i][j].pre);
1053 if (!op[i][j].key.dptr)
1056 h = hash_key(&op[i][j].key) % (total_keys * 2);
1057 while (!key_eq(hash[h].key, op[i][j].key)) {
1058 if (!hash[h].key.dptr) {
1059 hash[h].key = op[i][j].key;
1062 h = (h + 1) % (total_keys * 2);
1064 /* Might as well save some memory if we can. */
1065 if (op[i][j].key.dptr != hash[h].key.dptr) {
1066 talloc_free(op[i][j].key.dptr);
1067 op[i][j].key.dptr = hash[h].key.dptr;
1069 hash[h].user = talloc_realloc(hash, hash[h].user,
1071 hash[h].num_users+1);
1073 /* If it's in a transaction, it's the transaction which
1074 * matters from an analysis POV. */
1075 if (in_transaction(op[i], j)
1076 || in_chainlock(op[i], j)) {
1077 unsigned start = op[i][j].group_start;
1079 /* Don't include twice. */
1080 if (hash[h].num_users
1081 && hash[h].user[hash[h].num_users-1].file
1083 && hash[h].user[hash[h].num_users-1].op_num
1087 hash[h].user[hash[h].num_users].op_num = start;
1089 hash[h].user[hash[h].num_users].op_num = j;
1090 hash[h].user[hash[h].num_users].file = i;
1091 hash[h].num_users++;
1098 static bool satisfies(const TDB_DATA *key, const TDB_DATA *data,
1099 const struct op *op)
1101 const TDB_DATA *need = NULL;
1103 if (starts_transaction(op) || starts_chainlock(op)) {
1106 /* Look through for an op in this transaction which
1107 * needs this key. */
1108 for (i = 1; i < op->group_len; i++) {
1109 if (key_eq(op[i].key, *key)) {
1110 need = needs(&op[i]);
1111 /* tdb_exists() is special: there might be
1112 * something in the transaction with more
1113 * specific requirements. Other ops don't have
1114 * specific requirements (eg. store or delete),
1115 * but they change the value so we can't get
1116 * more information from future ops. */
1117 if (op[i].op != OP_TDB_EXISTS)
1124 /* Don't need anything? Cool. */
1128 /* This should be tdb_null or a real value. */
1129 assert(data != &must_exist);
1130 assert(data != &must_not_exist);
1131 assert(data != ¬_exists_or_empty);
1133 /* Must not exist? data must not exist. */
1134 if (need == &must_not_exist)
1135 return data == &tdb_null;
1138 if (need == &must_exist)
1139 return data != &tdb_null;
1141 /* Either noexist or empty. */
1142 if (need == ¬_exists_or_empty)
1143 return data->dsize == 0;
1145 /* Needs something specific. */
1146 return key_eq(*data, *need);
1149 static void move_to_front(struct key_user res[], unsigned off, unsigned elem)
1152 struct key_user tmp = res[elem];
1153 memmove(res + off + 1, res + off, (elem - off)*sizeof(res[0]));
1158 static void restore_to_pos(struct key_user res[], unsigned off, unsigned elem)
1161 struct key_user tmp = res[off];
1162 memmove(res + off, res + off + 1, (elem - off)*sizeof(res[0]));
1167 static bool sort_deps(char *filename[], struct op *op[],
1168 struct key_user res[],
1169 unsigned off, unsigned num,
1170 const TDB_DATA *key, const TDB_DATA *data,
1171 unsigned num_files, unsigned fuzz)
1173 unsigned int i, files_done;
1175 bool done[num_files];
1177 /* None left? We're sorted. */
1181 /* Does this make serial numbers go backwards? Allow a little fuzz. */
1183 int serial1 = op[res[off-1].file][res[off-1].op_num].serial;
1184 int serial2 = op[res[off].file][res[off].op_num].serial;
1186 if (serial1 - serial2 > (int)fuzz) {
1188 printf("Serial jump too far (%u -> %u)\n",
1195 memset(done, 0, sizeof(done));
1197 /* Since ops within a trace file are ordered, we just need to figure
1198 * out which file to try next. Since we don't take into account
1199 * inter-key relationships (which exist by virtue of trace file order),
1200 * we minimize the chance of harm by trying to keep in serial order. */
1201 for (files_done = 0, i = off; i < num && files_done < num_files; i++) {
1202 if (done[res[i].file])
1205 this_op = &op[res[i].file][res[i].op_num];
1207 /* Is what we have good enough for this op? */
1208 if (satisfies(key, data, this_op)) {
1209 move_to_front(res, off, i);
1210 if (sort_deps(filename, op, res, off+1, num,
1211 key, gives(key, data, this_op),
1214 restore_to_pos(res, off, i);
1216 done[res[i].file] = true;
1220 /* No combination worked. */
1224 static void check_dep_sorting(struct key_user user[], unsigned num_users,
1229 unsigned minima[num_files];
1231 memset(minima, 0, sizeof(minima));
1232 for (i = 0; i < num_users; i++) {
1233 assert(minima[user[i].file] < user[i].op_num);
1234 minima[user[i].file] = user[i].op_num;
1239 /* All these ops happen on the same key. Which comes first?
1241 * This can happen both because read ops or failed write ops don't
1242 * change serial number, and also due to race since we access the
1243 * number unlocked (the race can cause less detectable ordering problems,
1244 * in which case we'll deadlock and report: fix manually in that case).
1246 static void figure_deps(char *filename[], struct op *op[],
1247 const TDB_DATA *key, struct key_user user[],
1248 unsigned num_users, unsigned num_files)
1250 /* We assume database starts empty. */
1251 const struct TDB_DATA *data = &tdb_null;
1254 /* We prefer to keep strict serial order if possible: it's the
1255 * most likely. We get more lax if that fails. */
1256 for (fuzz = 0; fuzz < 100; fuzz = (fuzz + 1)*2) {
1257 if (sort_deps(filename, op, user, 0, num_users, key, data,
1263 fail(filename[user[0].file], user[0].op_num+1,
1264 "Could not resolve inter-dependencies");
1266 check_dep_sorting(user, num_users, num_files);
1269 static void sort_ops(struct keyinfo hash[], char *filename[], struct op *op[],
1274 /* Gcc nexted function extension. How cool is this? */
1275 int compare_serial(const void *_a, const void *_b)
1277 const struct key_user *a = _a, *b = _b;
1279 /* First, maintain order within any trace file. */
1280 if (a->file == b->file)
1281 return a->op_num - b->op_num;
1283 /* Otherwise, arrange by serial order. */
1284 if (op[a->file][a->op_num].serial !=
1285 op[b->file][b->op_num].serial)
1286 return op[a->file][a->op_num].serial
1287 - op[b->file][b->op_num].serial;
1289 /* Cancelled transactions are assumed to happen first. */
1290 if (starts_transaction(&op[a->file][a->op_num])
1291 && !successful_transaction(&op[a->file][a->op_num]))
1293 if (starts_transaction(&op[b->file][b->op_num])
1294 && !successful_transaction(&op[b->file][b->op_num]))
1301 /* Now sort into serial order. */
1302 for (h = 0; h < total_keys * 2; h++) {
1303 struct key_user *user = hash[h].user;
1305 qsort(user, hash[h].num_users, sizeof(user[0]), compare_serial);
1306 figure_deps(filename, op, &hash[h].key, user, hash[h].num_users,
1311 static int destroy_depend(struct depend *dep)
1313 list_del(&dep->pre_list);
1314 list_del(&dep->post_list);
1318 static void add_dependency(void *ctx,
1321 unsigned int needs_file,
1322 unsigned int needs_opnum,
1323 unsigned int satisfies_file,
1324 unsigned int satisfies_opnum)
1328 /* We don't depend on ourselves. */
1329 if (needs_file == satisfies_file) {
1330 assert(satisfies_opnum < needs_opnum);
1335 printf("%s:%u: depends on %s:%u\n",
1336 filename[needs_file], needs_opnum+1,
1337 filename[satisfies_file], satisfies_opnum+1);
1340 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
1341 /* If something in a traverse depends on something in another
1342 * traverse/transaction, it creates a dependency between the
1344 if ((in_traverse(op[satisfies_file], satisfies_opnum)
1345 && (starts_transaction(&op[needs_file][needs_opnum])
1346 || starts_traverse(&op[needs_file][needs_opnum])))
1347 || (in_traverse(op[needs_file], needs_opnum)
1348 && (starts_transaction(&op[satisfies_file][satisfies_opnum])
1349 || starts_traverse(&op[satisfies_file][satisfies_opnum])))){
1352 /* We are satisfied by end of group. */
1353 sat = op[satisfies_file][satisfies_opnum].group_start;
1354 satisfies_opnum = sat + op[satisfies_file][sat].group_len;
1355 /* And we need that done by start of our group. */
1356 needs_opnum = op[needs_file][needs_opnum].group_start;
1359 /* There is also this case:
1360 * <traverse> <read foo> ...
1361 * <transaction> ... </transaction> <create foo>
1362 * Where if we start the traverse then wait, we could block
1363 * the transaction and deadlock.
1365 * We try to address this by ensuring that where seqnum indicates it's
1366 * possible, we wait for <create foo> before *starting* traverse.
1368 else if (in_traverse(op[needs_file], needs_opnum)) {
1369 struct op *need = &op[needs_file][needs_opnum];
1370 if (op[needs_file][need->group_start].serial >
1371 op[satisfies_file][satisfies_opnum].serial) {
1372 needs_opnum = need->group_start;
1377 /* If you depend on a transaction or chainlock, you actually
1378 * depend on it ending. */
1379 if (starts_transaction(&op[satisfies_file][satisfies_opnum])
1380 || starts_chainlock(&op[satisfies_file][satisfies_opnum])) {
1382 += op[satisfies_file][satisfies_opnum].group_len;
1384 printf("-> Actually end of transaction %s:%u\n",
1385 filename[satisfies_file], satisfies_opnum+1);
1388 /* We should never create a dependency from middle of
1390 assert(!in_transaction(op[satisfies_file], satisfies_opnum)
1391 || op[satisfies_file][satisfies_opnum].op
1392 == OP_TDB_TRANSACTION_COMMIT
1393 || op[satisfies_file][satisfies_opnum].op
1394 == OP_TDB_TRANSACTION_CANCEL);
1396 assert(op[needs_file][needs_opnum].op != OP_TDB_TRAVERSE);
1397 assert(op[satisfies_file][satisfies_opnum].op != OP_TDB_TRAVERSE);
1399 dep = talloc(ctx, struct depend);
1400 dep->needs_file = needs_file;
1401 dep->needs_opnum = needs_opnum;
1402 dep->satisfies_file = satisfies_file;
1403 dep->satisfies_opnum = satisfies_opnum;
1404 list_add(&op[satisfies_file][satisfies_opnum].post, &dep->post_list);
1405 list_add(&op[needs_file][needs_opnum].pre, &dep->pre_list);
1406 talloc_set_destructor(dep, destroy_depend);
1409 static bool changes_db(const TDB_DATA *key, const struct op *op)
1411 return gives(key, NULL, op) != NULL;
1414 static void depend_on_previous(struct op *op[],
1417 struct key_user user[],
1427 if (prev == i - 1) {
1428 /* Just depend on previous. */
1429 add_dependency(NULL, op, filename,
1430 user[i].file, user[i].op_num,
1431 user[prev].file, user[prev].op_num);
1435 /* We have to wait for the readers. Find last one in *each* file. */
1436 memset(deps, 0, sizeof(deps));
1437 deps[user[i].file] = true;
1438 for (j = i - 1; j > prev; j--) {
1439 if (!deps[user[j].file]) {
1440 add_dependency(NULL, op, filename,
1441 user[i].file, user[i].op_num,
1442 user[j].file, user[j].op_num);
1443 deps[user[j].file] = true;
1448 /* This is simple, but not complete. We don't take into account
1449 * indirect dependencies. */
1450 static void optimize_dependencies(struct op *op[], unsigned int num_ops[],
1455 /* There can only be one real dependency on each file */
1456 for (i = 0; i < num; i++) {
1457 for (j = 1; j < num_ops[i]; j++) {
1458 struct depend *dep, *next;
1459 struct depend *prev[num];
1461 memset(prev, 0, sizeof(prev));
1463 list_for_each_safe(&op[i][j].pre, dep, next, pre_list) {
1464 if (!prev[dep->satisfies_file]) {
1465 prev[dep->satisfies_file] = dep;
1468 if (prev[dep->satisfies_file]->satisfies_opnum
1469 < dep->satisfies_opnum) {
1470 talloc_free(prev[dep->satisfies_file]);
1471 prev[dep->satisfies_file] = dep;
1478 for (i = 0; i < num; i++) {
1481 for (j = 0; j < num; j++)
1484 for (j = 1; j < num_ops[i]; j++) {
1485 struct depend *dep, *next;
1487 list_for_each_safe(&op[i][j].pre, dep, next, pre_list) {
1488 if (deps[dep->satisfies_file]
1489 >= (int)dep->satisfies_opnum)
1492 deps[dep->satisfies_file]
1493 = dep->satisfies_opnum;
1499 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
1500 struct traverse_dep {
1502 unsigned int op_num;
1505 /* Force an order among the traversals, so they don't deadlock (as much) */
1506 static void make_traverse_depends(char *filename[],
1507 struct op *op[], unsigned int num_ops[],
1510 unsigned int i, num_traversals = 0;
1512 struct traverse_dep *dep;
1514 /* Sort by which one runs first. */
1515 int compare_traverse_dep(const void *_a, const void *_b)
1517 const struct traverse_dep *ta = _a, *tb = _b;
1518 const struct op *a = &op[ta->file][ta->op_num],
1519 *b = &op[tb->file][tb->op_num];
1521 if (a->serial != b->serial)
1522 return a->serial - b->serial;
1524 /* If they have same serial, it means one didn't make any
1525 * changes. Thus sort by end in that case. */
1526 return a[a->group_len].serial - b[b->group_len].serial;
1529 dep = talloc_array(NULL, struct traverse_dep, 1);
1532 for (i = 0; i < num; i++) {
1533 for (j = 1; j < num_ops[i]; j++) {
1534 /* Traverse start (ignore those in
1535 * transactions; they're already covered by
1536 * transaction dependencies). */
1537 if (starts_traverse(&op[i][j])
1538 && !in_transaction(op[i], j)) {
1539 dep = talloc_realloc(NULL, dep,
1540 struct traverse_dep,
1542 dep[num_traversals].file = i;
1543 dep[num_traversals].op_num = j;
1548 qsort(dep, num_traversals, sizeof(dep[0]), compare_traverse_dep);
1550 for (i = 1; i < num_traversals; i++) {
1551 const struct op *prev = &op[dep[i-1].file][dep[i-1].op_num];
1552 const struct op *curr = &op[dep[i].file][dep[i].op_num];
1554 /* Read traverses don't depend on each other (read lock). */
1555 if (prev->op == OP_TDB_TRAVERSE_READ_START
1556 && curr->op == OP_TDB_TRAVERSE_READ_START)
1559 /* Only make dependency if it's clear. */
1560 if (compare_traverse_dep(&dep[i], &dep[i-1])) {
1561 /* i depends on end of traverse i-1. */
1562 add_dependency(NULL, op, filename,
1563 dep[i].file, dep[i].op_num,
1564 dep[i-1].file, dep[i-1].op_num
1572 static void derive_dependencies(char *filename[],
1573 struct op *op[], unsigned int num_ops[],
1576 struct keyinfo *hash;
1579 /* Create hash table for faster key lookup. */
1580 hash = hash_ops(op, num_ops, num);
1582 /* Sort them by serial number. */
1583 sort_ops(hash, filename, op, num);
1585 /* Create dependencies back to the last change, rather than
1586 * creating false dependencies by naively making each one
1587 * depend on the previous. This has two purposes: it makes
1588 * later optimization simpler, and it also avoids deadlock with
1589 * same sequence number ops inside traversals (if one
1590 * traversal doesn't write anything, two ops can have the same
1591 * sequence number yet we can create a traversal dependency
1592 * the other way). */
1593 for (h = 0; h < total_keys * 2; h++) {
1596 if (hash[h].num_users < 2)
1599 for (i = 0; i < hash[h].num_users; i++) {
1600 if (changes_db(&hash[h].key, &op[hash[h].user[i].file]
1601 [hash[h].user[i].op_num])) {
1602 depend_on_previous(op, filename, num,
1603 hash[h].user, i, prev);
1605 } else if (prev >= 0)
1606 add_dependency(hash, op, filename,
1607 hash[h].user[i].file,
1608 hash[h].user[i].op_num,
1609 hash[h].user[prev].file,
1610 hash[h].user[prev].op_num);
1614 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
1615 make_traverse_depends(filename, op, num_ops, num);
1618 optimize_dependencies(op, num_ops, num);
1621 int main(int argc, char *argv[])
1623 struct timeval start, end;
1624 unsigned int i, num_ops[argc], hashsize[argc], tdb_flags[argc], open_flags[argc];
1625 struct op *op[argc];
1631 errx(1, "Usage: %s <tdbfile> <tracefile>...", argv[0]);
1633 pipes = talloc_array(NULL, struct pipe, argc - 2);
1634 for (i = 0; i < argc - 2; i++) {
1635 printf("Loading tracefile %s...", argv[2+i]);
1637 op[i] = load_tracefile(argv[2+i], &num_ops[i], &hashsize[i],
1638 &tdb_flags[i], &open_flags[i]);
1639 if (pipe(pipes[i].fd) != 0)
1640 err(1, "creating pipe");
1644 printf("Calculating inter-dependencies...");
1646 derive_dependencies(argv+2, op, num_ops, i);
1649 /* Don't fork for single arg case: simple debugging. */
1651 struct tdb_context *tdb;
1652 tdb = tdb_open_ex(argv[1], hashsize[0], tdb_flags[0]|TDB_NOSYNC,
1653 open_flags[0], 0600, NULL, hash_key);
1654 printf("Single threaded run...");
1657 run_ops(tdb, pipes[0].fd[0], argv+2, op, 0, 1, num_ops[0],
1659 check_deps(argv[2], op[0], num_ops[0]);
1666 err(1, "creating pipe");
1668 for (i = 0; i < argc - 2; i++) {
1669 struct tdb_context *tdb;
1673 err(1, "fork failed");
1676 tdb = tdb_open_ex(argv[1], hashsize[i],
1677 tdb_flags[i]|TDB_NOSYNC,
1678 open_flags[i], 0600, NULL, hash_key);
1680 err(1, "Opening tdb %s", argv[1]);
1682 /* This catches parent exiting. */
1683 if (read(fds[0], &c, 1) != 1)
1685 run_ops(tdb, pipes[i].fd[0], argv+2, op, i, 1,
1687 check_deps(argv[2+i], op[i], num_ops[i]);
1694 /* Let everything settle. */
1697 printf("Starting run...");
1699 gettimeofday(&start, NULL);
1700 /* Tell them all to go! Any write of sufficient length will do. */
1701 if (write(fds[1], hashsize, i) != i)
1702 err(1, "Writing to wakeup pipe");
1704 for (i = 0; i < argc - 2; i++) {
1707 if (!WIFEXITED(status)) {
1708 warnx("Child died with signal %i", WTERMSIG(status));
1710 } else if (WEXITSTATUS(status) != 0)
1711 /* Assume child spat out error. */
1717 gettimeofday(&end, NULL);
1720 end.tv_sec -= start.tv_sec;
1721 printf("Time replaying: %lu usec\n",
1722 end.tv_sec * 1000000UL + (end.tv_usec - start.tv_usec));