]> git.ozlabs.org Git - ccan/blob - ccan/tdb/tools/replay_trace.c
Add handling of reduced test cases (traverse lines trimmed), and add all the test...
[ccan] / ccan / tdb / tools / replay_trace.c
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>
8 #include <err.h>
9 #include <ctype.h>
10 #include <string.h>
11 #include <unistd.h>
12 #include <sys/types.h>
13 #include <sys/wait.h>
14 #include <sys/time.h>
15 #include <errno.h>
16 #include <signal.h>
17 #include <assert.h>
18
19 #define STRINGIFY2(x) #x
20 #define STRINGIFY(x) STRINGIFY2(x)
21
22 /* Avoid mod by zero */
23 static unsigned int total_keys = 1;
24
25 /* #define DEBUG_DEPS 1 */
26
27 /* Traversals block transactions in the current implementation. */
28 #define TRAVERSALS_TAKE_TRANSACTION_LOCK 1
29
30 struct pipe {
31         int fd[2];
32 };
33 static struct pipe *pipes;
34
35 static void __attribute__((noreturn)) fail(const char *filename,
36                                            unsigned int line,
37                                            const char *fmt, ...)
38 {
39         va_list ap;
40
41         va_start(ap, fmt);
42         fprintf(stderr, "%s:%u: FAIL: ", filename, line);
43         vfprintf(stderr, fmt, ap);
44         fprintf(stderr, "\n");
45         va_end(ap);
46         exit(1);
47 }
48         
49 /* Try or die. */
50 #define try(expr, expect)                                               \
51         do {                                                            \
52                 int ret = (expr);                                       \
53                 if (ret != (expect))                                    \
54                         fail(filename[file], i+1,                       \
55                              STRINGIFY(expr) "= %i", ret);              \
56         } while (0)
57
58 /* Try or imitate results. */
59 #define unreliable(expr, expect, force, undo)                           \
60         do {                                                            \
61                 int ret = expr;                                         \
62                 if (ret != expect) {                                    \
63                         fprintf(stderr, "%s:%u: %s gave %i not %i",     \
64                                 filename[file], i+1, STRINGIFY(expr),   \
65                                 ret, expect);                           \
66                         if (expect == 0)                                \
67                                 force;                                  \
68                         else                                            \
69                                 undo;                                   \
70                 }                                                       \
71         } while (0)
72
73 static bool key_eq(TDB_DATA a, TDB_DATA b)
74 {
75         if (a.dsize != b.dsize)
76                 return false;
77         return memcmp(a.dptr, b.dptr, a.dsize) == 0;
78 }
79
80 /* This is based on the hash algorithm from gdbm */
81 static unsigned int hash_key(TDB_DATA *key)
82 {
83         uint32_t value; /* Used to compute the hash value.  */
84         uint32_t   i;   /* Used to cycle through random values. */
85
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)));
89
90         return (1103515243 * value + 12345);  
91 }
92
93 enum op_type {
94         OP_TDB_LOCKALL,
95         OP_TDB_LOCKALL_MARK,
96         OP_TDB_LOCKALL_UNMARK,
97         OP_TDB_LOCKALL_NONBLOCK,
98         OP_TDB_UNLOCKALL,
99         OP_TDB_LOCKALL_READ,
100         OP_TDB_LOCKALL_READ_NONBLOCK,
101         OP_TDB_UNLOCKALL_READ,
102         OP_TDB_CHAINLOCK,
103         OP_TDB_CHAINLOCK_NONBLOCK,
104         OP_TDB_CHAINLOCK_MARK,
105         OP_TDB_CHAINLOCK_UNMARK,
106         OP_TDB_CHAINUNLOCK,
107         OP_TDB_CHAINLOCK_READ,
108         OP_TDB_CHAINUNLOCK_READ,
109         OP_TDB_PARSE_RECORD,
110         OP_TDB_EXISTS,
111         OP_TDB_STORE,
112         OP_TDB_APPEND,
113         OP_TDB_GET_SEQNUM,
114         OP_TDB_WIPE_ALL,
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,
120         OP_TDB_TRAVERSE_END,
121         OP_TDB_TRAVERSE,
122         OP_TDB_FIRSTKEY,
123         OP_TDB_NEXTKEY,
124         OP_TDB_FETCH,
125         OP_TDB_DELETE,
126 };
127
128 struct op {
129         unsigned int serial;
130         enum op_type op;
131         TDB_DATA key;
132         TDB_DATA data;
133         int ret;
134
135         /* Who is waiting for us? */
136         struct list_head post;
137         /* What are we waiting for? */
138         struct list_head pre;
139
140         /* If I'm part of a group (traverse/transaction) where is
141          * start?  (Otherwise, 0) */
142         unsigned int group_start;
143
144         union {
145                 int flag; /* open and store */
146                 struct {  /* append */
147                         TDB_DATA pre;
148                         TDB_DATA post;
149                 } append;
150                 /* transaction/traverse start/chainlock */
151                 unsigned int group_len;
152         };
153 };
154
155 static unsigned char hex_char(const char *filename, unsigned int line, char c)
156 {
157         c = toupper(c);
158         if (c >= 'A' && c <= 'F')
159                 return c - 'A' + 10;
160         if (c >= '0' && c <= '9')
161                 return c - '0';
162         fail(filename, line, "invalid hex character '%c'", c);
163 }
164
165 /* TDB data is <size>:<%02x>* */
166 static TDB_DATA make_tdb_data(const void *ctx,
167                               const char *filename, unsigned int line,
168                               const char *word)
169 {
170         TDB_DATA data;
171         unsigned int i;
172         const char *p;
173
174         if (streq(word, "NULL"))
175                 return tdb_null;
176
177         data.dsize = atoi(word);
178         data.dptr = talloc_array(ctx, unsigned char, data.dsize);
179         p = strchr(word, ':');
180         if (!p)
181                 fail(filename, line, "invalid tdb data '%s'", word);
182         p++;
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]);
186
187         return data;
188 }
189
190 static void add_op(const char *filename, struct op **op, unsigned int i,
191                    unsigned int serial, enum op_type type)
192 {
193         struct op *new;
194         *op = talloc_realloc(NULL, *op, struct op, i+1);
195         new = (*op) + i;
196         new->op = type;
197         new->serial = serial;
198         new->ret = 0;
199         new->group_start = 0;
200 }
201
202 static void op_add_nothing(const char *filename,
203                            struct op op[], unsigned int op_num, char *words[])
204 {
205         if (words[2])
206                 fail(filename, op_num+1, "Expected no arguments");
207         op[op_num].key = tdb_null;
208 }
209
210 static void op_add_key(const char *filename,
211                        struct op op[], unsigned int op_num, char *words[])
212 {
213         if (words[2] == NULL || words[3])
214                 fail(filename, op_num+1, "Expected just a key");
215
216         op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
217         total_keys++;
218 }
219
220 static void op_add_key_ret(const char *filename,
221                            struct op op[], unsigned int op_num, char *words[])
222 {
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)
230                 total_keys++;
231 }
232
233 static void op_add_key_data(const char *filename,
234                             struct op op[], unsigned int op_num, char *words[])
235 {
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)
243                 total_keys++;
244 }
245
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[])
249 {
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;
254 }
255
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[])
260 {
261         if (words[2])
262                 fail(filename, op_num+1, "Expected no values");
263         op[op_num].key = tdb_null;
264 }
265
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[])
269 {
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>");
273
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]);
278         total_keys++;
279 }
280
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[])
284 {
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>");
288
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]);
291
292         op[op_num].append.post
293                 = make_tdb_data(op, filename, op_num+1, words[5]);
294
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;
299         total_keys++;
300 }
301
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[])
305 {
306         if (!words[2] || !words[3] || words[4] || !streq(words[2], "="))
307                 fail(filename, op_num+1, "Expect = <ret>");
308
309         op[op_num].key = tdb_null;
310         op[op_num].ret = atoi(words[3]);
311 }
312
313 static void op_add_traverse_start(const char *filename,
314                                   struct op op[],
315                                   unsigned int op_num, char *words[])
316 {
317         if (words[2])
318                 fail(filename, op_num+1, "Expect no arguments");
319
320         op[op_num].key = tdb_null;
321         op[op_num].group_len = 0;
322 }
323
324 static void op_add_transaction(const char *filename, struct op op[],
325                                unsigned int op_num, char *words[])
326 {
327         if (words[2])
328                 fail(filename, op_num+1, "Expect no arguments");
329
330         op[op_num].key = tdb_null;
331         op[op_num].group_len = 0;
332 }
333
334 static void op_add_chainlock(const char *filename,
335                              struct op op[], unsigned int op_num, char *words[])
336 {
337         if (words[2] == NULL || words[3])
338                 fail(filename, op_num+1, "Expected just a key");
339
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;
345 }
346
347 static void op_add_chainlock_ret(const char *filename,
348                                  struct op op[], unsigned int op_num,
349                                  char *words[])
350 {
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;
358         total_keys++;
359 }
360
361 static int op_find_start(struct op op[], unsigned int op_num, enum op_type type)
362 {
363         unsigned int i;
364
365         for (i = op_num-1; i > 0; i--) {
366                 if (op[i].op == type && !op[i].group_len)
367                         return i;
368         }
369         return 0;
370 }
371
372 static void op_analyze_transaction(const char *filename,
373                                    struct op op[], unsigned int op_num,
374                                    char *words[])
375 {
376         unsigned int start, i;
377
378         op[op_num].key = tdb_null;
379
380         if (words[2])
381                 fail(filename, op_num+1, "Expect no arguments");
382
383         start = op_find_start(op, op_num, OP_TDB_TRANSACTION_START);
384         if (!start)
385                 fail(filename, op_num+1, "no transaction start found");
386
387         op[start].group_len = op_num - start;
388
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;
392 }
393
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,
397                                  char *words[])
398 {
399         unsigned int i, start;
400
401         if (words[2] == NULL || words[3])
402                 fail(filename, op_num+1, "Expected just a key");
403
404         op[op_num].data = make_tdb_data(op, filename, op_num+1, words[2]);
405         op[op_num].key = tdb_null;
406         total_keys++;
407
408         start = op_find_start(op, op_num, OP_TDB_CHAINLOCK);
409         if (!start)
410                 start = op_find_start(op, op_num, OP_TDB_CHAINLOCK_READ);
411         if (!start)
412                 fail(filename, op_num+1, "no initial chainlock found");
413
414         /* FIXME: We'd have to do something clever to make this work
415          * vs. deadlock. */
416         if (!key_eq(op[start].data, op[op_num].data))
417                 fail(filename, op_num+1, "nested chainlock calls?");
418
419         op[start].group_len = op_num - start;
420         for (i = start; i <= op_num; i++)
421                 op[i].group_start = start;
422 }
423
424 static void op_analyze_traverse(const char *filename,
425                                 struct op op[], unsigned int op_num,
426                                 char *words[])
427 {
428         int i, start;
429
430         op[op_num].key = tdb_null;
431
432         /* = %u means traverse function terminated. */
433         if (words[2]) {
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]);
437         } else
438                 op[op_num].ret = 0;
439
440         start = op_find_start(op, op_num, OP_TDB_TRAVERSE_START);
441         if (!start)
442                 start = op_find_start(op, op_num, OP_TDB_TRAVERSE_READ_START);
443         if (!start)
444                 fail(filename, op_num+1, "no traversal start found");
445
446         op[start].group_len = op_num - start;
447
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;
452 }
453
454 /* Keep -Wmissing-declarations happy: */
455 const struct op_table *
456 find_keyword (register const char *str, register unsigned int len);
457
458 #include "keywords.c"
459
460 struct depend {
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;
468 };
469
470 static void check_deps(const char *filename, struct op op[], unsigned int num)
471 {
472 #ifdef DEBUG_DEPS
473         unsigned int i;
474
475         for (i = 1; i < num; i++)
476                 if (!list_empty(&op[i].pre))
477                         fail(filename, i+1, "Still has dependencies");
478 #endif
479 }
480
481 static void dump_pre(char *filename[], struct op *op[],
482                      unsigned int file, unsigned int i)
483 {
484         struct depend *dep;
485
486         printf("%s:%u (%u) still waiting for:\n", filename[file], i+1,
487                 op[file][i].serial);
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);
493 }
494
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,
499                    bool backoff)
500 {
501         while (!list_empty(&op[file][i].pre)) {
502                 struct depend *dep;
503
504 #if DEBUG_DEPS
505                 printf("%s:%u:waiting for pre\n", filename[file], i+1);
506                 fflush(stdout);
507 #endif
508                 if (backoff)
509                         alarm(2);
510                 else
511                         alarm(10);
512                 while (read(pre_fd, &dep, sizeof(dep)) != sizeof(dep)) {
513                         if (errno == EINTR) {
514                                 if (backoff) {
515                                         warnx("%s:%u:avoiding deadlock",
516                                               filename[file], i+1);
517                                         return false;
518                                 }
519                                 dump_pre(filename, op, file, i);
520                                 exit(1);
521                         } else
522                                 errx(1, "Reading from pipe");
523                 }
524                 alarm(0);
525
526 #if DEBUG_DEPS
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);
530                 fflush(stdout);
531 #endif
532                 /* This could be any op, not just this one. */
533                 talloc_free(dep);
534         }
535         return true;
536 }
537
538 static void do_post(char *filename[], struct op *op[],
539                     unsigned int file, unsigned int i)
540 {
541         struct depend *dep;
542
543         list_for_each(&op[file][i].post, dep, post_list) {
544 #if DEBUG_DEPS
545                 printf("%s:%u:sending to file %s:%u\n", filename[file], i+1,
546                        filename[dep->needs_file], dep->needs_opnum+1);
547 #endif
548                 if (write(pipes[dep->needs_file].fd[1], &dep, sizeof(dep))
549                     != sizeof(dep))
550                         err(1, "%s:%u failed to tell file %s",
551                             filename[file], i+1, filename[dep->needs_file]);
552         }
553 }
554
555 static int get_len(TDB_DATA key, TDB_DATA data, void *private_data)
556 {
557         return data.dsize;
558 }
559
560 static unsigned run_ops(struct tdb_context *tdb,
561                         int pre_fd,
562                         char *filename[],
563                         struct op *op[],
564                         unsigned int file,
565                         unsigned int start, unsigned int stop,
566                         bool backoff);
567
568 struct traverse_info {
569         struct op **op;
570         char **filename;
571         unsigned file;
572         int pre_fd;
573         unsigned int start;
574         unsigned int i;
575 };
576
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,
580                                void *_tinfo)
581 {
582         struct traverse_info *tinfo = _tinfo;
583         unsigned int trav_len = tinfo->op[tinfo->file][tinfo->start].group_len;
584         bool avoid_deadlock = false;
585
586         if (tinfo->i == tinfo->start + trav_len) {
587                 /* This can happen if traverse expects to be empty. */
588                 if (trav_len == 1)
589                         return 1;
590                 fail(tinfo->filename[tinfo->file], tinfo->start + 1,
591                      "traverse did not terminate");
592         }
593
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");
597
598 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
599         avoid_deadlock = true;
600 #endif
601
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,
605                            avoid_deadlock);
606
607         /* We backed off, or we hit OP_TDB_TRAVERSE_END. */
608         if (tinfo->op[tinfo->file][tinfo->i].op != OP_TDB_TRAVERSE)
609                 return 1;
610
611         return 0;
612 }
613
614 static unsigned op_traverse(struct tdb_context *tdb,
615                             int pre_fd,
616                             char *filename[],
617                             unsigned int file,
618                             int (*traversefn)(struct tdb_context *,
619                                               tdb_traverse_func, void *),
620                             struct op *op[],
621                             unsigned int start)
622 {
623         struct traverse_info tinfo = { op, filename, file, pre_fd,
624                                        start, start+1 };
625
626         traversefn(tdb, nontrivial_traverse, &tinfo);
627
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)
633                         tinfo.i++;
634                 else
635                         tinfo.i = run_ops(tdb, pre_fd, filename, op, file,
636                                           tinfo.i,
637                                           start + op[file][start].group_len,
638                                           false);
639         }
640
641         return tinfo.i;
642 }
643
644 static void break_out(int sig)
645 {
646 }
647
648 static __attribute__((noinline))
649 unsigned run_ops(struct tdb_context *tdb,
650                  int pre_fd,
651                  char *filename[],
652                  struct op *op[],
653                  unsigned int file,
654                  unsigned int start, unsigned int stop,
655                  bool backoff)
656 {
657         unsigned int i;
658         struct sigaction sa;
659
660         sa.sa_handler = break_out;
661         sa.sa_flags = 0;
662
663         sigaction(SIGALRM, &sa, NULL);
664         for (i = start; i < stop; i++) {
665                 if (!do_pre(tdb, filename, op, file, pre_fd, i, backoff))
666                         return i;
667
668                 switch (op[file][i].op) {
669                 case OP_TDB_LOCKALL:
670                         try(tdb_lockall(tdb), op[file][i].ret);
671                         break;
672                 case OP_TDB_LOCKALL_MARK:
673                         try(tdb_lockall_mark(tdb), op[file][i].ret);
674                         break;
675                 case OP_TDB_LOCKALL_UNMARK:
676                         try(tdb_lockall_unmark(tdb), op[file][i].ret);
677                         break;
678                 case OP_TDB_LOCKALL_NONBLOCK:
679                         unreliable(tdb_lockall_nonblock(tdb), op[file][i].ret,
680                                    tdb_lockall(tdb), tdb_unlockall(tdb));
681                         break;
682                 case OP_TDB_UNLOCKALL:
683                         try(tdb_unlockall(tdb), op[file][i].ret);
684                         break;
685                 case OP_TDB_LOCKALL_READ:
686                         try(tdb_lockall_read(tdb), op[file][i].ret);
687                         break;
688                 case OP_TDB_LOCKALL_READ_NONBLOCK:
689                         unreliable(tdb_lockall_read_nonblock(tdb),
690                                    op[file][i].ret,
691                                    tdb_lockall_read(tdb),
692                                    tdb_unlockall_read(tdb));
693                         break;
694                 case OP_TDB_UNLOCKALL_READ:
695                         try(tdb_unlockall_read(tdb), op[file][i].ret);
696                         break;
697                 case OP_TDB_CHAINLOCK:
698                         try(tdb_chainlock(tdb, op[file][i].key),
699                             op[file][i].ret);
700                         break;
701                 case OP_TDB_CHAINLOCK_NONBLOCK:
702                         unreliable(tdb_chainlock_nonblock(tdb, op[file][i].key),
703                                    op[file][i].ret,
704                                    tdb_chainlock(tdb, op[file][i].key),
705                                    tdb_chainunlock(tdb, op[file][i].key));
706                         break;
707                 case OP_TDB_CHAINLOCK_MARK:
708                         try(tdb_chainlock_mark(tdb, op[file][i].key),
709                             op[file][i].ret);
710                         break;
711                 case OP_TDB_CHAINLOCK_UNMARK:
712                         try(tdb_chainlock_unmark(tdb, op[file][i].key),
713                             op[file][i].ret);
714                         break;
715                 case OP_TDB_CHAINUNLOCK:
716                         try(tdb_chainunlock(tdb, op[file][i].key),
717                             op[file][i].ret);
718                         break;
719                 case OP_TDB_CHAINLOCK_READ:
720                         try(tdb_chainlock_read(tdb, op[file][i].key),
721                             op[file][i].ret);
722                         break;
723                 case OP_TDB_CHAINUNLOCK_READ:
724                         try(tdb_chainunlock_read(tdb, op[file][i].key),
725                             op[file][i].ret);
726                         break;
727                 case OP_TDB_PARSE_RECORD:
728                         try(tdb_parse_record(tdb, op[file][i].key, get_len,
729                                              NULL),
730                             op[file][i].ret);
731                         break;
732                 case OP_TDB_EXISTS:
733                         try(tdb_exists(tdb, op[file][i].key), op[file][i].ret);
734                         break;
735                 case OP_TDB_STORE:
736                         try(tdb_store(tdb, op[file][i].key, op[file][i].data,
737                                       op[file][i].flag),
738                             op[file][i].ret);
739                         break;
740                 case OP_TDB_APPEND:
741                         try(tdb_append(tdb, op[file][i].key, op[file][i].data),
742                             op[file][i].ret);
743                         break;
744                 case OP_TDB_GET_SEQNUM:
745                         try(tdb_get_seqnum(tdb), op[file][i].ret);
746                         break;
747                 case OP_TDB_WIPE_ALL:
748                         try(tdb_wipe_all(tdb), op[file][i].ret);
749                         break;
750                 case OP_TDB_TRANSACTION_START:
751                         try(tdb_transaction_start(tdb), op[file][i].ret);
752                         break;
753                 case OP_TDB_TRANSACTION_CANCEL:
754                         try(tdb_transaction_cancel(tdb), op[file][i].ret);
755                         break;
756                 case OP_TDB_TRANSACTION_COMMIT:
757                         try(tdb_transaction_commit(tdb), op[file][i].ret);
758                         break;
759                 case OP_TDB_TRAVERSE_READ_START:
760                         i = op_traverse(tdb, pre_fd, filename, file,
761                                         tdb_traverse_read, op, i);
762                         break;
763                 case OP_TDB_TRAVERSE_START:
764                         i = op_traverse(tdb, pre_fd, filename, file,
765                                         tdb_traverse, op, i);
766                         break;
767                 case OP_TDB_TRAVERSE:
768                         /* Terminate: we're in a traverse, and we've
769                          * done our ops. */
770                         return i;
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");
777                         break;
778                 case OP_TDB_NEXTKEY:
779                         if (!key_eq(tdb_nextkey(tdb, op[file][i].key),
780                                     op[file][i].data))
781                                 fail(filename[file], i+1, "bad nextkey");
782                         break;
783                 case OP_TDB_FETCH: {
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",
787                                      f.dsize);
788                         break;
789                 }
790                 case OP_TDB_DELETE:
791                         try(tdb_delete(tdb, op[file][i].key), op[file][i].ret);
792                         break;
793                 }
794                 do_post(filename, op, file, i);
795         }
796         return i;
797 }
798
799 /* tdbtorture, in particular, can do a tdb_close with a transaction in
800  * progress. */
801 static struct op *maybe_cancel_transaction(const char *filename,
802                                            struct op *op, unsigned int *num)
803 {
804         unsigned int start = op_find_start(op, *num, OP_TDB_TRANSACTION_START);
805
806         if (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);
811                 (*num)++;
812         }
813         return op;
814 }
815
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)
820 {
821         unsigned int i;
822         struct op *op = talloc_array(NULL, struct op, 1);
823         char **words;
824         char **lines;
825         char *file;
826
827         file = grab_file(NULL, filename, NULL);
828         if (!file)
829                 err(1, "Reading %s", filename);
830
831         lines = strsplit(file, file, "\n", NULL);
832         if (!lines[0])
833                 errx(1, "%s is empty", filename);
834
835         words = strsplit(lines, lines[0], " ", NULL);
836         if (!streq(words[1], "tdb_open"))
837                 fail(filename, 1, "does not start with tdb_open");
838
839         *hashsize = atoi(words[2]);
840         *tdb_flags = strtoul(words[3], NULL, 0);
841         *open_flags = strtoul(words[4], NULL, 0);
842
843         for (i = 1; lines[i]; i++) {
844                 const struct op_table *opt;
845
846                 words = strsplit(lines, lines[i], " ", NULL);
847                 if (!words[0] || !words[1])
848                         fail(filename, i+1, "Expected serial number and op");
849                
850                 opt = find_keyword(words[1], strlen(words[1]));
851                 if (!opt) {
852                         if (streq(words[1], "tdb_close")) {
853                                 if (lines[i+1])
854                                         fail(filename, i+2,
855                                              "lines after tdb_close");
856                                 *num = i;
857                                 talloc_free(lines);
858                                 return maybe_cancel_transaction(filename,
859                                                                 op, num);
860                         }
861                         fail(filename, i+1, "Unknown operation '%s'", words[1]);
862                 }
863
864                 add_op(filename, &op, i, atoi(words[0]), opt->type);
865                 opt->enhance_op(filename, op, i, words);
866         }
867
868         fprintf(stderr, "%s:%u:last operation is not tdb_close: incomplete?",
869               filename, i);
870         talloc_free(lines);
871         *num = i - 1;
872         return maybe_cancel_transaction(filename, op, num);
873 }
874
875 /* We remember all the keys we've ever seen, and who has them. */
876 struct key_user {
877         unsigned int file;
878         unsigned int op_num;
879 };
880
881 struct keyinfo {
882         TDB_DATA key;
883         unsigned int num_users;
884         struct key_user *user;
885 };
886
887 static const TDB_DATA must_not_exist;
888 static const TDB_DATA must_exist;
889 static const TDB_DATA not_exists_or_empty;
890
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)
895 {
896         switch (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:
905                 return NULL;
906
907         case OP_TDB_APPEND:
908                 if (op->append.pre.dsize == 0)
909                         return &not_exists_or_empty;
910                 return &op->append.pre;
911
912         case OP_TDB_STORE:
913                 if (op->flag == TDB_INSERT) {
914                         if (op->ret < 0)
915                                 return &must_exist;
916                         else
917                                 return &must_not_exist;
918                 } else if (op->flag == TDB_MODIFY) {
919                         if (op->ret < 0)
920                                 return &must_not_exist;
921                         else
922                                 return &must_exist;
923                 }
924                 /* No flags?  Don't care */
925                 return NULL;
926
927         case OP_TDB_EXISTS:
928                 if (op->ret == 1)
929                         return &must_exist;
930                 else
931                         return &must_not_exist;
932
933         case OP_TDB_PARSE_RECORD:
934                 if (op->ret < 0)
935                         return &must_not_exist;
936                 return &must_exist;
937
938         /* FIXME: handle these. */
939         case OP_TDB_WIPE_ALL:
940         case OP_TDB_FIRSTKEY:
941         case OP_TDB_NEXTKEY:
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:
947                 return NULL;
948
949         case OP_TDB_FETCH:
950                 if (!op->data.dptr)
951                         return &must_not_exist;
952                 return &op->data;
953
954         case OP_TDB_DELETE:
955                 if (op->ret < 0)
956                         return &must_not_exist;
957                 return &must_exist;
958
959         default:
960                 errx(1, "Unexpected op %i", op->op);
961         }
962         
963 }
964
965 static bool starts_transaction(const struct op *op)
966 {
967         return op->op == OP_TDB_TRANSACTION_START;
968 }
969
970 static bool in_transaction(const struct op op[], unsigned int i)
971 {
972         return op[i].group_start && starts_transaction(&op[op[i].group_start]);
973 }
974
975 static bool successful_transaction(const struct op *op)
976 {
977         return starts_transaction(op)
978                 && op[op->group_len].op == OP_TDB_TRANSACTION_COMMIT;
979 }
980
981 static bool starts_traverse(const struct op *op)
982 {
983         return op->op == OP_TDB_TRAVERSE_START
984                 || op->op == OP_TDB_TRAVERSE_READ_START;
985 }
986
987 static bool in_traverse(const struct op op[], unsigned int i)
988 {
989         return op[i].group_start && starts_traverse(&op[op[i].group_start]);
990 }
991
992 static bool starts_chainlock(const struct op *op)
993 {
994         return op->op == OP_TDB_CHAINLOCK_READ || op->op == OP_TDB_CHAINLOCK;
995 }
996
997 static bool in_chainlock(const struct op op[], unsigned int i)
998 {
999         return op[i].group_start && starts_chainlock(&op[op[i].group_start]);
1000 }
1001
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)
1005 {
1006         if (starts_transaction(op) || starts_chainlock(op)) {
1007                 unsigned int i;
1008
1009                 /* Cancelled transactions don't change anything. */
1010                 if (op[op->group_len].op == OP_TDB_TRANSACTION_CANCEL)
1011                         return pre;
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);
1015
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]);
1020                 }
1021                 return pre;
1022         }
1023
1024         /* Failed ops don't change state of db. */
1025         if (op->ret < 0)
1026                 return pre;
1027
1028         if (op->op == OP_TDB_DELETE || op->op == OP_TDB_WIPE_ALL)
1029                 return &tdb_null;
1030
1031         if (op->op == OP_TDB_APPEND)
1032                 return &op->append.post;
1033
1034         if (op->op == OP_TDB_STORE)
1035                 return &op->data;
1036
1037         return pre;
1038 }
1039
1040 static struct keyinfo *hash_ops(struct op *op[], unsigned int num_ops[],
1041                                 unsigned int num)
1042 {
1043         unsigned int i, j, h;
1044         struct keyinfo *hash;
1045
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);
1052
1053                         if (!op[i][j].key.dptr)
1054                                 continue;
1055
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;
1060                                         break;
1061                                 }
1062                                 h = (h + 1) % (total_keys * 2);
1063                         }
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;
1068                         }
1069                         hash[h].user = talloc_realloc(hash, hash[h].user,
1070                                                      struct key_user,
1071                                                      hash[h].num_users+1);
1072
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;
1078
1079                                 /* Don't include twice. */
1080                                 if (hash[h].num_users
1081                                     && hash[h].user[hash[h].num_users-1].file
1082                                         == i
1083                                     && hash[h].user[hash[h].num_users-1].op_num
1084                                         == start)
1085                                         continue;
1086
1087                                 hash[h].user[hash[h].num_users].op_num = start;
1088                         } else
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++;
1092                 }
1093         }
1094
1095         return hash;
1096 }
1097
1098 static bool satisfies(const TDB_DATA *key, const TDB_DATA *data,
1099                       const struct op *op)
1100 {
1101         const TDB_DATA *need = NULL;
1102
1103         if (starts_transaction(op) || starts_chainlock(op)) {
1104                 unsigned int i;
1105
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)
1118                                         break;
1119                         }
1120                 }
1121         } else
1122                 need = needs(op);
1123
1124         /* Don't need anything?  Cool. */
1125         if (!need)
1126                 return true;
1127
1128         /* This should be tdb_null or a real value. */
1129         assert(data != &must_exist);
1130         assert(data != &must_not_exist);
1131         assert(data != &not_exists_or_empty);
1132
1133         /* Must not exist?  data must not exist. */
1134         if (need == &must_not_exist)
1135                 return data == &tdb_null;
1136
1137         /* Must exist? */
1138         if (need == &must_exist)
1139                 return data != &tdb_null;
1140
1141         /* Either noexist or empty. */
1142         if (need == &not_exists_or_empty)
1143                 return data->dsize == 0;
1144
1145         /* Needs something specific. */
1146         return key_eq(*data, *need);
1147 }
1148
1149 static void move_to_front(struct key_user res[], unsigned off, unsigned elem)
1150 {
1151         if (elem != off) {
1152                 struct key_user tmp = res[elem];
1153                 memmove(res + off + 1, res + off, (elem - off)*sizeof(res[0]));
1154                 res[off] = tmp;
1155         }
1156 }
1157
1158 static void restore_to_pos(struct key_user res[], unsigned off, unsigned elem)
1159 {
1160         if (elem != off) {
1161                 struct key_user tmp = res[off];
1162                 memmove(res + off, res + off + 1, (elem - off)*sizeof(res[0]));
1163                 res[elem] = tmp;
1164         }
1165 }
1166
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)
1172 {
1173         unsigned int i, files_done;
1174         struct op *this_op;
1175         bool done[num_files];
1176
1177         /* None left?  We're sorted. */
1178         if (off == num)
1179                 return true;
1180
1181         /* Does this make serial numbers go backwards?  Allow a little fuzz. */
1182         if (off > 0) {
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;
1185
1186                 if (serial1 - serial2 > (int)fuzz) {
1187 #if DEBUG_DEPS
1188                         printf("Serial jump too far (%u -> %u)\n",
1189                                serial1, serial2);
1190 #endif
1191                         return false;
1192                 }
1193         }
1194
1195         memset(done, 0, sizeof(done));
1196
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])
1203                         continue;
1204
1205                 this_op = &op[res[i].file][res[i].op_num];
1206
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),
1212                                       num_files, fuzz))
1213                                 return true;
1214                         restore_to_pos(res, off, i);
1215                 }
1216                 done[res[i].file] = true;
1217                 files_done++;
1218         }
1219
1220         /* No combination worked. */
1221         return false;
1222 }
1223
1224 static void check_dep_sorting(struct key_user user[], unsigned num_users,
1225                               unsigned num_files)
1226 {
1227 #if DEBUG_DEPS
1228         unsigned int i;
1229         unsigned minima[num_files];
1230
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;
1235         }
1236 #endif
1237 }
1238
1239 /* All these ops happen on the same key.  Which comes first?
1240  *
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).
1245  */
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)
1249 {
1250         /* We assume database starts empty. */
1251         const struct TDB_DATA *data = &tdb_null;
1252         unsigned int fuzz;
1253
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,
1258                               num_files, fuzz))
1259                         break;
1260         }
1261
1262         if (fuzz >= 100)
1263                 fail(filename[user[0].file], user[0].op_num+1,
1264                      "Could not resolve inter-dependencies");
1265
1266         check_dep_sorting(user, num_users, num_files);
1267 }
1268
1269 static void sort_ops(struct keyinfo hash[], char *filename[], struct op *op[],
1270                      unsigned int num)
1271 {
1272         unsigned int h;
1273
1274         /* Gcc nexted function extension.  How cool is this? */
1275         int compare_serial(const void *_a, const void *_b)
1276         {
1277                 const struct key_user *a = _a, *b = _b;
1278
1279                 /* First, maintain order within any trace file. */
1280                 if (a->file == b->file)
1281                         return a->op_num - b->op_num;
1282
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;
1288
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]))
1292                         return -1;
1293                 if (starts_transaction(&op[b->file][b->op_num])
1294                     && !successful_transaction(&op[b->file][b->op_num]))
1295                         return 1;
1296
1297                 /* No idea. */
1298                 return 0;
1299         }
1300
1301         /* Now sort into serial order. */
1302         for (h = 0; h < total_keys * 2; h++) {
1303                 struct key_user *user = hash[h].user;
1304
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,
1307                             num);
1308         }
1309 }
1310
1311 static int destroy_depend(struct depend *dep)
1312 {
1313         list_del(&dep->pre_list);
1314         list_del(&dep->post_list);
1315         return 0;
1316 }
1317
1318 static void add_dependency(void *ctx,
1319                            struct op *op[],
1320                            char *filename[],
1321                            unsigned int needs_file,
1322                            unsigned int needs_opnum,
1323                            unsigned int satisfies_file,
1324                            unsigned int satisfies_opnum)
1325 {
1326         struct depend *dep;
1327
1328         /* We don't depend on ourselves. */
1329         if (needs_file == satisfies_file) {
1330                 assert(satisfies_opnum < needs_opnum);
1331                 return;
1332         }
1333
1334 #if DEBUG_DEPS
1335         printf("%s:%u: depends on %s:%u\n",
1336                filename[needs_file], needs_opnum+1,
1337                filename[satisfies_file], satisfies_opnum+1);
1338 #endif
1339
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
1343          * two groups. */
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])))){
1350                 unsigned int sat;
1351
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;
1357         }
1358
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.
1364          *
1365          * We try to address this by ensuring that where seqnum indicates it's
1366          * possible, we wait for <create foo> before *starting* traverse.
1367          */
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;
1373                 }
1374         }
1375 #endif
1376
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])) {
1381                 satisfies_opnum
1382                         += op[satisfies_file][satisfies_opnum].group_len;
1383 #if DEBUG_DEPS
1384                 printf("-> Actually end of transaction %s:%u\n",
1385                        filename[satisfies_file], satisfies_opnum+1);
1386 #endif
1387         } else
1388                 /* We should never create a dependency from middle of
1389                  * a transaction. */
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);
1395
1396         assert(op[needs_file][needs_opnum].op != OP_TDB_TRAVERSE);
1397         assert(op[satisfies_file][satisfies_opnum].op != OP_TDB_TRAVERSE);
1398
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);
1407 }
1408
1409 static bool changes_db(const TDB_DATA *key, const struct op *op)
1410 {
1411         return gives(key, NULL, op) != NULL;
1412 }
1413
1414 static void depend_on_previous(struct op *op[],
1415                                char *filename[],
1416                                unsigned int num,
1417                                struct key_user user[],
1418                                unsigned int i,
1419                                int prev)
1420 {
1421         bool deps[num];
1422         int j;
1423
1424         if (i == 0)
1425                 return;
1426
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);
1432                 return;
1433         }
1434
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;
1444                 }
1445         }
1446 }
1447
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[],
1451                                   unsigned int num)
1452 {
1453         unsigned int i, j;
1454
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];
1460
1461                         memset(prev, 0, sizeof(prev));
1462
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;
1466                                         continue;
1467                                 }
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;
1472                                 } else
1473                                         talloc_free(dep);
1474                         }
1475                 }
1476         }
1477
1478         for (i = 0; i < num; i++) {
1479                 int deps[num];
1480
1481                 for (j = 0; j < num; j++)
1482                         deps[j] = -1;
1483
1484                 for (j = 1; j < num_ops[i]; j++) {
1485                         struct depend *dep, *next;
1486
1487                         list_for_each_safe(&op[i][j].pre, dep, next, pre_list) {
1488                                 if (deps[dep->satisfies_file]
1489                                     >= (int)dep->satisfies_opnum)
1490                                         talloc_free(dep);
1491                                 else
1492                                         deps[dep->satisfies_file]
1493                                                 = dep->satisfies_opnum;
1494                         }
1495                 }
1496         }
1497 }
1498
1499 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
1500 struct traverse_dep {
1501         unsigned int file;
1502         unsigned int op_num;
1503 };
1504
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[],
1508                                   unsigned int num)
1509 {
1510         unsigned int i, num_traversals = 0;
1511         int j;
1512         struct traverse_dep *dep;
1513
1514         /* Sort by which one runs first. */
1515         int compare_traverse_dep(const void *_a, const void *_b)
1516         {
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];
1520
1521                 if (a->serial != b->serial)
1522                         return a->serial - b->serial;
1523
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;
1527         }
1528
1529         dep = talloc_array(NULL, struct traverse_dep, 1);
1530
1531         /* Count them. */
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,
1541                                                      num_traversals+1);
1542                                 dep[num_traversals].file = i;
1543                                 dep[num_traversals].op_num = j;
1544                                 num_traversals++;
1545                         }
1546                 }
1547         }
1548         qsort(dep, num_traversals, sizeof(dep[0]), compare_traverse_dep);
1549
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];
1553
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)
1557                         continue;
1558
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
1565                                        + prev->group_len);
1566                 }
1567         }
1568         talloc_free(dep);
1569 }
1570 #endif
1571
1572 static void derive_dependencies(char *filename[],
1573                                 struct op *op[], unsigned int num_ops[],
1574                                 unsigned int num)
1575 {
1576         struct keyinfo *hash;
1577         unsigned int h, i;
1578
1579         /* Create hash table for faster key lookup. */
1580         hash = hash_ops(op, num_ops, num);
1581
1582         /* Sort them by serial number. */
1583         sort_ops(hash, filename, op, num);
1584
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++) {
1594                 int prev = -1;
1595
1596                 if (hash[h].num_users < 2)
1597                         continue;
1598
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);
1604                                 prev = i;
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);
1611                 }
1612         }
1613
1614 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
1615         make_traverse_depends(filename, op, num_ops, num);
1616 #endif
1617
1618         optimize_dependencies(op, num_ops, num);
1619 }
1620
1621 int main(int argc, char *argv[])
1622 {
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];
1626         int fds[2];
1627         char c;
1628         bool ok = true;
1629
1630         if (argc < 3)
1631                 errx(1, "Usage: %s <tdbfile> <tracefile>...", argv[0]);
1632
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]);
1636                 fflush(stdout);
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");
1641                 printf("done\n");
1642         }
1643
1644         printf("Calculating inter-dependencies...");
1645         fflush(stdout);
1646         derive_dependencies(argv+2, op, num_ops, i);
1647         printf("done\n");
1648
1649         /* Don't fork for single arg case: simple debugging. */
1650         if (argc == 3) {
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...");
1655                 fflush(stdout);
1656
1657                 run_ops(tdb, pipes[0].fd[0], argv+2, op, 0, 1, num_ops[0],
1658                         false);
1659                 check_deps(argv[2], op[0], num_ops[0]);
1660
1661                 printf("done\n");
1662                 exit(0);
1663         }
1664
1665         if (pipe(fds) != 0)
1666                 err(1, "creating pipe");
1667
1668         for (i = 0; i < argc - 2; i++) {
1669                 struct tdb_context *tdb;
1670
1671                 switch (fork()) {
1672                 case -1:
1673                         err(1, "fork failed");
1674                 case 0:
1675                         close(fds[1]);
1676                         tdb = tdb_open_ex(argv[1], hashsize[i],
1677                                           tdb_flags[i]|TDB_NOSYNC,
1678                                           open_flags[i], 0600, NULL, hash_key);
1679                         if (!tdb)
1680                                 err(1, "Opening tdb %s", argv[1]);
1681
1682                         /* This catches parent exiting. */
1683                         if (read(fds[0], &c, 1) != 1)
1684                                 exit(1);
1685                         run_ops(tdb, pipes[i].fd[0], argv+2, op, i, 1,
1686                                 num_ops[i], false);
1687                         check_deps(argv[2+i], op[i], num_ops[i]);
1688                         exit(0);
1689                 default:
1690                         break;
1691                 }
1692         }
1693
1694         /* Let everything settle. */
1695         sleep(1);
1696
1697         printf("Starting run...");
1698         fflush(stdout);
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");
1703
1704         for (i = 0; i < argc - 2; i++) {
1705                 int status;
1706                 wait(&status);
1707                 if (!WIFEXITED(status)) {
1708                         warnx("Child died with signal %i", WTERMSIG(status));
1709                         ok = false;
1710                 } else if (WEXITSTATUS(status) != 0)
1711                         /* Assume child spat out error. */
1712                         ok = false;
1713         }
1714         if (!ok)
1715                 exit(1);
1716
1717         gettimeofday(&end, NULL);
1718         printf("done\n");
1719
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));
1723         
1724         exit(0);
1725 }