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