]> git.ozlabs.org Git - ccan/blob - ccan/tdb/tools/replay_trace.c
Clean up traverse keyword handling.
[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                 unsigned int group_len; /* transaction/traverse start */
151         };
152 };
153
154 static unsigned char hex_char(const char *filename, unsigned int line, char c)
155 {
156         c = toupper(c);
157         if (c >= 'A' && c <= 'F')
158                 return c - 'A' + 10;
159         if (c >= '0' && c <= '9')
160                 return c - '0';
161         fail(filename, line, "invalid hex character '%c'", c);
162 }
163
164 /* TDB data is <size>:<%02x>* */
165 static TDB_DATA make_tdb_data(const void *ctx,
166                               const char *filename, unsigned int line,
167                               const char *word)
168 {
169         TDB_DATA data;
170         unsigned int i;
171         const char *p;
172
173         if (streq(word, "NULL"))
174                 return tdb_null;
175
176         data.dsize = atoi(word);
177         data.dptr = talloc_array(ctx, unsigned char, data.dsize);
178         p = strchr(word, ':');
179         if (!p)
180                 fail(filename, line, "invalid tdb data '%s'", word);
181         p++;
182         for (i = 0; i < data.dsize; i++)
183                 data.dptr[i] = hex_char(filename, line, p[i*2])*16
184                         + hex_char(filename, line, p[i*2+1]);
185
186         return data;
187 }
188
189 static void add_op(const char *filename, struct op **op, unsigned int i,
190                    unsigned int serial, enum op_type type)
191 {
192         struct op *new;
193         *op = talloc_realloc(NULL, *op, struct op, i+1);
194         new = (*op) + i;
195         new->op = type;
196         new->serial = serial;
197         new->ret = 0;
198         new->group_start = 0;
199 }
200
201 static void op_add_nothing(const char *filename,
202                            struct op op[], unsigned int op_num, char *words[])
203 {
204         if (words[2])
205                 fail(filename, op_num+1, "Expected no arguments");
206         op[op_num].key = tdb_null;
207 }
208
209 static void op_add_key(const char *filename,
210                        struct op op[], unsigned int op_num, char *words[])
211 {
212         if (words[2] == NULL || words[3])
213                 fail(filename, op_num+1, "Expected just a key");
214
215         op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
216         total_keys++;
217 }
218
219 static void op_add_key_ret(const char *filename,
220                            struct op op[], unsigned int op_num, char *words[])
221 {
222         if (!words[2] || !words[3] || !words[4] || words[5]
223             || !streq(words[3], "="))
224                 fail(filename, op_num+1, "Expected <key> = <ret>");
225         op[op_num].ret = atoi(words[4]);
226         op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
227         /* May only be a unique key if it fails */
228         if (op[op_num].ret != 0)
229                 total_keys++;
230 }
231
232 static void op_add_key_data(const char *filename,
233                             struct op op[], unsigned int op_num, char *words[])
234 {
235         if (!words[2] || !words[3] || !words[4] || words[5]
236             || !streq(words[3], "="))
237                 fail(filename, op_num+1, "Expected <key> = <data>");
238         op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
239         op[op_num].data = make_tdb_data(op, filename, op_num+1, words[4]);
240         /* May only be a unique key if it fails */
241         if (!op[op_num].data.dptr)
242                 total_keys++;
243 }
244
245 /* We don't record the keys or data for a traverse, as we don't use them. */
246 static void op_add_traverse(const char *filename,
247                             struct op op[], unsigned int op_num, char *words[])
248 {
249         if (!words[2] || !words[3] || !words[4] || words[5]
250             || !streq(words[3], "="))
251                 fail(filename, op_num+1, "Expected <key> = <data>");
252         op[op_num].key = tdb_null;
253 }
254
255 /* <serial> tdb_store <rec> <rec> <flag> = <ret> */
256 static void op_add_store(const char *filename,
257                          struct op op[], unsigned int op_num, char *words[])
258 {
259         if (!words[2] || !words[3] || !words[4] || !words[5] || !words[6]
260             || words[7] || !streq(words[5], "="))
261                 fail(filename, op_num+1, "Expect <key> <data> <flag> = <ret>");
262
263         op[op_num].flag = strtoul(words[4], NULL, 0);
264         op[op_num].ret = atoi(words[6]);
265         op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
266         op[op_num].data = make_tdb_data(op, filename, op_num+1, words[3]);
267         total_keys++;
268 }
269
270 /* <serial> tdb_append <rec> <rec> = <rec> */
271 static void op_add_append(const char *filename,
272                           struct op op[], unsigned int op_num, char *words[])
273 {
274         if (!words[2] || !words[3] || !words[4] || !words[5] || words[6]
275             || !streq(words[4], "="))
276                 fail(filename, op_num+1, "Expect <key> <data> = <rec>");
277
278         op[op_num].key = make_tdb_data(op, filename, op_num+1, words[2]);
279         op[op_num].data = make_tdb_data(op, filename, op_num+1, words[3]);
280
281         op[op_num].append.post
282                 = make_tdb_data(op, filename, op_num+1, words[5]);
283
284         /* By subtraction, figure out what previous data was. */
285         op[op_num].append.pre.dptr = op[op_num].append.post.dptr;
286         op[op_num].append.pre.dsize
287                 = op[op_num].append.post.dsize - op[op_num].data.dsize;
288         total_keys++;
289 }
290
291 /* <serial> tdb_get_seqnum = <ret> */
292 static void op_add_seqnum(const char *filename,
293                           struct op op[], unsigned int op_num, char *words[])
294 {
295         if (!words[2] || !words[3] || words[4] || !streq(words[2], "="))
296                 fail(filename, op_num+1, "Expect = <ret>");
297
298         op[op_num].key = tdb_null;
299         op[op_num].ret = atoi(words[3]);
300 }
301
302 static void op_add_traverse_start(const char *filename,
303                                   struct op op[],
304                                   unsigned int op_num, char *words[])
305 {
306         if (words[2])
307                 fail(filename, op_num+1, "Expect no arguments");
308
309         op[op_num].key = tdb_null;
310         op[op_num].group_len = 0;
311 }
312
313 static void op_add_transaction(const char *filename, struct op op[],
314                                unsigned int op_num, char *words[])
315 {
316         if (words[2])
317                 fail(filename, op_num+1, "Expect no arguments");
318
319         op[op_num].key = tdb_null;
320         op[op_num].group_len = 0;
321 }
322
323 static int op_transaction_start(struct op op[], unsigned int op_num)
324 {
325         unsigned int i;
326
327         for (i = op_num-1; i > 0; i--) {
328                 if (op[i].op == OP_TDB_TRANSACTION_START && !op[i].group_len)
329                         return i;
330         }
331         return 0;
332 }
333
334 static void op_analyze_transaction(const char *filename,
335                                    struct op op[], unsigned int op_num,
336                                    char *words[])
337 {
338         unsigned int start, i;
339
340         op[op_num].key = tdb_null;
341
342         if (words[2])
343                 fail(filename, op_num+1, "Expect no arguments");
344
345         start = op_transaction_start(op, op_num);
346         if (!start)
347                 fail(filename, op_num+1, "no transaction start found");
348
349         op[start].group_len = op_num - start;
350
351         /* This rolls in nested transactions.  I think that's right. */
352         for (i = start; i <= op_num; i++)
353                 op[i].group_start = start;
354 }
355
356 struct traverse_hash {
357         TDB_DATA key;
358         unsigned int index;
359 };
360
361 static void op_analyze_traverse(const char *filename,
362                                 struct op op[], unsigned int op_num,
363                                 char *words[])
364 {
365         int i, start;
366
367         op[op_num].key = tdb_null;
368
369         /* = %u means traverse function terminated. */
370         if (words[2]) {
371                 if (!streq(words[2], "=") || !words[3] || words[4])
372                         fail(filename, op_num+1, "expect = <num>");
373                 op[op_num].ret = atoi(words[3]);
374         } else
375                 op[op_num].ret = 0;
376
377         for (i = op_num-1; i >= 0; i--) {
378                 if (op[i].op != OP_TDB_TRAVERSE_READ_START
379                     && op[i].op != OP_TDB_TRAVERSE_START)
380                         continue;
381                 if (op[i].group_len)
382                         continue;
383                 break;
384         }
385
386         if (i < 0)
387                 fail(filename, op_num+1, "no traversal start found");
388
389         start = i;
390         op[start].group_len = op_num - start;
391
392         for (i = start; i <= op_num; i++)
393                 op[i].group_start = start;
394 }
395
396 /* Keep -Wmissing-declarations happy: */
397 const struct op_table *
398 find_keyword (register const char *str, register unsigned int len);
399
400 #include "keywords.c"
401
402 struct depend {
403         /* We can have more than one */
404         struct list_node pre_list;
405         struct list_node post_list;
406         unsigned int needs_file;
407         unsigned int needs_opnum;
408         unsigned int satisfies_file;
409         unsigned int satisfies_opnum;
410 };
411
412 static void check_deps(const char *filename, struct op op[], unsigned int num)
413 {
414 #ifdef DEBUG_DEPS
415         unsigned int i;
416
417         for (i = 1; i < num; i++)
418                 if (!list_empty(&op[i].pre))
419                         fail(filename, i+1, "Still has dependencies");
420 #endif
421 }
422
423 static void dump_pre(char *filename[], struct op *op[],
424                      unsigned int file, unsigned int i)
425 {
426         struct depend *dep;
427
428         printf("%s:%u (%u) still waiting for:\n", filename[file], i+1,
429                 op[file][i].serial);
430         list_for_each(&op[file][i].pre, dep, pre_list)
431                 printf("    %s:%u (%u)\n",
432                        filename[dep->satisfies_file], dep->satisfies_opnum+1,
433                        op[dep->satisfies_file][dep->satisfies_opnum].serial);
434         check_deps(filename[file], op[file], i);
435 }
436
437 /* We simply read/write pointers, since we all are children. */
438 static bool do_pre(struct tdb_context *tdb,
439                    char *filename[], struct op *op[],
440                    unsigned int file, int pre_fd, unsigned int i,
441                    bool backoff)
442 {
443         while (!list_empty(&op[file][i].pre)) {
444                 struct depend *dep;
445
446 #if DEBUG_DEPS
447                 printf("%s:%u:waiting for pre\n", filename[file], i+1);
448                 fflush(stdout);
449 #endif
450                 if (backoff)
451                         alarm(2);
452                 else
453                         alarm(10);
454                 while (read(pre_fd, &dep, sizeof(dep)) != sizeof(dep)) {
455                         if (errno == EINTR) {
456                                 if (backoff) {
457                                         warnx("%s:%u:avoiding deadlock",
458                                               filename[file], i+1);
459                                         return false;
460                                 }
461                                 dump_pre(filename, op, file, i);
462                                 exit(1);
463                         } else
464                                 errx(1, "Reading from pipe");
465                 }
466                 alarm(0);
467
468 #if DEBUG_DEPS
469                 printf("%s:%u:got pre %u from %s:%u\n", filename[file], i+1,
470                        dep->needs_opnum+1, filename[dep->satisfies_file],
471                        dep->satisfies_opnum+1);
472                 fflush(stdout);
473 #endif
474                 /* This could be any op, not just this one. */
475                 talloc_free(dep);
476         }
477         return true;
478 }
479
480 static void do_post(char *filename[], struct op *op[],
481                     unsigned int file, unsigned int i)
482 {
483         struct depend *dep;
484
485         list_for_each(&op[file][i].post, dep, post_list) {
486 #if DEBUG_DEPS
487                 printf("%s:%u:sending to file %s:%u\n", filename[file], i+1,
488                        filename[dep->needs_file], dep->needs_opnum+1);
489 #endif
490                 if (write(pipes[dep->needs_file].fd[1], &dep, sizeof(dep))
491                     != sizeof(dep))
492                         err(1, "%s:%u failed to tell file %s",
493                             filename[file], i+1, filename[dep->needs_file]);
494         }
495 }
496
497 static int get_len(TDB_DATA key, TDB_DATA data, void *private_data)
498 {
499         return data.dsize;
500 }
501
502 static unsigned run_ops(struct tdb_context *tdb,
503                         int pre_fd,
504                         char *filename[],
505                         struct op *op[],
506                         unsigned int file,
507                         unsigned int start, unsigned int stop,
508                         bool backoff);
509
510 struct traverse_info {
511         struct op **op;
512         char **filename;
513         unsigned file;
514         int pre_fd;
515         unsigned int start;
516         unsigned int i;
517 };
518
519 /* More complex.  Just do whatever's they did at the n'th entry. */
520 static int nontrivial_traverse(struct tdb_context *tdb,
521                                TDB_DATA key, TDB_DATA data,
522                                void *_tinfo)
523 {
524         struct traverse_info *tinfo = _tinfo;
525         unsigned int trav_len = tinfo->op[tinfo->file][tinfo->start].group_len;
526         bool avoid_deadlock = false;
527
528         if (tinfo->i == tinfo->start + trav_len) {
529                 /* This can happen if traverse expects to be empty. */
530                 if (trav_len == 1)
531                         return 1;
532                 fail(tinfo->filename[tinfo->file], tinfo->start + 1,
533                      "traverse did not terminate");
534         }
535
536         if (tinfo->op[tinfo->file][tinfo->i].op != OP_TDB_TRAVERSE)
537                 fail(tinfo->filename[tinfo->file], tinfo->start + 1,
538                      "%s:%u:traverse terminated early");
539
540 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
541         avoid_deadlock = true;
542 #endif
543
544         /* Run any normal ops. */
545         tinfo->i = run_ops(tdb, tinfo->pre_fd, tinfo->filename, tinfo->op,
546                            tinfo->file, tinfo->i+1, tinfo->start + trav_len,
547                            avoid_deadlock);
548
549         /* We backed off, or we hit OP_TDB_TRAVERSE_END. */
550         if (tinfo->op[tinfo->file][tinfo->i].op != OP_TDB_TRAVERSE)
551                 return 1;
552
553         return 0;
554 }
555
556 static unsigned op_traverse(struct tdb_context *tdb,
557                             int pre_fd,
558                             char *filename[],
559                             unsigned int file,
560                             int (*traversefn)(struct tdb_context *,
561                                               tdb_traverse_func, void *),
562                             struct op *op[],
563                             unsigned int start)
564 {
565         struct traverse_info tinfo = { op, filename, file, pre_fd,
566                                        start, start+1 };
567
568         traversefn(tdb, nontrivial_traverse, &tinfo);
569
570         /* Traversing in wrong order can have strange effects: eg. if
571          * original traverse went A (delete A), B, we might do B
572          * (delete A).  So if we have ops left over, we do it now. */
573         while (tinfo.i != start + op[file][start].group_len) {
574                 if (op[file][tinfo.i].op == OP_TDB_TRAVERSE)
575                         tinfo.i++;
576                 else
577                         tinfo.i = run_ops(tdb, pre_fd, filename, op, file,
578                                           tinfo.i,
579                                           start + op[file][start].group_len,
580                                           false);
581         }
582
583         return tinfo.i;
584 }
585
586 static void break_out(int sig)
587 {
588 }
589
590 static __attribute__((noinline))
591 unsigned run_ops(struct tdb_context *tdb,
592                  int pre_fd,
593                  char *filename[],
594                  struct op *op[],
595                  unsigned int file,
596                  unsigned int start, unsigned int stop,
597                  bool backoff)
598 {
599         unsigned int i;
600         struct sigaction sa;
601
602         sa.sa_handler = break_out;
603         sa.sa_flags = 0;
604
605         sigaction(SIGALRM, &sa, NULL);
606         for (i = start; i < stop; i++) {
607                 if (!do_pre(tdb, filename, op, file, pre_fd, i, backoff))
608                         return i;
609
610                 switch (op[file][i].op) {
611                 case OP_TDB_LOCKALL:
612                         try(tdb_lockall(tdb), op[file][i].ret);
613                         break;
614                 case OP_TDB_LOCKALL_MARK:
615                         try(tdb_lockall_mark(tdb), op[file][i].ret);
616                         break;
617                 case OP_TDB_LOCKALL_UNMARK:
618                         try(tdb_lockall_unmark(tdb), op[file][i].ret);
619                         break;
620                 case OP_TDB_LOCKALL_NONBLOCK:
621                         unreliable(tdb_lockall_nonblock(tdb), op[file][i].ret,
622                                    tdb_lockall(tdb), tdb_unlockall(tdb));
623                         break;
624                 case OP_TDB_UNLOCKALL:
625                         try(tdb_unlockall(tdb), op[file][i].ret);
626                         break;
627                 case OP_TDB_LOCKALL_READ:
628                         try(tdb_lockall_read(tdb), op[file][i].ret);
629                         break;
630                 case OP_TDB_LOCKALL_READ_NONBLOCK:
631                         unreliable(tdb_lockall_read_nonblock(tdb),
632                                    op[file][i].ret,
633                                    tdb_lockall_read(tdb),
634                                    tdb_unlockall_read(tdb));
635                         break;
636                 case OP_TDB_UNLOCKALL_READ:
637                         try(tdb_unlockall_read(tdb), op[file][i].ret);
638                         break;
639                 case OP_TDB_CHAINLOCK:
640                         try(tdb_chainlock(tdb, op[file][i].key),
641                             op[file][i].ret);
642                         break;
643                 case OP_TDB_CHAINLOCK_NONBLOCK:
644                         unreliable(tdb_chainlock_nonblock(tdb, op[file][i].key),
645                                    op[file][i].ret,
646                                    tdb_chainlock(tdb, op[file][i].key),
647                                    tdb_chainunlock(tdb, op[file][i].key));
648                         break;
649                 case OP_TDB_CHAINLOCK_MARK:
650                         try(tdb_chainlock_mark(tdb, op[file][i].key),
651                             op[file][i].ret);
652                         break;
653                 case OP_TDB_CHAINLOCK_UNMARK:
654                         try(tdb_chainlock_unmark(tdb, op[file][i].key),
655                             op[file][i].ret);
656                         break;
657                 case OP_TDB_CHAINUNLOCK:
658                         try(tdb_chainunlock(tdb, op[file][i].key),
659                             op[file][i].ret);
660                         break;
661                 case OP_TDB_CHAINLOCK_READ:
662                         try(tdb_chainlock_read(tdb, op[file][i].key),
663                             op[file][i].ret);
664                         break;
665                 case OP_TDB_CHAINUNLOCK_READ:
666                         try(tdb_chainunlock_read(tdb, op[file][i].key),
667                             op[file][i].ret);
668                         break;
669                 case OP_TDB_PARSE_RECORD:
670                         try(tdb_parse_record(tdb, op[file][i].key, get_len,
671                                              NULL),
672                             op[file][i].ret);
673                         break;
674                 case OP_TDB_EXISTS:
675                         try(tdb_exists(tdb, op[file][i].key), op[file][i].ret);
676                         break;
677                 case OP_TDB_STORE:
678                         try(tdb_store(tdb, op[file][i].key, op[file][i].data,
679                                       op[file][i].flag),
680                             op[file][i].ret);
681                         break;
682                 case OP_TDB_APPEND:
683                         try(tdb_append(tdb, op[file][i].key, op[file][i].data),
684                             op[file][i].ret);
685                         break;
686                 case OP_TDB_GET_SEQNUM:
687                         try(tdb_get_seqnum(tdb), op[file][i].ret);
688                         break;
689                 case OP_TDB_WIPE_ALL:
690                         try(tdb_wipe_all(tdb), op[file][i].ret);
691                         break;
692                 case OP_TDB_TRANSACTION_START:
693                         try(tdb_transaction_start(tdb), op[file][i].ret);
694                         break;
695                 case OP_TDB_TRANSACTION_CANCEL:
696                         try(tdb_transaction_cancel(tdb), op[file][i].ret);
697                         break;
698                 case OP_TDB_TRANSACTION_COMMIT:
699                         try(tdb_transaction_commit(tdb), op[file][i].ret);
700                         break;
701                 case OP_TDB_TRAVERSE_READ_START:
702                         i = op_traverse(tdb, pre_fd, filename, file,
703                                         tdb_traverse_read, op, i);
704                         break;
705                 case OP_TDB_TRAVERSE_START:
706                         i = op_traverse(tdb, pre_fd, filename, file,
707                                         tdb_traverse, op, i);
708                         break;
709                 case OP_TDB_TRAVERSE:
710                         /* Terminate: we're in a traverse, and we've
711                          * done our ops. */
712                         return i;
713                 case OP_TDB_TRAVERSE_END:
714                         fail(filename[file], i+1, "unexpected end traverse");
715                 /* FIXME: These must be treated like traverse. */
716                 case OP_TDB_FIRSTKEY:
717                         if (!key_eq(tdb_firstkey(tdb), op[file][i].data))
718                                 fail(filename[file], i+1, "bad firstkey");
719                         break;
720                 case OP_TDB_NEXTKEY:
721                         if (!key_eq(tdb_nextkey(tdb, op[file][i].key),
722                                     op[file][i].data))
723                                 fail(filename[file], i+1, "bad nextkey");
724                         break;
725                 case OP_TDB_FETCH: {
726                         TDB_DATA f = tdb_fetch(tdb, op[file][i].key);
727                         if (!key_eq(f, op[file][i].data))
728                                 fail(filename[file], i+1, "bad fetch %u",
729                                      f.dsize);
730                         break;
731                 }
732                 case OP_TDB_DELETE:
733                         try(tdb_delete(tdb, op[file][i].key), op[file][i].ret);
734                         break;
735                 }
736                 do_post(filename, op, file, i);
737         }
738         return i;
739 }
740
741 /* tdbtorture, in particular, can do a tdb_close with a transaction in
742  * progress. */
743 static struct op *maybe_cancel_transaction(const char *filename,
744                                            struct op *op, unsigned int *num)
745 {
746         unsigned int start = op_transaction_start(op, *num);
747
748         if (start) {
749                 char *words[] = { "<unknown>", "tdb_close", NULL };
750                 add_op(filename, &op, *num, op[start].serial,
751                        OP_TDB_TRANSACTION_CANCEL);
752                 op_analyze_transaction(filename, op, *num, words);
753                 (*num)++;
754         }
755         return op;
756 }
757
758 static struct op *load_tracefile(const char *filename, unsigned int *num,
759                                  unsigned int *hashsize,
760                                  unsigned int *tdb_flags,
761                                  unsigned int *open_flags)
762 {
763         unsigned int i;
764         struct op *op = talloc_array(NULL, struct op, 1);
765         char **words;
766         char **lines;
767         char *file;
768
769         file = grab_file(NULL, filename, NULL);
770         if (!file)
771                 err(1, "Reading %s", filename);
772
773         lines = strsplit(file, file, "\n", NULL);
774         if (!lines[0])
775                 errx(1, "%s is empty", filename);
776
777         words = strsplit(lines, lines[0], " ", NULL);
778         if (!streq(words[1], "tdb_open"))
779                 fail(filename, 1, "does not start with tdb_open");
780
781         *hashsize = atoi(words[2]);
782         *tdb_flags = strtoul(words[3], NULL, 0);
783         *open_flags = strtoul(words[4], NULL, 0);
784
785         for (i = 1; lines[i]; i++) {
786                 const struct op_table *opt;
787
788                 words = strsplit(lines, lines[i], " ", NULL);
789                 if (!words[0] || !words[1])
790                         fail(filename, i+1, "Expected serial number and op");
791                
792                 opt = find_keyword(words[1], strlen(words[1]));
793                 if (!opt) {
794                         if (streq(words[1], "tdb_close")) {
795                                 if (lines[i+1])
796                                         fail(filename, i+2,
797                                              "lines after tdb_close");
798                                 *num = i;
799                                 talloc_free(lines);
800                                 return maybe_cancel_transaction(filename,
801                                                                 op, num);
802                         }
803                         fail(filename, i+1, "Unknown operation '%s'", words[1]);
804                 }
805
806                 add_op(filename, &op, i, atoi(words[0]), opt->type);
807                 opt->enhance_op(filename, op, i, words);
808         }
809
810         fprintf(stderr, "%s:%u:last operation is not tdb_close: incomplete?",
811               filename, i);
812         talloc_free(lines);
813         *num = i - 1;
814         return maybe_cancel_transaction(filename, op, num);
815 }
816
817 /* We remember all the keys we've ever seen, and who has them. */
818 struct key_user {
819         unsigned int file;
820         unsigned int op_num;
821 };
822
823 struct keyinfo {
824         TDB_DATA key;
825         unsigned int num_users;
826         struct key_user *user;
827 };
828
829 static const TDB_DATA must_not_exist;
830 static const TDB_DATA must_exist;
831 static const TDB_DATA not_exists_or_empty;
832
833 /* NULL means doesn't care if it exists or not, &must_exist means
834  * it must exist but we don't care what, &must_not_exist means it must
835  * not exist, otherwise the data it needs. */
836 static const TDB_DATA *needs(const struct op *op)
837 {
838         switch (op->op) {
839         /* FIXME: Pull forward deps, since we can deadlock */
840         case OP_TDB_CHAINLOCK:
841         case OP_TDB_CHAINLOCK_NONBLOCK:
842         case OP_TDB_CHAINLOCK_MARK:
843         case OP_TDB_CHAINLOCK_UNMARK:
844         case OP_TDB_CHAINUNLOCK:
845         case OP_TDB_CHAINLOCK_READ:
846         case OP_TDB_CHAINUNLOCK_READ:
847                 return NULL;
848
849         case OP_TDB_APPEND:
850                 if (op->append.pre.dsize == 0)
851                         return &not_exists_or_empty;
852                 return &op->append.pre;
853
854         case OP_TDB_STORE:
855                 if (op->flag == TDB_INSERT) {
856                         if (op->ret < 0)
857                                 return &must_exist;
858                         else
859                                 return &must_not_exist;
860                 } else if (op->flag == TDB_MODIFY) {
861                         if (op->ret < 0)
862                                 return &must_not_exist;
863                         else
864                                 return &must_exist;
865                 }
866                 /* No flags?  Don't care */
867                 return NULL;
868
869         case OP_TDB_EXISTS:
870                 if (op->ret == 1)
871                         return &must_exist;
872                 else
873                         return &must_not_exist;
874
875         case OP_TDB_PARSE_RECORD:
876                 if (op->ret < 0)
877                         return &must_not_exist;
878                 return &must_exist;
879
880         /* FIXME: handle these. */
881         case OP_TDB_WIPE_ALL:
882         case OP_TDB_FIRSTKEY:
883         case OP_TDB_NEXTKEY:
884         case OP_TDB_GET_SEQNUM:
885         case OP_TDB_TRAVERSE:
886         case OP_TDB_TRANSACTION_COMMIT:
887         case OP_TDB_TRANSACTION_CANCEL:
888         case OP_TDB_TRANSACTION_START:
889                 return NULL;
890
891         case OP_TDB_FETCH:
892                 if (!op->data.dptr)
893                         return &must_not_exist;
894                 return &op->data;
895
896         case OP_TDB_DELETE:
897                 if (op->ret < 0)
898                         return &must_not_exist;
899                 return &must_exist;
900
901         default:
902                 errx(1, "Unexpected op %i", op->op);
903         }
904         
905 }
906
907 static bool is_transaction(const struct op *op)
908 {
909         return op->op == OP_TDB_TRANSACTION_START;
910 }
911
912 /* What's the data after this op?  pre if nothing changed. */
913 static const TDB_DATA *gives(const TDB_DATA *key, const TDB_DATA *pre,
914                              const struct op *op)
915 {
916         if (is_transaction(op)) {
917                 unsigned int i;
918
919                 /* Cancelled transactions don't change anything. */
920                 if (op[op->group_len].op == OP_TDB_TRANSACTION_CANCEL)
921                         return pre;
922                 assert(op[op->group_len].op == OP_TDB_TRANSACTION_COMMIT);
923
924                 for (i = 1; i < op->group_len; i++) {
925                         /* This skips nested transactions, too */
926                         if (key_eq(op[i].key, *key))
927                                 pre = gives(key, pre, &op[i]);
928                 }
929                 return pre;
930         }
931
932         /* Failed ops don't change state of db. */
933         if (op->ret < 0)
934                 return pre;
935
936         if (op->op == OP_TDB_DELETE || op->op == OP_TDB_WIPE_ALL)
937                 return &tdb_null;
938
939         if (op->op == OP_TDB_APPEND)
940                 return &op->append.post;
941
942         if (op->op == OP_TDB_STORE)
943                 return &op->data;
944
945         return pre;
946 }
947
948 static bool in_transaction(const struct op op[], unsigned int i)
949 {
950         return op[i].group_start && is_transaction(&op[op[i].group_start]);
951 }
952
953 static bool is_traverse(const struct op *op)
954 {
955         return op->op == OP_TDB_TRAVERSE_START
956                 || op->op == OP_TDB_TRAVERSE_READ_START;
957 }
958
959 static bool in_traverse(const struct op op[], unsigned int i)
960 {
961         return op[i].group_start && is_traverse(&op[op[i].group_start]);
962 }
963
964 static struct keyinfo *hash_ops(struct op *op[], unsigned int num_ops[],
965                                 unsigned int num)
966 {
967         unsigned int i, j, h;
968         struct keyinfo *hash;
969
970         hash = talloc_zero_array(op[0], struct keyinfo, total_keys*2);
971         for (i = 0; i < num; i++) {
972                 for (j = 1; j < num_ops[i]; j++) {
973                         /* We can't do this on allocation, due to realloc. */
974                         list_head_init(&op[i][j].post);
975                         list_head_init(&op[i][j].pre);
976
977                         if (!op[i][j].key.dptr)
978                                 continue;
979
980                         h = hash_key(&op[i][j].key) % (total_keys * 2);
981                         while (!key_eq(hash[h].key, op[i][j].key)) {
982                                 if (!hash[h].key.dptr) {
983                                         hash[h].key = op[i][j].key;
984                                         break;
985                                 }
986                                 h = (h + 1) % (total_keys * 2);
987                         }
988                         /* Might as well save some memory if we can. */
989                         if (op[i][j].key.dptr != hash[h].key.dptr) {
990                                 talloc_free(op[i][j].key.dptr);
991                                 op[i][j].key.dptr = hash[h].key.dptr;
992                         }
993                         hash[h].user = talloc_realloc(hash, hash[h].user,
994                                                      struct key_user,
995                                                      hash[h].num_users+1);
996
997                         /* If it's in a transaction, it's the transaction which
998                          * matters from an analysis POV. */
999                         if (in_transaction(op[i], j)) {
1000                                 unsigned start = op[i][j].group_start;
1001
1002                                 /* Don't include twice. */
1003                                 if (hash[h].num_users
1004                                     && hash[h].user[hash[h].num_users-1].file
1005                                         == i
1006                                     && hash[h].user[hash[h].num_users-1].op_num
1007                                         == start)
1008                                         continue;
1009
1010                                 hash[h].user[hash[h].num_users].op_num = start;
1011                         } else
1012                                 hash[h].user[hash[h].num_users].op_num = j;
1013                         hash[h].user[hash[h].num_users].file = i;
1014                         hash[h].num_users++;
1015                 }
1016         }
1017
1018         return hash;
1019 }
1020
1021 static bool satisfies(const TDB_DATA *key, const TDB_DATA *data,
1022                       const struct op *op)
1023 {
1024         const TDB_DATA *need = NULL;
1025
1026         if (is_transaction(op)) {
1027                 unsigned int i;
1028
1029                 /* Look through for an op in this transaction which
1030                  * needs this key. */
1031                 for (i = 1; i < op->group_len; i++) {
1032                         if (key_eq(op[i].key, *key)) {
1033                                 need = needs(&op[i]);
1034                                 /* tdb_exists() is special: there might be
1035                                  * something in the transaction with more
1036                                  * specific requirements.  Other ops don't have
1037                                  * specific requirements (eg. store or delete),
1038                                  * but they change the value so we can't get
1039                                  * more information from future ops. */
1040                                 if (op[i].op != OP_TDB_EXISTS)
1041                                         break;
1042                         }
1043                 }
1044         } else
1045                 need = needs(op);
1046
1047         /* Don't need anything?  Cool. */
1048         if (!need)
1049                 return true;
1050
1051         /* This should be tdb_null or a real value. */
1052         assert(data != &must_exist);
1053         assert(data != &must_not_exist);
1054         assert(data != &not_exists_or_empty);
1055
1056         /* Must not exist?  data must not exist. */
1057         if (need == &must_not_exist)
1058                 return data == &tdb_null;
1059
1060         /* Must exist? */
1061         if (need == &must_exist)
1062                 return data != &tdb_null;
1063
1064         /* Either noexist or empty. */
1065         if (need == &not_exists_or_empty)
1066                 return data->dsize == 0;
1067
1068         /* Needs something specific. */
1069         return key_eq(*data, *need);
1070 }
1071
1072 static void move_to_front(struct key_user res[], unsigned off, unsigned elem)
1073 {
1074         if (elem != off) {
1075                 struct key_user tmp = res[elem];
1076                 memmove(res + off + 1, res + off, (elem - off)*sizeof(res[0]));
1077                 res[off] = tmp;
1078         }
1079 }
1080
1081 static void restore_to_pos(struct key_user res[], unsigned off, unsigned elem)
1082 {
1083         if (elem != off) {
1084                 struct key_user tmp = res[off];
1085                 memmove(res + off, res + off + 1, (elem - off)*sizeof(res[0]));
1086                 res[elem] = tmp;
1087         }
1088 }
1089
1090 static bool sort_deps(char *filename[], struct op *op[],
1091                       struct key_user res[],
1092                       unsigned off, unsigned num,
1093                       const TDB_DATA *key, const TDB_DATA *data,
1094                       unsigned num_files, unsigned fuzz)
1095 {
1096         unsigned int i, files_done;
1097         struct op *this_op;
1098         bool done[num_files];
1099
1100         /* None left?  We're sorted. */
1101         if (off == num)
1102                 return true;
1103
1104         /* Does this make serial numbers go backwards?  Allow a little fuzz. */
1105         if (off > 0) {
1106                 int serial1 = op[res[off-1].file][res[off-1].op_num].serial;
1107                 int serial2 = op[res[off].file][res[off].op_num].serial;
1108
1109                 if (serial1 - serial2 > (int)fuzz) {
1110 #if DEBUG_DEPS
1111                         printf("Serial jump too far (%u -> %u)\n",
1112                                serial1, serial2);
1113 #endif
1114                         return false;
1115                 }
1116         }
1117
1118         memset(done, 0, sizeof(done));
1119
1120         /* Since ops within a trace file are ordered, we just need to figure
1121          * out which file to try next.  Since we don't take into account
1122          * inter-key relationships (which exist by virtue of trace file order),
1123          * we minimize the chance of harm by trying to keep in serial order. */
1124         for (files_done = 0, i = off; i < num && files_done < num_files; i++) {
1125                 if (done[res[i].file])
1126                         continue;
1127
1128                 this_op = &op[res[i].file][res[i].op_num];
1129
1130                 /* Is what we have good enough for this op? */
1131                 if (satisfies(key, data, this_op)) {
1132                         move_to_front(res, off, i);
1133                         if (sort_deps(filename, op, res, off+1, num,
1134                                       key, gives(key, data, this_op),
1135                                       num_files, fuzz))
1136                                 return true;
1137                         restore_to_pos(res, off, i);
1138                 }
1139                 done[res[i].file] = true;
1140                 files_done++;
1141         }
1142
1143         /* No combination worked. */
1144         return false;
1145 }
1146
1147 static void check_dep_sorting(struct key_user user[], unsigned num_users,
1148                               unsigned num_files)
1149 {
1150 #if DEBUG_DEPS
1151         unsigned int i;
1152         unsigned minima[num_files];
1153
1154         memset(minima, 0, sizeof(minima));
1155         for (i = 0; i < num_users; i++) {
1156                 assert(minima[user[i].file] < user[i].op_num);
1157                 minima[user[i].file] = user[i].op_num;
1158         }
1159 #endif
1160 }
1161
1162 /* All these ops happen on the same key.  Which comes first?
1163  *
1164  * This can happen both because read ops or failed write ops don't
1165  * change serial number, and also due to race since we access the
1166  * number unlocked (the race can cause less detectable ordering problems,
1167  * in which case we'll deadlock and report: fix manually in that case).
1168  */
1169 static void figure_deps(char *filename[], struct op *op[],
1170                         const TDB_DATA *key, struct key_user user[],
1171                         unsigned num_users, unsigned num_files)
1172 {
1173         /* We assume database starts empty. */
1174         const struct TDB_DATA *data = &tdb_null;
1175         unsigned int fuzz;
1176
1177         /* We prefer to keep strict serial order if possible: it's the
1178          * most likely.  We get more lax if that fails. */
1179         for (fuzz = 0; fuzz < 100; fuzz = (fuzz + 1)*2) {
1180                 if (sort_deps(filename, op, user, 0, num_users, key, data,
1181                               num_files, fuzz))
1182                         break;
1183         }
1184
1185         if (fuzz >= 100)
1186                 fail(filename[user[0].file], user[0].op_num+1,
1187                      "Could not resolve inter-dependencies");
1188
1189         check_dep_sorting(user, num_users, num_files);
1190 }
1191
1192 static void sort_ops(struct keyinfo hash[], char *filename[], struct op *op[],
1193                      unsigned int num)
1194 {
1195         unsigned int h;
1196
1197         /* Gcc nexted function extension.  How cool is this? */
1198         int compare_serial(const void *_a, const void *_b)
1199         {
1200                 const struct key_user *a = _a, *b = _b;
1201
1202                 /* First, maintain order within any trace file. */
1203                 if (a->file == b->file)
1204                         return a->op_num - b->op_num;
1205
1206                 /* Otherwise, arrange by serial order. */
1207                 return op[a->file][a->op_num].serial
1208                         - op[b->file][b->op_num].serial;
1209         }
1210
1211         /* Now sort into serial order. */
1212         for (h = 0; h < total_keys * 2; h++) {
1213                 struct key_user *user = hash[h].user;
1214
1215                 qsort(user, hash[h].num_users, sizeof(user[0]), compare_serial);
1216                 figure_deps(filename, op, &hash[h].key, user, hash[h].num_users,
1217                             num);
1218         }
1219 }
1220
1221 static int destroy_depend(struct depend *dep)
1222 {
1223         list_del(&dep->pre_list);
1224         list_del(&dep->post_list);
1225         return 0;
1226 }
1227
1228 static void add_dependency(void *ctx,
1229                            struct op *op[],
1230                            char *filename[],
1231                            unsigned int needs_file,
1232                            unsigned int needs_opnum,
1233                            unsigned int satisfies_file,
1234                            unsigned int satisfies_opnum)
1235 {
1236         struct depend *dep;
1237
1238         /* We don't depend on ourselves. */
1239         if (needs_file == satisfies_file) {
1240                 assert(satisfies_opnum < needs_opnum);
1241                 return;
1242         }
1243
1244 #if DEBUG_DEPS
1245         printf("%s:%u: depends on %s:%u\n",
1246                filename[needs_file], needs_opnum+1,
1247                filename[satisfies_file], satisfies_opnum+1);
1248 #endif
1249
1250 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
1251         /* If something in a traverse depends on something in another
1252          * traverse/transaction, it creates a dependency between the
1253          * two groups. */
1254         if ((in_traverse(op[satisfies_file], satisfies_opnum)
1255              && op[needs_file][needs_opnum].group_start)
1256             || (in_traverse(op[needs_file], needs_opnum)
1257                 && op[satisfies_file][satisfies_opnum].group_start)) {
1258                 unsigned int sat;
1259
1260                 /* We are satisfied by end of group. */
1261                 sat = op[satisfies_file][satisfies_opnum].group_start;
1262                 satisfies_opnum = sat + op[satisfies_file][sat].group_len;
1263                 /* And we need that done by start of our group. */
1264                 needs_opnum = op[needs_file][needs_opnum].group_start;
1265         }
1266
1267         /* There is also this case:
1268          *  <traverse> <read foo> ...
1269          *  <transaction> ... </transaction> <create foo>
1270          * Where if we start the traverse then wait, we could block
1271          * the transaction and deadlock.
1272          *
1273          * We try to address this by ensuring that where seqnum indicates it's
1274          * possible, we wait for <create foo> before *starting* traverse.
1275          */
1276         else if (in_traverse(op[needs_file], needs_opnum)) {
1277                 struct op *need = &op[needs_file][needs_opnum];
1278                 if (op[needs_file][need->group_start].serial >
1279                     op[satisfies_file][satisfies_opnum].serial) {
1280                         needs_opnum = need->group_start;
1281                 }
1282         }
1283 #endif
1284
1285         /* If you depend on a transaction, you actually depend on it ending. */
1286         if (is_transaction(&op[satisfies_file][satisfies_opnum])) {
1287                 satisfies_opnum
1288                         += op[satisfies_file][satisfies_opnum].group_len;
1289 #if DEBUG_DEPS
1290                 printf("-> Actually end of transaction %s:%u\n",
1291                        filename[satisfies_file], satisfies_opnum+1);
1292 #endif
1293         } else
1294                 /* We should never create a dependency from middle of
1295                  * a transaction. */
1296                 assert(!in_transaction(op[satisfies_file], satisfies_opnum)
1297                        || op[satisfies_file][satisfies_opnum].op
1298                        == OP_TDB_TRANSACTION_COMMIT
1299                        || op[satisfies_file][satisfies_opnum].op
1300                        == OP_TDB_TRANSACTION_CANCEL);
1301
1302         assert(op[needs_file][needs_opnum].op != OP_TDB_TRAVERSE);
1303         assert(op[satisfies_file][satisfies_opnum].op != OP_TDB_TRAVERSE);
1304
1305         dep = talloc(ctx, struct depend);
1306         dep->needs_file = needs_file;
1307         dep->needs_opnum = needs_opnum;
1308         dep->satisfies_file = satisfies_file;
1309         dep->satisfies_opnum = satisfies_opnum;
1310         list_add(&op[satisfies_file][satisfies_opnum].post, &dep->post_list);
1311         list_add(&op[needs_file][needs_opnum].pre, &dep->pre_list);
1312         talloc_set_destructor(dep, destroy_depend);
1313 }
1314
1315 static bool changes_db(const TDB_DATA *key, const struct op *op)
1316 {
1317         return gives(key, NULL, op) != NULL;
1318 }
1319
1320 static void depend_on_previous(struct op *op[],
1321                                char *filename[],
1322                                unsigned int num,
1323                                struct key_user user[],
1324                                unsigned int i,
1325                                int prev)
1326 {
1327         bool deps[num];
1328         int j;
1329
1330         if (i == 0)
1331                 return;
1332
1333         if (prev == i - 1) {
1334                 /* Just depend on previous. */
1335                 add_dependency(NULL, op, filename,
1336                                user[i].file, user[i].op_num,
1337                                user[prev].file, user[prev].op_num);
1338                 return;
1339         }
1340
1341         /* We have to wait for the readers.  Find last one in *each* file. */
1342         memset(deps, 0, sizeof(deps));
1343         deps[user[i].file] = true;
1344         for (j = i - 1; j > prev; j--) {
1345                 if (!deps[user[j].file]) {
1346                         add_dependency(NULL, op, filename,
1347                                        user[i].file, user[i].op_num,
1348                                        user[j].file, user[j].op_num);
1349                         deps[user[j].file] = true;
1350                 }
1351         }
1352 }
1353
1354 /* This is simple, but not complete.  We don't take into account
1355  * indirect dependencies. */
1356 static void optimize_dependencies(struct op *op[], unsigned int num_ops[],
1357                                   unsigned int num)
1358 {
1359         unsigned int i, j;
1360
1361         /* There can only be one real dependency on each file */
1362         for (i = 0; i < num; i++) {
1363                 for (j = 1; j < num_ops[i]; j++) {
1364                         struct depend *dep, *next;
1365                         struct depend *prev[num];
1366
1367                         memset(prev, 0, sizeof(prev));
1368
1369                         list_for_each_safe(&op[i][j].pre, dep, next, pre_list) {
1370                                 if (!prev[dep->satisfies_file]) {
1371                                         prev[dep->satisfies_file] = dep;
1372                                         continue;
1373                                 }
1374                                 if (prev[dep->satisfies_file]->satisfies_opnum
1375                                     < dep->satisfies_opnum) {
1376                                         talloc_free(prev[dep->satisfies_file]);
1377                                         prev[dep->satisfies_file] = dep;
1378                                 } else
1379                                         talloc_free(dep);
1380                         }
1381                 }
1382         }
1383
1384         for (i = 0; i < num; i++) {
1385                 int deps[num];
1386
1387                 for (j = 0; j < num; j++)
1388                         deps[j] = -1;
1389
1390                 for (j = 1; j < num_ops[i]; j++) {
1391                         struct depend *dep, *next;
1392
1393                         list_for_each_safe(&op[i][j].pre, dep, next, pre_list) {
1394                                 if (deps[dep->satisfies_file]
1395                                     >= (int)dep->satisfies_opnum)
1396                                         talloc_free(dep);
1397                                 else
1398                                         deps[dep->satisfies_file]
1399                                                 = dep->satisfies_opnum;
1400                         }
1401                 }
1402         }
1403 }
1404
1405 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
1406 struct traverse_dep {
1407         unsigned int file;
1408         unsigned int op_num;
1409 };
1410
1411 /* Force an order among the traversals, so they don't deadlock (as much) */
1412 static void make_traverse_depends(char *filename[],
1413                                   struct op *op[], unsigned int num_ops[],
1414                                   unsigned int num)
1415 {
1416         unsigned int i, num_traversals = 0;
1417         int j;
1418         struct traverse_dep *dep;
1419
1420         /* Sort by which one runs first. */
1421         int compare_traverse_dep(const void *_a, const void *_b)
1422         {
1423                 const struct traverse_dep *ta = _a, *tb = _b;
1424                 const struct op *a = &op[ta->file][ta->op_num],
1425                         *b = &op[tb->file][tb->op_num];
1426
1427                 if (a->serial != b->serial)
1428                         return a->serial - b->serial;
1429
1430                 /* If they have same serial, it means one didn't make any
1431                  * changes.  Thus sort by end in that case. */
1432                 return a[a->group_len].serial - b[b->group_len].serial;
1433         }
1434
1435         dep = talloc_array(NULL, struct traverse_dep, 1);
1436
1437         /* Count them. */
1438         for (i = 0; i < num; i++) {
1439                 for (j = 1; j < num_ops[i]; j++) {
1440                         /* Traverse start (ignore those in
1441                          * transactions; they're already covered by
1442                          * transaction dependencies). */
1443                         if (is_traverse(&op[i][j])
1444                             && !in_transaction(op[i], j)) {
1445                                 dep = talloc_realloc(NULL, dep,
1446                                                      struct traverse_dep,
1447                                                      num_traversals+1);
1448                                 dep[num_traversals].file = i;
1449                                 dep[num_traversals].op_num = j;
1450                                 num_traversals++;
1451                         }
1452                 }
1453         }
1454         qsort(dep, num_traversals, sizeof(dep[0]), compare_traverse_dep);
1455
1456         for (i = 1; i < num_traversals; i++) {
1457                 const struct op *prev = &op[dep[i-1].file][dep[i-1].op_num];
1458
1459                 /* Only make dependency if it's clear. */
1460                 if (compare_traverse_dep(&dep[i], &dep[i-1])) {
1461                         /* i depends on end of traverse i-1. */
1462                         add_dependency(NULL, op, filename,
1463                                        dep[i].file, dep[i].op_num,
1464                                        dep[i-1].file, dep[i-1].op_num
1465                                        + prev->group_len);
1466                 }
1467         }
1468         talloc_free(dep);
1469 }
1470 #endif
1471
1472 static void derive_dependencies(char *filename[],
1473                                 struct op *op[], unsigned int num_ops[],
1474                                 unsigned int num)
1475 {
1476         struct keyinfo *hash;
1477         unsigned int h, i;
1478
1479         /* Create hash table for faster key lookup. */
1480         hash = hash_ops(op, num_ops, num);
1481
1482         /* Sort them by serial number. */
1483         sort_ops(hash, filename, op, num);
1484
1485         /* Create dependencies back to the last change, rather than
1486          * creating false dependencies by naively making each one
1487          * depend on the previous.  This has two purposes: it makes
1488          * later optimization simpler, and it also avoids deadlock with
1489          * same sequence number ops inside traversals (if one
1490          * traversal doesn't write anything, two ops can have the same
1491          * sequence number yet we can create a traversal dependency
1492          * the other way). */
1493         for (h = 0; h < total_keys * 2; h++) {
1494                 int prev = -1;
1495
1496                 if (hash[h].num_users < 2)
1497                         continue;
1498
1499                 for (i = 0; i < hash[h].num_users; i++) {
1500                         if (changes_db(&hash[h].key, &op[hash[h].user[i].file]
1501                                        [hash[h].user[i].op_num])) {
1502                                 depend_on_previous(op, filename, num,
1503                                                    hash[h].user, i, prev);
1504                                 prev = i;
1505                         } else if (prev >= 0)
1506                                 add_dependency(hash, op, filename,
1507                                                hash[h].user[i].file,
1508                                                hash[h].user[i].op_num,
1509                                                hash[h].user[prev].file,
1510                                                hash[h].user[prev].op_num);
1511                 }
1512         }
1513
1514 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
1515         make_traverse_depends(filename, op, num_ops, num);
1516 #endif
1517
1518         optimize_dependencies(op, num_ops, num);
1519 }
1520
1521 int main(int argc, char *argv[])
1522 {
1523         struct timeval start, end;
1524         unsigned int i, num_ops[argc], hashsize[argc], tdb_flags[argc], open_flags[argc];
1525         struct op *op[argc];
1526         int fds[2];
1527         char c;
1528         bool ok = true;
1529
1530         if (argc < 3)
1531                 errx(1, "Usage: %s <tdbfile> <tracefile>...", argv[0]);
1532
1533         pipes = talloc_array(NULL, struct pipe, argc - 2);
1534         for (i = 0; i < argc - 2; i++) {
1535                 printf("Loading tracefile %s...", argv[2+i]);
1536                 fflush(stdout);
1537                 op[i] = load_tracefile(argv[2+i], &num_ops[i], &hashsize[i],
1538                                        &tdb_flags[i], &open_flags[i]);
1539                 if (pipe(pipes[i].fd) != 0)
1540                         err(1, "creating pipe");
1541                 printf("done\n");
1542         }
1543
1544         printf("Calculating inter-dependencies...");
1545         fflush(stdout);
1546         derive_dependencies(argv+2, op, num_ops, i);
1547         printf("done\n");
1548
1549         /* Don't fork for single arg case: simple debugging. */
1550         if (argc == 3) {
1551                 struct tdb_context *tdb;
1552                 tdb = tdb_open_ex(argv[1], hashsize[0], tdb_flags[0]|TDB_NOSYNC,
1553                                   open_flags[0], 0600, NULL, hash_key);
1554                 printf("Single threaded run...");
1555                 fflush(stdout);
1556
1557                 run_ops(tdb, pipes[0].fd[0], argv+2, op, 0, 1, num_ops[0],
1558                         false);
1559                 check_deps(argv[2], op[0], num_ops[0]);
1560
1561                 printf("done\n");
1562                 exit(0);
1563         }
1564
1565         if (pipe(fds) != 0)
1566                 err(1, "creating pipe");
1567
1568         for (i = 0; i < argc - 2; i++) {
1569                 struct tdb_context *tdb;
1570
1571                 switch (fork()) {
1572                 case -1:
1573                         err(1, "fork failed");
1574                 case 0:
1575                         close(fds[1]);
1576                         tdb = tdb_open_ex(argv[1], hashsize[i],
1577                                           tdb_flags[i]|TDB_NOSYNC,
1578                                           open_flags[i], 0600, NULL, hash_key);
1579                         if (!tdb)
1580                                 err(1, "Opening tdb %s", argv[1]);
1581
1582                         /* This catches parent exiting. */
1583                         if (read(fds[0], &c, 1) != 1)
1584                                 exit(1);
1585                         run_ops(tdb, pipes[i].fd[0], argv+2, op, i, 1,
1586                                 num_ops[i], false);
1587                         check_deps(argv[2+i], op[i], num_ops[i]);
1588                         exit(0);
1589                 default:
1590                         break;
1591                 }
1592         }
1593
1594         /* Let everything settle. */
1595         sleep(1);
1596
1597         printf("Starting run...");
1598         fflush(stdout);
1599         gettimeofday(&start, NULL);
1600         /* Tell them all to go!  Any write of sufficient length will do. */
1601         if (write(fds[1], hashsize, i) != i)
1602                 err(1, "Writing to wakeup pipe");
1603
1604         for (i = 0; i < argc - 2; i++) {
1605                 int status;
1606                 wait(&status);
1607                 if (!WIFEXITED(status)) {
1608                         warnx("Child died with signal %i", WTERMSIG(status));
1609                         ok = false;
1610                 } else if (WEXITSTATUS(status) != 0)
1611                         /* Assume child spat out error. */
1612                         ok = false;
1613         }
1614         if (!ok)
1615                 exit(1);
1616
1617         gettimeofday(&end, NULL);
1618         printf("done\n");
1619
1620         end.tv_sec -= start.tv_sec;
1621         printf("Time replaying: %lu usec\n",
1622                end.tv_sec * 1000000UL + (end.tv_usec - start.tv_usec));
1623         
1624         exit(0);
1625 }