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