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