]> git.ozlabs.org Git - ccan/blob - ccan/tdb/tools/replay_trace.c
Slightly more sophisticated dependency generation: fixes traverse interaction.
[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 list;
452         unsigned int file;
453         unsigned int op;
454 };
455
456 struct depend_xmit {
457         unsigned int dst_op;
458         unsigned int src_file, src_op;
459 };
460
461 static void remove_matching_dep(struct list_head *deps,
462                                 unsigned int file, unsigned int op)
463 {
464         struct depend *dep;
465
466         list_for_each(deps, dep, list) {
467                 if (dep->file == file && dep->op == op) {
468                         list_del(&dep->list);
469                         return;
470                 }
471         }
472         errx(1, "Failed to find depend on file %u line %u\n", file, op+1);
473 }
474
475 static void check_deps(const char *filename, struct op op[], unsigned int num)
476 {
477 #ifdef DEBUG_DEPS
478         unsigned int i;
479
480         for (i = 1; i < num; i++)
481                 if (!list_empty(&op[i].pre))
482                         fail(filename, i+1, "Still has dependencies");
483 #endif
484 }
485
486 static void dump_pre(char *filename[], unsigned int file,
487                      struct op op[], unsigned int i)
488 {
489         struct depend *dep;
490
491         printf("%s:%u still waiting for:\n", filename[file], i+1);
492         list_for_each(&op[i].pre, dep, list)
493                 printf("    %s:%u\n", filename[dep->file], dep->op+1);
494         check_deps(filename[file], op, i);
495 }
496
497 static void do_pre(char *filename[], unsigned int file, int pre_fd,
498                    struct op op[], unsigned int i)
499 {
500         while (!list_empty(&op[i].pre)) {
501                 struct depend_xmit dep;
502
503 #if DEBUG_DEPS
504                 printf("%s:%u:waiting for pre\n", filename[file], i+1);
505                 fflush(stdout);
506 #endif
507                 alarm(10);
508                 while (read(pre_fd, &dep, sizeof(dep)) != sizeof(dep)) {
509                         if (errno == EINTR) {
510                                 dump_pre(filename, file, op, i);
511                                 exit(1);
512                         } else
513                                 errx(1, "Reading from pipe");
514                 }
515                 alarm(0);
516
517 #if DEBUG_DEPS
518                 printf("%s:%u:got pre %u from %s:%u\n", filename[file], i+1,
519                        dep.dst_op+1, filename[dep.src_file], dep.src_op+1);
520                 fflush(stdout);
521 #endif
522                 /* This could be any op, not just this one. */
523                 remove_matching_dep(&op[dep.dst_op].pre,
524                                     dep.src_file, dep.src_op);
525         }
526 }
527
528 static void do_post(char *filename[], unsigned int file,
529                     const struct op op[], unsigned int i)
530 {
531         struct depend *dep;
532
533         list_for_each(&op[i].post, dep, list) {
534                 struct depend_xmit dx;
535
536                 dx.src_file = file;
537                 dx.src_op = i;
538                 dx.dst_op = dep->op;
539 #if DEBUG_DEPS
540                 printf("%s:%u:sending to file %s:%u\n", filename[file], i+1,
541                        filename[dep->file], dep->op+1);
542 #endif
543                 if (write(pipes[dep->file].fd[1], &dx, sizeof(dx))
544                     != sizeof(dx))
545                         err(1, "%s:%u failed to tell file %s",
546                             filename[file], i+1, filename[dep->file]);
547         }
548 }
549
550 static int get_len(TDB_DATA key, TDB_DATA data, void *private_data)
551 {
552         return data.dsize;
553 }
554
555 static unsigned run_ops(struct tdb_context *tdb,
556                         int pre_fd,
557                         char *filename[],
558                         unsigned int file,
559                         struct op op[],
560                         unsigned int start, unsigned int stop);
561
562 struct traverse_info {
563         struct op *op;
564         char **filename;
565         unsigned file;
566         int pre_fd;
567         unsigned int start;
568         unsigned int i;
569 };
570
571 /* Trivial case: do whatever they did for this key. */
572 static int trivial_traverse(struct tdb_context *tdb,
573                             TDB_DATA key, TDB_DATA data,
574                             void *_tinfo)
575 {
576         struct traverse_info *tinfo = _tinfo;
577         struct traverse *trav = tinfo->op[tinfo->start].trav;
578         unsigned int h = hash_key(&key) % (trav->num * 2);
579
580         while (trav->hash[h].index) {
581                 if (key_eq(trav->hash[h].key, key)) {
582                         run_ops(tdb, tinfo->pre_fd, tinfo->filename,
583                                 tinfo->file, tinfo->op, trav->hash[h].index,
584                                 trav->end);
585                         tinfo->i++;
586                         return 0;
587                 }
588                 h = (h + 1) % (trav->num * 2);
589         }
590         fail(tinfo->filename[tinfo->file], tinfo->start + 1,
591              "unexpected traverse key");
592 }
593
594 /* More complex.  Just do whatever's they did at the n'th entry. */
595 static int nontrivial_traverse(struct tdb_context *tdb,
596                                TDB_DATA key, TDB_DATA data,
597                                void *_tinfo)
598 {
599         struct traverse_info *tinfo = _tinfo;
600         struct traverse *trav = tinfo->op[tinfo->start].trav;
601
602         if (tinfo->i == trav->end) {
603                 /* This can happen if traverse expects to be empty. */
604                 if (tinfo->start + 1 == trav->end)
605                         return 1;
606                 fail(tinfo->filename[tinfo->file], tinfo->start + 1,
607                      "traverse did not terminate");
608         }
609
610         if (tinfo->op[tinfo->i].op != OP_TDB_TRAVERSE)
611                 fail(tinfo->filename[tinfo->file], tinfo->start + 1,
612                      "%s:%u:traverse terminated early");
613
614         /* Run any normal ops. */
615         tinfo->i = run_ops(tdb, tinfo->pre_fd, tinfo->filename, tinfo->file,
616                            tinfo->op, tinfo->i+1, trav->end);
617
618         if (tinfo->i == trav->end)
619                 return 1;
620
621         return 0;
622 }
623
624 static unsigned op_traverse(struct tdb_context *tdb,
625                             int pre_fd,
626                             char *filename[],
627                             unsigned int file,
628                             int (*traversefn)(struct tdb_context *,
629                                               tdb_traverse_func, void *),
630                             struct op op[],
631                             unsigned int start)
632 {
633         struct traverse *trav = op[start].trav;
634         struct traverse_info tinfo = { op, filename, file, pre_fd,
635                                        start, start+1 };
636
637         /* Trivial case. */
638         if (trav->hash) {
639                 int ret = traversefn(tdb, trivial_traverse, &tinfo);
640                 if (ret != trav->num)
641                         fail(filename[file], start+1,
642                              "short traversal %i", ret);
643                 return trav->end;
644         }
645
646         traversefn(tdb, nontrivial_traverse, &tinfo);
647
648         /* Traversing in wrong order can have strange effects: eg. if
649          * original traverse went A (delete A), B, we might do B
650          * (delete A).  So if we have ops left over, we do it now. */
651         while (tinfo.i != trav->end) {
652                 if (op[tinfo.i].op == OP_TDB_TRAVERSE)
653                         tinfo.i++;
654                 else
655                         tinfo.i = run_ops(tdb, pre_fd, filename, file, op,
656                                           tinfo.i, trav->end);
657         }
658
659         return trav->end;
660 }
661
662 static void break_out(int sig)
663 {
664 }
665
666 static __attribute__((noinline))
667 unsigned run_ops(struct tdb_context *tdb,
668                  int pre_fd,
669                  char *filename[],
670                  unsigned int file,
671                  struct op op[], unsigned int start, unsigned int stop)
672 {
673         unsigned int i;
674         struct sigaction sa;
675
676         sa.sa_handler = break_out;
677         sa.sa_flags = 0;
678
679         sigaction(SIGALRM, &sa, NULL);
680         for (i = start; i < stop; i++) {
681                 do_pre(filename, file, pre_fd, op, i);
682
683                 switch (op[i].op) {
684                 case OP_TDB_LOCKALL:
685                         try(tdb_lockall(tdb), op[i].ret);
686                         break;
687                 case OP_TDB_LOCKALL_MARK:
688                         try(tdb_lockall_mark(tdb), op[i].ret);
689                         break;
690                 case OP_TDB_LOCKALL_UNMARK:
691                         try(tdb_lockall_unmark(tdb), op[i].ret);
692                         break;
693                 case OP_TDB_LOCKALL_NONBLOCK:
694                         unreliable(tdb_lockall_nonblock(tdb), op[i].ret,
695                                    tdb_lockall(tdb), tdb_unlockall(tdb));
696                         break;
697                 case OP_TDB_UNLOCKALL:
698                         try(tdb_unlockall(tdb), op[i].ret);
699                         break;
700                 case OP_TDB_LOCKALL_READ:
701                         try(tdb_lockall_read(tdb), op[i].ret);
702                         break;
703                 case OP_TDB_LOCKALL_READ_NONBLOCK:
704                         unreliable(tdb_lockall_read_nonblock(tdb), op[i].ret,
705                                    tdb_lockall_read(tdb),
706                                    tdb_unlockall_read(tdb));
707                         break;
708                 case OP_TDB_UNLOCKALL_READ:
709                         try(tdb_unlockall_read(tdb), op[i].ret);
710                         break;
711                 case OP_TDB_CHAINLOCK:
712                         try(tdb_chainlock(tdb, op[i].key), op[i].ret);
713                         break;
714                 case OP_TDB_CHAINLOCK_NONBLOCK:
715                         unreliable(tdb_chainlock_nonblock(tdb, op[i].key),
716                                    op[i].ret,
717                                    tdb_chainlock(tdb, op[i].key),
718                                    tdb_chainunlock(tdb, op[i].key));
719                         break;
720                 case OP_TDB_CHAINLOCK_MARK:
721                         try(tdb_chainlock_mark(tdb, op[i].key), op[i].ret);
722                         break;
723                 case OP_TDB_CHAINLOCK_UNMARK:
724                         try(tdb_chainlock_unmark(tdb, op[i].key), op[i].ret);
725                         break;
726                 case OP_TDB_CHAINUNLOCK:
727                         try(tdb_chainunlock(tdb, op[i].key), op[i].ret);
728                         break;
729                 case OP_TDB_CHAINLOCK_READ:
730                         try(tdb_chainlock_read(tdb, op[i].key), op[i].ret);
731                         break;
732                 case OP_TDB_CHAINUNLOCK_READ:
733                         try(tdb_chainunlock_read(tdb, op[i].key), op[i].ret);
734                         break;
735                 case OP_TDB_PARSE_RECORD:
736                         try(tdb_parse_record(tdb, op[i].key, get_len, NULL),
737                             op[i].ret);
738                         break;
739                 case OP_TDB_EXISTS:
740                         try(tdb_exists(tdb, op[i].key), op[i].ret);
741                         break;
742                 case OP_TDB_STORE:
743                         try(tdb_store(tdb, op[i].key, op[i].data, op[i].flag),
744                             op[i].ret);
745                         break;
746                 case OP_TDB_APPEND:
747                         try(tdb_append(tdb, op[i].key, op[i].data), op[i].ret);
748                         break;
749                 case OP_TDB_GET_SEQNUM:
750                         try(tdb_get_seqnum(tdb), op[i].ret);
751                         break;
752                 case OP_TDB_WIPE_ALL:
753                         try(tdb_wipe_all(tdb), op[i].ret);
754                         break;
755                 case OP_TDB_TRANSACTION_START:
756                         try(tdb_transaction_start(tdb), op[i].ret);
757                         break;
758                 case OP_TDB_TRANSACTION_CANCEL:
759                         try(tdb_transaction_cancel(tdb), op[i].ret);
760                         break;
761                 case OP_TDB_TRANSACTION_COMMIT:
762                         try(tdb_transaction_commit(tdb), op[i].ret);
763                         break;
764                 case OP_TDB_TRAVERSE_READ_START:
765                         i = op_traverse(tdb, pre_fd, filename, file,
766                                         tdb_traverse_read, op, i);
767                         break;
768                 case OP_TDB_TRAVERSE_START:
769                         i = op_traverse(tdb, pre_fd, filename, file,
770                                         tdb_traverse, op, i);
771                         break;
772                 case OP_TDB_TRAVERSE:
773                         /* Terminate: we're in a traverse, and we've
774                          * done our ops. */
775                         return i;
776                 case OP_TDB_TRAVERSE_END:
777                         fail(filename[file], i+1, "unepxected end traverse");
778                 /* FIXME: These must be treated like traverse. */
779                 case OP_TDB_FIRSTKEY:
780                         if (!key_eq(tdb_firstkey(tdb), op[i].data))
781                                 fail(filename[file], i+1, "bad firstkey");
782                         break;
783                 case OP_TDB_NEXTKEY:
784                         if (!key_eq(tdb_nextkey(tdb, op[i].key), op[i].data))
785                                 fail(filename[file], i+1, "bad nextkey");
786                         break;
787                 case OP_TDB_FETCH: {
788                         TDB_DATA f = tdb_fetch(tdb, op[i].key);
789                         if (!key_eq(f, op[i].data))
790                                 fail(filename[file], i+1, "bad fetch %u",
791                                      f.dsize);
792                         break;
793                 }
794                 case OP_TDB_DELETE:
795                         try(tdb_delete(tdb, op[i].key), op[i].ret);
796                         break;
797                 }
798                 do_post(filename, file, op, i);
799         }
800         return i;
801 }
802
803 static struct op *load_tracefile(const char *filename, unsigned int *num,
804                                  unsigned int *hashsize,
805                                  unsigned int *tdb_flags,
806                                  unsigned int *open_flags)
807 {
808         unsigned int i;
809         struct op *op = talloc_array(NULL, struct op, 1);
810         char **words;
811         char **lines;
812         char *file;
813
814         file = grab_file(NULL, filename, NULL);
815         if (!file)
816                 err(1, "Reading %s", filename);
817
818         lines = strsplit(file, file, "\n", NULL);
819         if (!lines[0])
820                 errx(1, "%s is empty", filename);
821
822         words = strsplit(lines, lines[0], " ", NULL);
823         if (!streq(words[1], "tdb_open"))
824                 fail(filename, 1, "does not start with tdb_open");
825
826         *hashsize = atoi(words[2]);
827         *tdb_flags = strtoul(words[3], NULL, 0);
828         *open_flags = strtoul(words[4], NULL, 0);
829
830         for (i = 1; lines[i]; i++) {
831                 const struct op_table *opt;
832
833                 words = strsplit(lines, lines[i], " ", NULL);
834                 if (!words[0] || !words[1])
835                         fail(filename, i+1, "Expected serial number and op");
836                
837                 opt = find_keyword(words[1], strlen(words[1]));
838                 if (!opt) {
839                         if (streq(words[1], "tdb_close")) {
840                                 if (lines[i+1])
841                                         fail(filename, i+2,
842                                              "lines after tdb_close");
843                                 *num = i;
844                                 talloc_free(lines);
845                                 return op;
846                         }
847                         fail(filename, i+1, "Unknown operation '%s'", words[1]);
848                 }
849
850                 add_op(filename, &op, i, atoi(words[0]), opt->type);
851                 opt->enhance_op(filename, op, i, words);
852         }
853
854         fprintf(stderr, "%s:%u:last operation is not tdb_close: incomplete?",
855               filename, i);
856         talloc_free(lines);
857         *num = i - 1;
858         return op;
859 }
860
861 /* We remember all the keys we've ever seen, and who has them. */
862 struct key_user {
863         unsigned int file;
864         unsigned int op_num;
865 };
866
867 struct keyinfo {
868         TDB_DATA key;
869         unsigned int num_users;
870         struct key_user *user;
871 };
872
873 static const TDB_DATA must_not_exist;
874 static const TDB_DATA must_exist;
875 static const TDB_DATA not_exists_or_empty;
876
877 /* NULL means doesn't care if it exists or not, &must_exist means
878  * it must exist but we don't care what, &must_not_exist means it must
879  * not exist, otherwise the data it needs. */
880 static const TDB_DATA *needs(const struct op *op)
881 {
882         switch (op->op) {
883         /* FIXME: Pull forward deps, since we can deadlock */
884         case OP_TDB_CHAINLOCK:
885         case OP_TDB_CHAINLOCK_NONBLOCK:
886         case OP_TDB_CHAINLOCK_MARK:
887         case OP_TDB_CHAINLOCK_UNMARK:
888         case OP_TDB_CHAINUNLOCK:
889         case OP_TDB_CHAINLOCK_READ:
890         case OP_TDB_CHAINUNLOCK_READ:
891                 return NULL;
892
893         case OP_TDB_APPEND:
894                 if (op->append.pre.dsize == 0)
895                         return &not_exists_or_empty;
896                 return &op->append.pre;
897
898         case OP_TDB_STORE:
899                 if (op->flag == TDB_INSERT) {
900                         if (op->ret < 0)
901                                 return &must_exist;
902                         else
903                                 return &must_not_exist;
904                 } else if (op->flag == TDB_MODIFY) {
905                         if (op->ret < 0)
906                                 return &must_not_exist;
907                         else
908                                 return &must_exist;
909                 }
910                 /* No flags?  Don't care */
911                 return NULL;
912
913         case OP_TDB_EXISTS:
914                 if (op->ret == 1)
915                         return &must_exist;
916                 else
917                         return &must_not_exist;
918
919         case OP_TDB_PARSE_RECORD:
920                 if (op->ret < 0)
921                         return &must_not_exist;
922                 return &must_exist;
923
924         /* FIXME: handle these. */
925         case OP_TDB_WIPE_ALL:
926         case OP_TDB_FIRSTKEY:
927         case OP_TDB_NEXTKEY:
928         case OP_TDB_GET_SEQNUM:
929         case OP_TDB_TRAVERSE:
930         case OP_TDB_TRANSACTION_COMMIT:
931         case OP_TDB_TRANSACTION_CANCEL:
932         case OP_TDB_TRANSACTION_START:
933                 return NULL;
934
935         case OP_TDB_FETCH:
936                 if (!op->data.dptr)
937                         return &must_not_exist;
938                 return &op->data;
939
940         case OP_TDB_DELETE:
941                 if (op->ret < 0)
942                         return &must_not_exist;
943                 return &must_exist;
944
945         default:
946                 errx(1, "Unexpected op %i", op->op);
947         }
948         
949 }
950
951 /* What's the data after this op?  pre if nothing changed. */
952 static const TDB_DATA *gives(const struct op *op, const TDB_DATA *pre)
953 {
954         /* Failed ops don't change state of db. */
955         if (op->ret < 0)
956                 return pre;
957
958         if (op->op == OP_TDB_DELETE || op->op == OP_TDB_WIPE_ALL)
959                 return &tdb_null;
960
961         if (op->op == OP_TDB_APPEND)
962                 return &op->append.post;
963
964         if (op->op == OP_TDB_STORE)
965                 return &op->data;
966
967         return pre;
968 }
969
970 static struct keyinfo *hash_ops(struct op *op[], unsigned int num_ops[],
971                                 unsigned int num)
972 {
973         unsigned int i, j, h;
974         struct keyinfo *hash;
975
976         hash = talloc_zero_array(op[0], struct keyinfo, total_keys*2);
977         for (i = 0; i < num; i++) {
978                 for (j = 1; j < num_ops[i]; j++) {
979                         /* We can't do this on allocation, due to realloc. */
980                         list_head_init(&op[i][j].post);
981                         list_head_init(&op[i][j].pre);
982
983                         if (!op[i][j].key.dptr)
984                                 continue;
985
986                         /* We don't wait for traverse keys */
987                         /* FIXME: We should, for trivial traversals. */
988                         if (op[i][j].op == OP_TDB_TRAVERSE)
989                                 continue;
990
991                         h = hash_key(&op[i][j].key) % (total_keys * 2);
992                         while (!key_eq(hash[h].key, op[i][j].key)) {
993                                 if (!hash[h].key.dptr) {
994                                         hash[h].key = op[i][j].key;
995                                         break;
996                                 }
997                                 h = (h + 1) % (total_keys * 2);
998                         }
999                         /* Might as well save some memory if we can. */
1000                         if (op[i][j].key.dptr != hash[h].key.dptr) {
1001                                 talloc_free(op[i][j].key.dptr);
1002                                 op[i][j].key.dptr = hash[h].key.dptr;
1003                         }
1004                         hash[h].user = talloc_realloc(hash, hash[h].user,
1005                                                      struct key_user,
1006                                                      hash[h].num_users+1);
1007                         hash[h].user[hash[h].num_users].op_num = j;
1008                         hash[h].user[hash[h].num_users].file = i;
1009                         hash[h].num_users++;
1010                 }
1011         }
1012
1013         return hash;
1014 }
1015
1016 static bool satisfies(const TDB_DATA *data, const TDB_DATA *need)
1017 {
1018         /* Don't need anything?  Cool. */
1019         if (!need)
1020                 return true;
1021
1022         /* This should be tdb_null or a real value. */
1023         assert(data != &must_exist);
1024         assert(data != &must_not_exist);
1025         assert(data != &not_exists_or_empty);
1026
1027         /* must_not_exist == must_not_exist, must_exist == must_exist, or
1028            not_exists_or_empty == not_exists_or_empty. */
1029         if (data->dsize == need->dsize && data->dptr == need->dptr)
1030                 return true;
1031
1032         /* Must not exist?  data must not exist. */
1033         if (need == &must_not_exist)
1034                 return data->dptr == NULL;
1035
1036         /* Must exist? */
1037         if (need == &must_exist)
1038                 return data->dptr != NULL;
1039
1040         /* Either noexist or empty. */
1041         if (need == &not_exists_or_empty)
1042                 return data->dsize == 0;
1043
1044         /* Needs something specific. */
1045         return key_eq(*data, *need);
1046 }
1047
1048 static bool sort_deps(char *filename[], struct op *op[],
1049                       struct key_user res[], unsigned num,
1050                       const TDB_DATA *data)
1051 {
1052         unsigned int i;
1053
1054         /* Nothing left?  We're sorted. */
1055         if (num == 0)
1056                 return true;
1057
1058         for (i = 0; i < num; i++) {
1059                 struct op *this_op = &op[res[i].file][res[i].op_num];
1060
1061                 /* Is what we have good enough for this op? */
1062                 if (satisfies(data, needs(this_op))) {
1063                         /* Try this one next. */
1064                         struct key_user tmp = res[0];
1065                         res[0] = res[i];
1066                         res[i] = tmp;
1067                         if (sort_deps(filename, op, res+1, num-1,
1068                                       gives(this_op, data)))
1069                                 return true;
1070                 }
1071         }
1072         /* No combination worked. */
1073         return false;
1074 }
1075
1076 /* All these ops have the same serial number.  Which comes first?
1077  *
1078  * This can happen both because read ops or failed write ops don't
1079  * change serial number, and also due to race since we access the
1080  * number unlocked (the race can cause less detectable ordering problems,
1081  * in which case we'll deadlock and report: fix manually in that case).
1082  */
1083 static void figure_deps(char *filename[], struct op *op[],
1084                         struct key_user user[], unsigned start, unsigned end)
1085 {
1086         unsigned int i;
1087         /* We assume database starts empty. */
1088         const struct TDB_DATA *data = &tdb_null;
1089
1090         /* What do we have to start with? */
1091         for (i = 0; i < start; i++)
1092                 data = gives(&op[user[i].file][user[i].op_num], data);
1093
1094         if (!sort_deps(filename, op, user + start, end - start, data))
1095                 fail(filename[user[start].file], user[start].op_num+1,
1096                      "Could not resolve inter-dependencies");
1097 }
1098
1099 static void sort_ops(struct keyinfo hash[], char *filename[], struct op *op[])
1100 {
1101         unsigned int h;
1102
1103         /* Gcc nexted function extension.  How cool is this? */
1104         int compare_serial(const void *_a, const void *_b)
1105         {
1106                 const struct key_user *a = _a, *b = _b;
1107                 return op[a->file][a->op_num].serial
1108                         - op[b->file][b->op_num].serial;
1109         }
1110
1111         /* Now sort into seqnum order. */
1112         for (h = 0; h < total_keys * 2; h++) {
1113                 unsigned int i, same;
1114                 struct key_user *user = hash[h].user;
1115
1116                 qsort(user, hash[h].num_users, sizeof(user[0]), compare_serial);
1117
1118                 /* Try to deal with same serial numbers. */
1119                 for (i = 1, same = 0; i < hash[h].num_users; i++) {
1120                         if (op[user[i].file][user[i].op_num].serial
1121                             == op[user[i-1].file][user[i-1].op_num].serial) {
1122                                 same++;
1123                                 continue;
1124                         }
1125
1126                         if (same) {
1127                                 figure_deps(filename, op, user, i-same-1, i);
1128                                 same = 0;
1129                         }
1130                 }
1131                 if (same)
1132                         figure_deps(filename, op, user, i-same-1, i);
1133         }
1134 }
1135
1136 static unsigned int dep_count;
1137 static void add_dependency(void *ctx,
1138                            struct op *op[],
1139                            char *filename[],
1140                            unsigned int needs_file,
1141                            unsigned int needs_opnum,
1142                            unsigned int satisfies_file,
1143                            unsigned int satisfies_opnum)
1144 {
1145         struct depend *post, *pre;
1146         unsigned int needs_start, sat_start;
1147
1148         /* We don't depend on ourselves. */
1149         if (needs_file == satisfies_file)
1150                 return;
1151
1152 #if DEBUG_DEPS
1153         printf("%s:%u: depends on %s:%u\n",
1154                filename[needs_file], needs_opnum+1,
1155                filename[satisfies_file], satisfies_opnum+1);
1156 #endif
1157
1158         needs_start = op[needs_file][needs_opnum].group_start;
1159         sat_start = op[satisfies_file][satisfies_opnum].group_start;
1160
1161         /* If needs is in a transaction, we need it before start. */
1162         if (needs_start) {
1163                 switch (op[needs_file][needs_start].op) {
1164                 case OP_TDB_TRANSACTION_START:
1165                         needs_opnum = needs_start;
1166 #ifdef DEBUG_DEPS
1167                         printf("  -> Back to %u\n", needs_start+1);
1168                         fflush(stdout);
1169 #endif
1170                         break;
1171                 default:
1172                         break;
1173                 }
1174         }
1175
1176         /* If satisfies is in a transaction, we wait until after commit. */
1177         /* FIXME: If transaction is cancelled, don't need dependency. */
1178         if (sat_start) {
1179                 if (op[satisfies_file][sat_start].op
1180                     == OP_TDB_TRANSACTION_START) {
1181                         satisfies_opnum
1182                                 = op[satisfies_file][sat_start].transaction_end;
1183 #ifdef DEBUG_DEPS
1184                         printf("  -> Depends on %u\n", satisfies_opnum+1);
1185                         fflush(stdout);
1186 #endif
1187                 }
1188         }
1189
1190         post = talloc(ctx, struct depend);
1191         post->file = needs_file;
1192         post->op = needs_opnum;
1193         list_add(&op[satisfies_file][satisfies_opnum].post, &post->list);
1194
1195         pre = talloc(ctx, struct depend);
1196         pre->file = satisfies_file;
1197         pre->op = satisfies_opnum;
1198         list_add(&op[needs_file][needs_opnum].pre, &pre->list);
1199
1200         dep_count++;
1201 }
1202
1203 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
1204 struct traverse_dep {
1205         unsigned int file;
1206         unsigned int op_num;
1207         const struct op *op;
1208 };
1209
1210 /* Sort by which one runs first. */
1211 static int compare_traverse_dep(const void *_a, const void *_b)
1212 {
1213         const struct traverse_dep *a = _a, *b = _b;
1214         const struct traverse *trava = a->op->trav, *travb = b->op->trav;
1215
1216         if (a->op->serial != b->op->serial)
1217                 return a->op->serial - b->op->serial;
1218
1219         /* If they have same serial, it means one didn't make any changes.
1220          * Thus sort by end in that case. */
1221         return a->op[trava->end - a->op_num].serial
1222                 - b->op[travb->end - b->op_num].serial;
1223 }
1224
1225 /* Traversals can deadlock against each other.  Force order. */
1226 static void make_traverse_depends(char *filename[],
1227                                   struct op *op[], unsigned int num_ops[],
1228                                   unsigned int num)
1229 {
1230         unsigned int i, j, num_traversals = 0;
1231         struct traverse_dep *dep;
1232
1233         dep = talloc_array(NULL, struct traverse_dep, 1);
1234
1235         /* Count them. */
1236         for (i = 0; i < num; i++) {
1237                 for (j = 0; j < num_ops[i]; j++) {
1238                         if (op[i][j].op == OP_TDB_TRAVERSE_START
1239                             || op[i][j].op == OP_TDB_TRAVERSE_READ_START) {
1240                                 dep = talloc_realloc(NULL, dep,
1241                                                      struct traverse_dep,
1242                                                      num_traversals+1);
1243                                 dep[num_traversals].file = i;
1244                                 dep[num_traversals].op_num = j;
1245                                 dep[num_traversals].op = &op[i][j];
1246                                 num_traversals++;
1247                         }
1248                 }
1249         }
1250         qsort(dep, num_traversals, sizeof(dep[0]), compare_traverse_dep);
1251         for (i = 1; i < num_traversals; i++) {
1252                 /* i depends on end of traverse i-1. */
1253                 add_dependency(NULL, op, filename, dep[i].file, dep[i].op_num,
1254                                dep[i-1].file, dep[i-1].op->trav->end);
1255         }
1256         talloc_free(dep);
1257         printf("Dep count after traverses: %u\n", dep_count);
1258 }
1259 #endif /* TRAVERSALS_TAKE_TRANSACTION_LOCK */
1260
1261 static bool changes_db(const struct op *op)
1262 {
1263         return gives(op, NULL) != NULL;
1264 }
1265
1266 static void depend_on_previous(struct op *op[],
1267                                char *filename[],
1268                                unsigned int num,
1269                                struct key_user user[],
1270                                unsigned int i,
1271                                int prev)
1272 {
1273         bool deps[num];
1274         int j;
1275
1276         if (i == 0)
1277                 return;
1278
1279         if (prev == i - 1) {
1280                 /* Just depend on previous. */
1281                 add_dependency(NULL, op, filename,
1282                                user[i].file, user[i].op_num,
1283                                user[prev].file, user[prev].op_num);
1284                 return;
1285         }
1286
1287         /* We have to wait for the readers.  Find last one in *each* file. */
1288         memset(deps, 0, sizeof(deps));
1289         deps[user[i].file] = true;
1290         for (j = i - 1; j > prev; j--) {
1291                 if (!deps[user[j].file]) {
1292                         add_dependency(NULL, op, filename,
1293                                        user[i].file, user[i].op_num,
1294                                        user[j].file, user[j].op_num);
1295                         deps[user[j].file] = true;
1296                 }
1297         }
1298 }
1299
1300 static void derive_dependencies(char *filename[],
1301                                 struct op *op[], unsigned int num_ops[],
1302                                 unsigned int num)
1303 {
1304         struct keyinfo *hash;
1305         unsigned int h, i;
1306
1307         /* Create hash table for faster key lookup. */
1308         hash = hash_ops(op, num_ops, num);
1309
1310         /* Now handle the hard cases: same serial number. */
1311         sort_ops(hash, filename, op);
1312
1313         /* Create dependencies back to the last change, rather than
1314          * creating false dependencies by naively making each one
1315          * depend on the previous.  This has two purposes: it makes
1316          * later optimization simpler, and it also avoids deadlock with
1317          * same sequence number ops inside traversals (if one
1318          * traversal doesn't write anything, two ops can have the same
1319          * sequence number yet we can create a traversal dependency
1320          * the other way). */
1321         for (h = 0; h < total_keys * 2; h++) {
1322                 int prev = -1;
1323
1324                 if (hash[h].num_users < 2)
1325                         continue;
1326
1327                 for (i = 0; i < hash[h].num_users; i++) {
1328                         if (changes_db(&op[hash[h].user[i].file]
1329                                        [hash[h].user[i].op_num])) {
1330                                 depend_on_previous(op, filename, num,
1331                                                    hash[h].user, i, prev);
1332                                 prev = i;
1333                         } else if (prev >= 0)
1334                                 add_dependency(hash, op, filename,
1335                                                hash[h].user[i].file,
1336                                                hash[h].user[i].op_num,
1337                                                hash[h].user[prev].file,
1338                                                hash[h].user[prev].op_num);
1339                 }
1340         }
1341         printf("Dep count after deriving: %u\n", dep_count);
1342
1343 #if TRAVERSALS_TAKE_TRANSACTION_LOCK
1344         make_traverse_depends(filename, op, num_ops, num);
1345 #endif
1346 }
1347
1348 int main(int argc, char *argv[])
1349 {
1350         struct timeval start, end;
1351         unsigned int i, num_ops[argc], hashsize[argc], tdb_flags[argc], open_flags[argc];
1352         struct op *op[argc];
1353         int fds[2];
1354         char c;
1355         bool ok = true;
1356
1357         if (argc < 3)
1358                 errx(1, "Usage: %s <tdbfile> <tracefile>...", argv[0]);
1359
1360         pipes = talloc_array(NULL, struct pipe, argc - 2);
1361         for (i = 0; i < argc - 2; i++) {
1362                 printf("Loading tracefile %s...", argv[2+i]);
1363                 fflush(stdout);
1364                 op[i] = load_tracefile(argv[2+i], &num_ops[i], &hashsize[i],
1365                                        &tdb_flags[i], &open_flags[i]);
1366                 if (pipe(pipes[i].fd) != 0)
1367                         err(1, "creating pipe");
1368                 printf("done\n");
1369         }
1370
1371         printf("Calculating inter-dependencies...");
1372         fflush(stdout);
1373         derive_dependencies(argv+2, op, num_ops, i);
1374         printf("done\n");
1375
1376         /* Don't fork for single arg case: simple debugging. */
1377         if (argc == 3) {
1378                 struct tdb_context *tdb;
1379                 tdb = tdb_open_ex(argv[1], hashsize[0], tdb_flags[0],
1380                                   open_flags[0], 0600,
1381                                   NULL, hash_key);
1382                 printf("Single threaded run...");
1383                 fflush(stdout);
1384
1385                 run_ops(tdb, pipes[0].fd[0], argv+2, 0, op[0], 1, num_ops[0]);
1386                 check_deps(argv[2], op[0], num_ops[0]);
1387
1388                 printf("done\n");
1389                 exit(0);
1390         }
1391
1392         if (pipe(fds) != 0)
1393                 err(1, "creating pipe");
1394
1395         for (i = 0; i < argc - 2; i++) {
1396                 struct tdb_context *tdb;
1397
1398                 switch (fork()) {
1399                 case -1:
1400                         err(1, "fork failed");
1401                 case 0:
1402                         close(fds[1]);
1403                         tdb = tdb_open_ex(argv[1], hashsize[i], tdb_flags[i],
1404                                           open_flags[i], 0600,
1405                                           NULL, hash_key);
1406                         if (!tdb)
1407                                 err(1, "Opening tdb %s", argv[1]);
1408
1409                         /* This catches parent exiting. */
1410                         if (read(fds[0], &c, 1) != 1)
1411                                 exit(1);
1412                         run_ops(tdb, pipes[i].fd[0], argv+2, i, op[i], 1,
1413                                 num_ops[i]);
1414                         check_deps(argv[2+i], op[i], num_ops[i]);
1415                         exit(0);
1416                 default:
1417                         break;
1418                 }
1419         }
1420
1421         /* Let everything settle. */
1422         sleep(1);
1423
1424         printf("Starting run...");
1425         fflush(stdout);
1426         gettimeofday(&start, NULL);
1427         /* Tell them all to go!  Any write of sufficient length will do. */
1428         if (write(fds[1], hashsize, i) != i)
1429                 err(1, "Writing to wakeup pipe");
1430
1431         for (i = 0; i < argc - 2; i++) {
1432                 int status;
1433                 wait(&status);
1434                 if (!WIFEXITED(status)) {
1435                         warnx("Child died with signal %i", WTERMSIG(status));
1436                         ok = false;
1437                 } else if (WEXITSTATUS(status) != 0)
1438                         /* Assume child spat out error. */
1439                         ok = false;
1440         }
1441         if (!ok)
1442                 exit(1);
1443
1444         gettimeofday(&end, NULL);
1445         printf("done\n");
1446
1447         end.tv_sec -= start.tv_sec;
1448         printf("Time replaying: %lu usec\n",
1449                end.tv_sec * 1000000UL + (end.tv_usec - start.tv_usec));
1450         
1451         exit(0);
1452 }