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