]> git.tuebingen.mpg.de Git - paraslash.git/blob - buffer_tree.c
btr: Speed up btr_node_status().
[paraslash.git] / buffer_tree.c
1 /* Copyright (C) 2009 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file buffer_tree.c Buffer tree and buffer pool implementations. */
4 #include <regex.h>
5
6 #include "para.h"
7 #include "list.h"
8 #include "string.h"
9 #include "buffer_tree.h"
10 #include "error.h"
11 #include "sched.h"
12
13 /* whead = NULL means area full */
14 struct btr_pool {
15         char *name;
16         char *area_start;
17         char *area_end;
18         char *rhead;
19         char *whead;
20 };
21
22 struct btr_buffer {
23         char *buf;
24         size_t size;
25         /** The number of references to this buffer. */
26         int refcount;
27         /* NULL means no buffer pool but a malloced buffer. */
28         struct btr_pool *pool;
29         /* Only relevant if pool is NULL. */
30         bool dont_free;
31 };
32
33 struct btr_buffer_reference {
34         struct btr_buffer *btrb;
35         size_t consumed;
36         /* Each buffer reference belongs to the buffer queue list of some buffer tree node. */
37         struct list_head node;
38         size_t wrap_count;
39 };
40
41 struct btr_node {
42         char *name;
43         struct btr_node *parent;
44         /* The position of this btr node in the buffer tree. */
45         struct list_head node;
46         /* The children nodes of this btr node are linked together in a list. */
47         struct list_head children;
48         /* Time of first data transfer. */
49         struct timeval start;
50         /**
51          * The input queue is a list of references to btr buffers. Each item on
52          * the list represents an input buffer which has not been completely
53          * used by this btr node.
54          */
55         struct list_head input_queue;
56         btr_command_handler execute;
57         void *context;
58 };
59
60 /**
61  * Create a new buffer pool.
62  *
63  * \param name The name of the new buffer pool.
64  * \param area_size The size in bytes of the pool area.
65  *
66  * \return An opaque pointer to the newly created buffer pool. It must be
67  * passed to btr_pool_free() after it is no longer used to deallocate all
68  * resources.
69  */
70 struct btr_pool *btr_pool_new(const char *name, size_t area_size)
71 {
72         struct btr_pool *btrp;
73
74         PARA_INFO_LOG("%s, %zu bytes\n", name, area_size);
75         btrp = alloc(sizeof(*btrp));
76         btrp->area_start = alloc(area_size);
77         btrp->area_end = btrp->area_start + area_size;
78         btrp->rhead = btrp->area_start;
79         btrp->whead = btrp->area_start;
80         btrp->name = para_strdup(name);
81         return btrp;
82 }
83
84 /**
85  * Deallocate resources used by a buffer pool.
86  *
87  * \param btrp A pointer obtained via btr_pool_new().
88  */
89 void btr_pool_free(struct btr_pool *btrp)
90 {
91         if (!btrp)
92                 return;
93         free(btrp->area_start);
94         free(btrp->name);
95         free(btrp);
96 }
97
98 /**
99  * Return the size of the buffer pool area.
100  *
101  * \param btrp The buffer pool.
102  *
103  * \return The same value which was passed during creation time to
104  * btr_pool_new().
105  */
106 size_t btr_pool_size(struct btr_pool *btrp)
107 {
108         return btrp->area_end - btrp->area_start;
109 }
110
111 static size_t btr_pool_filled(struct btr_pool *btrp)
112 {
113         if (!btrp->whead)
114                 return btr_pool_size(btrp);
115         if (btrp->rhead <= btrp->whead)
116                 return  btrp->whead - btrp->rhead;
117         return btr_pool_size(btrp) - (btrp->rhead - btrp->whead);
118 }
119
120 /**
121  * Get the number of unused bytes in the buffer pool.
122  *
123  * \param btrp The pool.
124  *
125  * \return The number of bytes that can currently be allocated.
126  *
127  * Note that in general the returned number of bytes is not available as a
128  * single contiguous buffer. Use btr_pool_available() to obtain the length of
129  * the largest contiguous buffer that can currently be allocated from the
130  * buffer pool.
131  */
132 size_t btr_pool_unused(struct btr_pool *btrp)
133 {
134         return btr_pool_size(btrp) - btr_pool_filled(btrp);
135 }
136
137 /*
138  * Return maximal size available for one read. This is
139  * smaller than the value returned by btr_pool_unused().
140  */
141 static size_t btr_pool_available(struct btr_pool *btrp)
142 {
143         if (!btrp->whead)
144                 return 0;
145         if (btrp->rhead <= btrp->whead)
146                 return btrp->area_end - btrp->whead;
147         return btrp->rhead - btrp->whead;
148 }
149
150 /**
151  * Obtain the current write head.
152  *
153  * \param btrp The buffer pool.
154  * \param result The write head is returned here.
155  *
156  * \return The maximal amount of bytes that may be written to the returned
157  * buffer.
158  */
159 size_t btr_pool_get_buffer(struct btr_pool *btrp, char **result)
160 {
161         if (result)
162                 *result = btrp->whead;
163         return btr_pool_available(btrp);
164 }
165
166 /**
167  * Get references to buffers pointing to free space of the buffer pool area.
168  *
169  * \param btrp The buffer pool.
170  * \param iov The scatter array.
171  *
172  * \return Zero if the buffer pool is full, one if the free space of the buffer
173  * pool area is available as a single contiguous buffer, two if the free space
174  * consists of two buffers. If this function returns the value n, then n
175  * elements of \a iov are initialized.
176  */
177 int btr_pool_get_buffers(struct btr_pool *btrp, struct iovec iov[2])
178 {
179         size_t sz, unused;
180         char *buf;
181
182         sz = btr_pool_get_buffer(btrp, &buf);
183         if (sz == 0)
184                 return 0;
185         iov[0].iov_len = sz;
186         iov[0].iov_base = buf;
187         unused = btr_pool_unused(btrp);
188         if (sz == unused)
189                 return 1;
190         iov[1].iov_len = unused - sz;
191         iov[1].iov_base = btrp->area_start;
192         return 2;
193 }
194
195 /**
196  * Mark a part of the buffer pool area as allocated.
197  *
198  * \param btrp The buffer pool.
199  * \param size The amount of bytes to be allocated.
200  *
201  * This is usually called after the caller wrote to the buffer obtained by
202  * btr_pool_get_buffer().
203  */
204 static void btr_pool_allocate(struct btr_pool *btrp, size_t size)
205 {
206         char *end;
207
208         if (size == 0)
209                 return;
210         assert(size <= btr_pool_available(btrp));
211         end = btrp->whead + size;
212         assert(end <= btrp->area_end);
213
214         if (end == btrp->area_end) {
215                 PARA_DEBUG_LOG("%s: end of pool area reached\n", btrp->name);
216                 end = btrp->area_start;
217         }
218         if (end == btrp->rhead) {
219                 PARA_DEBUG_LOG("%s btrp buffer full\n", btrp->name);
220                 end = NULL; /* buffer full */
221         }
222         btrp->whead = end;
223 }
224
225 static void btr_pool_deallocate(struct btr_pool *btrp, size_t size)
226 {
227         char *end = btrp->rhead + size;
228
229         if (size == 0)
230                 return;
231         assert(end <= btrp->area_end);
232         assert(size <= btr_pool_filled(btrp));
233         if (end == btrp->area_end)
234                 end = btrp->area_start;
235         if (!btrp->whead)
236                 btrp->whead = btrp->rhead;
237         btrp->rhead = end;
238         if (btrp->rhead == btrp->whead)
239                 btrp->rhead = btrp->whead = btrp->area_start;
240 }
241
242 #define FOR_EACH_CHILD(_tn, _btrn) list_for_each_entry((_tn), \
243         &((_btrn)->children), node)
244 #define FOR_EACH_CHILD_SAFE(_tn, _tmp, _btrn) \
245         list_for_each_entry_safe((_tn), (_tmp), &((_btrn)->children), node)
246
247 #define FOR_EACH_BUFFER_REF(_br, _btrn) \
248         list_for_each_entry((_br), &(_btrn)->input_queue, node)
249 #define FOR_EACH_BUFFER_REF_SAFE(_br, _tmp, _btrn) \
250         list_for_each_entry_safe((_br), (_tmp), &(_btrn)->input_queue, node)
251
252 /**
253  * Create a new buffer tree node.
254  *
255  * \param bnd Specifies how to create the new node.
256  *
257  * \return A pointer to the newly allocated node.
258  *
259  * This function always succeeds (or calls exit()). The returned pointer must
260  * be freed using btr_free_node() after the node has been removed from the
261  * buffer tree via btr_remove_node().
262  */
263 struct btr_node *btr_new_node(struct btr_node_description *bnd)
264 {
265         struct btr_node *btrn = alloc(sizeof(*btrn));
266
267         btrn->name = para_strdup(bnd->name);
268         btrn->parent = bnd->parent;
269         btrn->execute = bnd->handler;
270         btrn->context = bnd->context;
271         btrn->start.tv_sec = 0;
272         btrn->start.tv_usec = 0;
273         init_list_head(&btrn->children);
274         init_list_head(&btrn->input_queue);
275         if (!bnd->child) {
276                 if (bnd->parent) {
277                         list_add_tail(&btrn->node, &bnd->parent->children);
278                         PARA_INFO_LOG("new leaf node: %s (child of %s)\n",
279                                 bnd->name, bnd->parent->name);
280                 } else
281                         PARA_INFO_LOG("added %s as btr root\n", bnd->name);
282                 goto out;
283         }
284         if (!bnd->parent) {
285                 assert(!bnd->child->parent);
286                 PARA_INFO_LOG("new root: %s (was %s)\n",
287                         bnd->name, bnd->child->name);
288                 btrn->parent = NULL;
289                 list_add_tail(&bnd->child->node, &btrn->children);
290                 /* link it in */
291                 bnd->child->parent = btrn;
292                 goto out;
293         }
294         list_add_tail(&btrn->node, &bnd->parent->children);
295         list_move(&bnd->child->node, &btrn->children);
296         bnd->child->parent = btrn;
297         PARA_INFO_LOG("added %s as internal node\n", bnd->name);
298 out:
299         return btrn;
300 }
301
302 /*
303  * Allocate a new btr buffer.
304  *
305  * The freshly allocated buffer will have a zero refcount and will
306  * not be associated with a btr pool.
307  */
308 static struct btr_buffer *new_btrb(char *buf, size_t size)
309 {
310         struct btr_buffer *btrb = zalloc(sizeof(*btrb));
311
312         btrb->buf = buf;
313         btrb->size = size;
314         return btrb;
315 }
316
317 static void dealloc_buffer(struct btr_buffer *btrb)
318 {
319         if (btrb->pool)
320                 btr_pool_deallocate(btrb->pool, btrb->size);
321         else if (!btrb->dont_free)
322                 free(btrb->buf);
323 }
324
325 static struct btr_buffer_reference *get_first_input_br(struct btr_node *btrn)
326 {
327         if (list_empty(&btrn->input_queue))
328                 return NULL;
329         return list_first_entry(&btrn->input_queue,
330                 struct btr_buffer_reference, node);
331 }
332
333 /*
334  * Deallocate the reference, release the resources if refcount drops to zero.
335  */
336 static void btr_drop_buffer_reference(struct btr_buffer_reference *br)
337 {
338         struct btr_buffer *btrb = br->btrb;
339
340         list_del(&br->node);
341         free(br);
342         btrb->refcount--;
343         if (btrb->refcount == 0) {
344                 dealloc_buffer(btrb);
345                 free(btrb);
346         }
347 }
348
349 static void add_btrb_to_children(struct btr_buffer *btrb,
350                 struct btr_node *btrn, size_t consumed)
351 {
352         struct btr_node *ch;
353
354         if (btrn->start.tv_sec == 0)
355                 btrn->start = *now;
356         FOR_EACH_CHILD(ch, btrn) {
357                 struct btr_buffer_reference *br = zalloc(sizeof(*br));
358                 br->btrb = btrb;
359                 br->consumed = consumed;
360                 list_add_tail(&br->node, &ch->input_queue);
361                 btrb->refcount++;
362                 if (ch->start.tv_sec == 0)
363                         ch->start = *now;
364         }
365 }
366
367 /**
368  * Insert a malloced buffer into the buffer tree.
369  *
370  * \param buf The buffer to insert.
371  * \param size The size of \a buf in bytes.
372  * \param btrn Position in the buffer tree to create the output.
373  *
374  * This creates references to \a buf and adds these references to each child of
375  * \a btrn. The buffer will be freed using standard free() once no buffer tree
376  * node is referencing it any more.
377  *
378  * Note that this function must not be used if \a buf was obtained from a
379  * buffer pool. Use btr_add_output_pool() in this case.
380  */
381 void btr_add_output(char *buf, size_t size, struct btr_node *btrn)
382 {
383         struct btr_buffer *btrb;
384
385         if (size == 0)
386                 return;
387         if (list_empty(&btrn->children)) {
388                 free(buf);
389                 return;
390         }
391         btrb = new_btrb(buf, size);
392         add_btrb_to_children(btrb, btrn, 0);
393 }
394
395 /**
396  * Insert a buffer into the buffer tree, non-freeing variant.
397  *
398  * \param buf See \ref btr_add_output().
399  * \param size See \ref btr_add_output().
400  * \param btrn See \ref btr_add_output().
401  *
402  * This is similar to btr_add_output() but additionally sets the \p dont_free
403  * flag on \a buf. If the refcount for the buffer drops to zero, \a buf will
404  * not be deallocated if this flag is set.
405  *
406  * The \p dont_free bit also prevents the children of \a btrn from modifying
407  * the buffer contents inplace. Specifically, \ref btr_inplace_ok() returns
408  * false if there is any buffer in the input queue with the \p dont_free bit
409  * set.
410  */
411 void btr_add_output_dont_free(const char *buf, size_t size, struct btr_node *btrn)
412 {
413         struct btr_buffer *btrb;
414
415         if (size == 0)
416                 return;
417         if (list_empty(&btrn->children))
418                 return;
419         btrb = new_btrb((char *)buf, size);
420         btrb->dont_free = true;
421         add_btrb_to_children(btrb, btrn, 0);
422 }
423
424 /**
425  * Feed data to child nodes of a buffer tree node.
426  *
427  * \param btrp The buffer pool.
428  * \param size The number of bytes to be allocated and fed to each child.
429  * \param btrn The node whose children are to be fed.
430  *
431  * This function allocates the amount of bytes from the buffer pool area,
432  * starting at the current value of the write head, and creates buffer
433  * references to the resulting part of the buffer pool area, one for each child
434  * of \a btrn. The references are then fed into the input queue of each child.
435  */
436 void btr_add_output_pool(struct btr_pool *btrp, size_t size,
437                 struct btr_node *btrn)
438 {
439         struct btr_buffer *btrb;
440         char *buf;
441         size_t avail;
442
443         if (size == 0)
444                 return;
445         if (list_empty(&btrn->children))
446                 return;
447         avail = btr_pool_get_buffer(btrp, &buf);
448         assert(avail >= size);
449         btr_pool_allocate(btrp, size);
450         btrb = new_btrb(buf, size);
451         btrb->pool = btrp;
452         add_btrb_to_children(btrb, btrn, 0);
453 }
454
455 /**
456  * Copy data to write head of a buffer pool and feed it to all children nodes.
457  *
458  * \param src The source buffer.
459  * \param n The size of the source buffer in bytes.
460  * \param btrp The destination buffer pool.
461  * \param btrn Add the data as output of this node.
462  *
463  * This is expensive. The caller must make sure the data fits into the buffer
464  * pool area.
465  */
466 void btr_copy(const void *src, size_t n, struct btr_pool *btrp,
467         struct btr_node *btrn)
468 {
469         char *buf;
470         size_t sz, copy;
471
472         if (n == 0)
473                 return;
474         assert(n <= btr_pool_unused(btrp));
475         sz = btr_pool_get_buffer(btrp, &buf);
476         copy = PARA_MIN(sz, n);
477         memcpy(buf, src, copy);
478         btr_add_output_pool(btrp, copy, btrn);
479         if (copy == n)
480                 return;
481         sz = btr_pool_get_buffer(btrp, &buf);
482         assert(sz >= n - copy);
483         memcpy(buf, src + copy, n - copy);
484         btr_add_output_pool(btrp, n - copy, btrn);
485 }
486
487 static void btr_pushdown_br(struct btr_buffer_reference *br, struct btr_node *btrn)
488 {
489         add_btrb_to_children(br->btrb, btrn, br->consumed);
490         btr_drop_buffer_reference(br);
491 }
492
493 /**
494  * Feed all buffer references of the input queue through the output channel.
495  *
496  * \param btrn The node whose buffer references should be pushed down.
497  *
498  * This function is useful for filters that do not change the contents of the
499  * buffers at all, like the wav filter or the amp filter if no amplification
500  * was specified. This function is rather cheap.
501  *
502  * \sa \ref btr_pushdown_one().
503  */
504 void btr_pushdown(struct btr_node *btrn)
505 {
506         struct btr_buffer_reference *br, *tmp;
507
508         FOR_EACH_BUFFER_REF_SAFE(br, tmp, btrn)
509                 btr_pushdown_br(br, btrn);
510 }
511
512 /**
513  * Feed the next buffer of the input queue through the output channel.
514  *
515  * \param btrn The node whose first input queue buffer should be pushed down.
516  *
517  * This works like \ref btr_pushdown() but pushes down only one buffer
518  * reference.
519  */
520 void btr_pushdown_one(struct btr_node *btrn)
521 {
522         struct btr_buffer_reference *br;
523
524         if (list_empty(&btrn->input_queue))
525                 return;
526         br = list_first_entry(&btrn->input_queue, struct btr_buffer_reference, node);
527         btr_pushdown_br(br, btrn);
528 }
529
530 /*
531  * Find out whether a node is a leaf node.
532  *
533  * \param btrn The node to check.
534  *
535  * \return True if this node has no children. False otherwise.
536  */
537 static bool btr_no_children(struct btr_node *btrn)
538 {
539         return list_empty(&btrn->children);
540 }
541
542 /**
543  * Find out whether a node is an orphan.
544  *
545  * \param btrn The buffer tree node.
546  *
547  * \return True if \a btrn has no parent.
548  *
549  * This function returns true for the root node and false for any other node.
550  *
551  * After a (non-leaf) node was removed removed from the tree, the function
552  * returns true for all child nodes.
553  */
554 bool btr_no_parent(struct btr_node *btrn)
555 {
556         return !btrn->parent;
557 }
558
559 /**
560  * Find out whether it is OK to change an input buffer.
561  *
562  * \param btrn The buffer tree node to check.
563  *
564  * This is used by filters that produce exactly the same amount of output as
565  * there is input. The amp filter which multiplies each sample by some number
566  * is an example of such a filter. If there are no other nodes in the buffer
567  * tree that read the same input stream (i.e. if \a btrn has no siblings), a
568  * node may modify its input buffer directly and push down the modified buffer
569  * to its children, thereby avoiding to allocate a possibly large additional
570  * buffer.
571  *
572  * Since the buffer tree may change at any time, this function should be called
573  * during each post_monitor call.
574  *
575  * \return True if \a btrn has no siblings.
576  */
577 bool btr_inplace_ok(struct btr_node *btrn)
578 {
579         struct btr_buffer_reference *br;
580         FOR_EACH_BUFFER_REF(br, btrn) {
581                 struct btr_buffer *btrb = br->btrb;
582                 if (btrb->refcount > 1)
583                         return false;
584                 if (btrb->dont_free == true)
585                         return false;
586         }
587         return true;
588 }
589
590 static inline size_t br_available_bytes(struct btr_buffer_reference *br)
591 {
592         return br->btrb->size - br->consumed;
593 }
594
595 static size_t btr_get_buffer_by_reference(struct btr_buffer_reference *br, char **buf)
596 {
597         if (buf)
598                 *buf = br->btrb->buf + br->consumed;
599         return br_available_bytes(br);
600 }
601
602 /**
603  * Obtain the next buffer of the input queue, omitting data.
604  *
605  * \param btrn The node whose input queue is to be queried.
606  * \param omit Number of bytes to be omitted.
607  * \param bufp Result pointer. It is OK to pass \p NULL here.
608  *
609  * If a buffer tree node needs more input data but can not consume the data it
610  * already has (because it might be needed again later) this function can be
611  * used instead of btr_next_buffer() to get a reference to the buffer obtained
612  * by skipping the given number of bytes. Skipped input bytes are not consumed.
613  *
614  * With a zero \a omit argument, this function is equivalent to \ref
615  * btr_next_buffer().
616  *
617  * \return Number of bytes in \a bufp. If there are less than or equal to \a
618  * omit many bytes available in the input queue of the buffer tree node pointed
619  * to by \a btrn, the function returns zero and the value of \a bufp is
620  * undefined.
621  */
622 size_t btr_next_buffer_omit(struct btr_node *btrn, size_t omit, char **bufp)
623 {
624         struct btr_buffer_reference *br;
625         size_t wrap_count, sz, rv = 0;
626         char *buf, *result = NULL;
627
628         br = get_first_input_br(btrn);
629         if (!br)
630                 return 0;
631         wrap_count = br->wrap_count;
632         if (wrap_count > 0) { /* we have a wrap buffer */
633                 sz = btr_get_buffer_by_reference(br, &buf);
634                 if (sz > omit) { /* and it's big enough */
635                         result = buf + omit;
636                         rv = sz - omit;
637                         /*
638                          * Wrap buffers are allocated by malloc(), so the next
639                          * buffer ref will not align nicely, so we return the
640                          * tail of the wrap buffer.
641                          */
642                         goto out;
643                 }
644                 /*
645                  * The next wrap_count bytes exist twice, in the wrap buffer
646                  * and as a buffer reference in the buffer tree pool.
647                  */
648                 omit += wrap_count;
649         }
650         /*
651          * For buffer tree pools, the buffers in the list align, i.e. the next
652          * buffer in the list starts directly at the end of its predecessor. In
653          * this case we merge adjacent buffers and return one larger buffer
654          * instead.
655          */
656         FOR_EACH_BUFFER_REF(br, btrn) {
657                 sz = btr_get_buffer_by_reference(br, &buf);
658                 if (result) {
659                         if (result + rv != buf)
660                                 goto out;
661                         rv += sz;
662                 } else if (sz > omit) {
663                         result = buf + omit;
664                         rv = sz - omit;
665                 } else
666                         omit -= sz;
667         }
668         if (!result)
669                 return 0;
670 out:
671         if (bufp)
672                 *bufp = result;
673         return rv;
674 }
675
676 /**
677  * Obtain the next buffer of the input queue of a buffer tree node.
678  *
679  * \param btrn The node whose input queue is to be queried.
680  * \param bufp Result pointer.
681  *
682  * \return The number of bytes that can be read from buf.
683  *
684  * The call of this function is is equivalent to calling \ref
685  * btr_next_buffer_omit() with an \a omit value of zero.
686  */
687 size_t btr_next_buffer(struct btr_node *btrn, char **bufp)
688 {
689         return btr_next_buffer_omit(btrn, 0, bufp);
690 }
691
692 /**
693  * Deallocate the given number of bytes from the input queue.
694  *
695  * \param btrn The buffer tree node.
696  * \param numbytes The number of bytes to be deallocated.
697  *
698  * This function must be used to get rid of existing buffer references in the
699  * node's input queue. If no references to a buffer remain, the underlying
700  * buffers are either freed (in the non-buffer pool case) or the read head of
701  * the buffer pool is being advanced.
702  *
703  * Note that \a numbytes may be smaller than the buffer size. In this case the
704  * buffer is not deallocated and subsequent calls to btr_next_buffer() return
705  * the remaining part of the buffer.
706  */
707 void btr_consume(struct btr_node *btrn, size_t numbytes)
708 {
709         struct btr_buffer_reference *br, *tmp;
710         size_t sz;
711
712         if (numbytes == 0)
713                 return;
714         br = get_first_input_br(btrn);
715         assert(br);
716
717         if (br->wrap_count == 0) {
718                 /*
719                  * No wrap buffer. Drop buffer references whose buffer
720                  * has been fully used. */
721                 FOR_EACH_BUFFER_REF_SAFE(br, tmp, btrn) {
722                         if (br->consumed + numbytes <= br->btrb->size) {
723                                 br->consumed += numbytes;
724                                 if (br->consumed == br->btrb->size)
725                                         btr_drop_buffer_reference(br);
726                                 return;
727                         }
728                         numbytes -= br->btrb->size - br->consumed;
729                         btr_drop_buffer_reference(br);
730                 }
731                 assert(false);
732         }
733         /*
734          * We have a wrap buffer, consume from it. If in total, i.e. including
735          * previous calls to brt_consume(), less than wrap_count has been
736          * consumed, there's nothing more we can do.
737          *
738          * Otherwise we drop the wrap buffer and consume from subsequent
739          * buffers of the input queue the correct amount of bytes. This is the
740          * total number of bytes that have been consumed from the wrap buffer.
741          */
742         PARA_DEBUG_LOG("consuming %zu/%zu bytes from wrap buffer\n", numbytes,
743                 br_available_bytes(br));
744
745         assert(numbytes <= br_available_bytes(br));
746         if (br->consumed + numbytes < br->wrap_count) {
747                 br->consumed += numbytes;
748                 return;
749         }
750         PARA_DEBUG_LOG("dropping wrap buffer (%zu bytes)\n", br->btrb->size);
751         /* get rid of the wrap buffer */
752         sz = br->consumed + numbytes;
753         btr_drop_buffer_reference(br);
754         return btr_consume(btrn, sz);
755 }
756
757 /**
758  * Clear the input queue of a buffer tree node.
759  *
760  * \param btrn The node whose input queue should be cleared.
761  */
762 void btr_drain(struct btr_node *btrn)
763 {
764         struct btr_buffer_reference *br, *tmp;
765
766         FOR_EACH_BUFFER_REF_SAFE(br, tmp, btrn)
767                 btr_drop_buffer_reference(br);
768 }
769
770 static void btr_free_node(struct btr_node *btrn)
771 {
772         free(btrn->name);
773         free(btrn);
774 }
775
776 /**
777  * Remove a node from a buffer tree.
778  *
779  * \param btrnp Determines the node to remove.
780  *
781  * This orphans all children of the node given by \a btrnp and removes this
782  * node from the child list of its parent. Moreover, the input queue is flushed
783  * and the node pointer given by \a btrp is set to \p NULL.
784  *
785  * \sa \ref btr_splice_out_node.
786  */
787 void btr_remove_node(struct btr_node **btrnp)
788 {
789         struct btr_node *ch;
790         struct btr_node *btrn;
791
792         if (!btrnp)
793                 return;
794         btrn = *btrnp;
795         if (!btrn)
796                 goto out;
797         PARA_INFO_LOG("removing btr node %s from buffer tree\n", btrn->name);
798         FOR_EACH_CHILD(ch, btrn)
799                 ch->parent = NULL;
800         btr_drain(btrn);
801         if (btrn->parent)
802                 list_del(&btrn->node);
803         btr_free_node(btrn);
804 out:
805         *btrnp = NULL;
806 }
807
808 /**
809  * Return the amount of available input bytes of a buffer tree node.
810  *
811  * \param btrn The node whose input size should be computed.
812  *
813  * \return The total number of bytes available in the node's input
814  * queue.
815  *
816  * This simply iterates over all buffer references in the input queue and
817  * returns the sum of the sizes of all references.
818  */
819 size_t btr_get_input_queue_size(struct btr_node *btrn)
820 {
821         struct btr_buffer_reference *br;
822         size_t size = 0, wrap_consumed = 0;
823
824         FOR_EACH_BUFFER_REF(br, btrn) {
825                 if (br->wrap_count != 0) {
826                         wrap_consumed = br->consumed;
827                         continue;
828                 }
829                 size += br_available_bytes(br);
830         }
831         assert(wrap_consumed <= size);
832         size -= wrap_consumed;
833         return size;
834 }
835
836 static bool min_iqs_available(size_t min_iqs, struct btr_node *btrn)
837 {
838         struct btr_buffer_reference *br;
839         size_t have = 0, wrap_consumed = 0;
840
841         FOR_EACH_BUFFER_REF(br, btrn) {
842                 if (br->wrap_count != 0) {
843                         wrap_consumed = br->consumed;
844                         continue;
845                 }
846                 have += br_available_bytes(br);
847                 if (have > wrap_consumed + min_iqs)
848                         return true;
849         }
850         return false;
851 }
852 /**
853  * Remove a node from the buffer tree, reconnecting parent and children.
854  *
855  * \param btrnp The node to splice out.
856  *
857  * This function is used by buffer tree nodes that do not exist during the
858  * whole lifetime of the buffer tree. Unlike btr_remove_node(), calling
859  * btr_splice_out_node() does not split the tree into disconnected components
860  * but reconnects the buffer tree by making all child nodes of \a btrn children
861  * of the parent of \a btrn.
862  */
863 void btr_splice_out_node(struct btr_node **btrnp)
864 {
865         struct btr_node *btrn = *btrnp, *ch, *tmp;
866
867         assert(btrn);
868         PARA_NOTICE_LOG("splicing out %s\n", btrn->name);
869         btr_pushdown(btrn);
870         if (btrn->parent)
871                 list_del(&btrn->node);
872         FOR_EACH_CHILD_SAFE(ch, tmp, btrn) {
873                 PARA_INFO_LOG("parent(%s): %s\n", ch->name,
874                         btrn->parent? btrn->parent->name : "NULL");
875                 ch->parent = btrn->parent;
876                 if (btrn->parent)
877                         list_move(&ch->node, &btrn->parent->children);
878                 else
879                         list_del(&ch->node);
880         }
881         assert(list_empty(&btrn->children));
882         btr_free_node(btrn);
883         *btrnp = NULL;
884 }
885
886 /**
887  * Return number of queued output bytes of a buffer tree node.
888  *
889  * \param btrn The node whose output queue size should be computed.
890  *
891  * \return This function iterates over all children of the given node and
892  * returns the size of the largest input queue.
893  */
894 size_t btr_get_output_queue_size(struct btr_node *btrn)
895 {
896         size_t max_size = 0;
897         struct btr_node *ch;
898
899         FOR_EACH_CHILD(ch, btrn) {
900                 size_t size = btr_get_input_queue_size(ch);
901                 max_size = PARA_MAX(max_size, size);
902         }
903         return max_size;
904 }
905
906 /**
907  * Execute an inter-node command on the given node or on a parent node.
908  *
909  * \param btrn The node to start looking.
910  * \param command The command to execute.
911  * \param value_result Additional arguments and result value.
912  *
913  * This function traverses the buffer tree from \a btrn upwards and looks for
914  * the first node that understands \a command. On this node \a command is
915  * executed, and the result is stored in \a value_result.
916  *
917  * \return \p -ENOTSUP if no parent node of \a btrn understands \a command.
918  * Otherwise the return value of the command handler is returned.
919  *
920  * \sa \ref receiver::execute, \ref filter::execute, \ref writer::execute.
921  */
922 int btr_exec_up(struct btr_node *btrn, const char *command, char **value_result)
923 {
924         int ret;
925
926         for (; btrn; btrn = btrn->parent) {
927                 if (!btrn->execute)
928                         continue;
929                 PARA_INFO_LOG("executing %s on %s\n", command, btrn->name);
930                 ret = btrn->execute(btrn, command, value_result);
931                 if (ret == -ERRNO_TO_PARA_ERROR(ENOTSUP))
932                         continue;
933                 if (ret < 0)
934                         return ret;
935                 if (value_result && *value_result)
936                         PARA_INFO_LOG("%s(%s): %s\n", command, btrn->name,
937                                 *value_result);
938                 return 1;
939         }
940         return -ERRNO_TO_PARA_ERROR(ENOTSUP);
941 }
942
943 /**
944  * Obtain the context of a buffer node tree.
945  *
946  * \param btrn The node whose output queue size should be computed.
947  *
948  * \return A pointer to the \a context address specified at node creation time.
949  *
950  * \sa \ref btr_new_node(), struct \ref btr_node_description.
951  */
952 void *btr_context(struct btr_node *btrn)
953 {
954         return btrn->context;
955 }
956
957 static bool need_buffer_pool_merge(struct btr_node *btrn)
958 {
959         struct btr_buffer_reference *br = get_first_input_br(btrn);
960
961         if (!br)
962                 return false;
963         if (br->wrap_count != 0)
964                 return true;
965         if (br->btrb->pool)
966                 return true;
967         return false;
968 }
969
970 static void merge_input_pool(struct btr_node *btrn, size_t dest_size)
971 {
972         struct btr_buffer_reference *br, *wbr = NULL;
973         int num_refs; /* including wrap buffer */
974         char *buf, *buf1 = NULL, *buf2 = NULL;
975         size_t sz, sz1 = 0, sz2 = 0, wb_consumed = 0;
976
977         br = get_first_input_br(btrn);
978         if (!br || br_available_bytes(br) >= dest_size)
979                 return;
980         num_refs = 0;
981         FOR_EACH_BUFFER_REF(br, btrn) {
982                 num_refs++;
983                 sz = btr_get_buffer_by_reference(br, &buf);
984                 if (sz == 0)
985                         break;
986                 if (br->wrap_count != 0) {
987                         assert(!wbr);
988                         assert(num_refs == 1);
989                         wbr = br;
990                         if (sz >= dest_size)
991                                 return;
992                         wb_consumed = br->consumed;
993                         continue;
994                 }
995                 if (!buf1) {
996                         buf1 = buf;
997                         sz1 = sz;
998                         goto next;
999                 }
1000                 if (buf1 + sz1 == buf) {
1001                         sz1 += sz;
1002                         goto next;
1003                 }
1004                 if (!buf2) {
1005                         buf2 = buf;
1006                         sz2 = sz;
1007                         goto next;
1008                 }
1009                 assert(buf2 + sz2 == buf);
1010                 sz2 += sz;
1011 next:
1012                 if (sz1 + sz2 >= dest_size + wb_consumed)
1013                         break;
1014         }
1015         if (!buf2) /* nothing to do */
1016                 return;
1017         assert(buf1 && sz2 > 0);
1018         /*
1019          * If the second buffer is large, we only take the first part of it to
1020          * avoid having to memcpy() huge buffers.
1021          */
1022         sz2 = PARA_MIN(sz2, (size_t)(64 * 1024));
1023         if (!wbr) {
1024                 /* Make a new wrap buffer combining buf1 and buf2. */
1025                 sz = sz1 + sz2;
1026                 buf = alloc(sz);
1027                 PARA_DEBUG_LOG("merging input buffers: (%p:%zu, %p:%zu) -> %p:%zu\n",
1028                         buf1, sz1, buf2, sz2, buf, sz);
1029                 memcpy(buf, buf1, sz1);
1030                 memcpy(buf + sz1, buf2, sz2);
1031                 br = zalloc(sizeof(*br));
1032                 br->btrb = new_btrb(buf, sz);
1033                 br->btrb->refcount = 1;
1034                 br->consumed = 0;
1035                 /* This is a wrap buffer */
1036                 br->wrap_count = sz1;
1037                 para_list_add(&br->node, &btrn->input_queue);
1038                 return;
1039         }
1040         /*
1041          * We already have a wrap buffer, but it is too small. It might be
1042          * partially used.
1043          */
1044         if (wbr->wrap_count == sz1 && wbr->btrb->size >= sz1 + sz2) /* nothing we can do about it */
1045                 return;
1046         sz = sz1 + sz2 - wbr->btrb->size; /* amount of new data */
1047         PARA_DEBUG_LOG("increasing wrap buffer %zu -> %zu\n", wbr->btrb->size,
1048                 wbr->btrb->size + sz);
1049         wbr->btrb->size += sz;
1050         wbr->btrb->buf = para_realloc(wbr->btrb->buf, wbr->btrb->size);
1051         /* copy the new data to the end of the reallocated buffer */
1052         assert(sz2 >= sz);
1053         memcpy(wbr->btrb->buf + wbr->btrb->size - sz, buf2 + sz2 - sz, sz);
1054 }
1055
1056 /**
1057  * Merge the first two input buffers into one.
1058  *
1059  * This is a quite expensive operation.
1060  *
1061  * \return The number of buffers that have been available (zero, one or two).
1062  */
1063 static int merge_input(struct btr_node *btrn)
1064 {
1065         struct btr_buffer_reference *brs[2], *br;
1066         char *bufs[2], *buf;
1067         size_t szs[2], sz;
1068         int i;
1069
1070         if (list_empty(&btrn->input_queue))
1071                 return 0;
1072         if (list_is_singular(&btrn->input_queue))
1073                 return 1;
1074         i = 0;
1075         /* get references to the first two buffers */
1076         FOR_EACH_BUFFER_REF(br, btrn) {
1077                 brs[i] = br;
1078                 szs[i] = btr_get_buffer_by_reference(brs[i], bufs + i);
1079                 i++;
1080                 if (i == 2)
1081                         break;
1082         }
1083         assert(i == 2);
1084         /* make a new btrb that combines the two buffers and a br to it. */
1085         sz = szs[0] + szs[1];
1086         buf = alloc(sz);
1087         PARA_DEBUG_LOG("%s: memory merging input buffers: (%zu, %zu) -> %zu\n",
1088                 btrn->name, szs[0], szs[1], sz);
1089         memcpy(buf, bufs[0], szs[0]);
1090         memcpy(buf + szs[0], bufs[1], szs[1]);
1091
1092         br = zalloc(sizeof(*br));
1093         br->btrb = new_btrb(buf, sz);
1094         br->btrb->refcount = 1;
1095
1096         /* replace the first two refs by the new one */
1097         btr_drop_buffer_reference(brs[0]);
1098         btr_drop_buffer_reference(brs[1]);
1099         para_list_add(&br->node, &btrn->input_queue);
1100         return 2;
1101 }
1102
1103 /**
1104  * Combine input queue buffers.
1105  *
1106  * \param btrn The buffer tree node whose input should be merged.
1107  * \param dest_size Stop merging if a buffer of at least this size exists.
1108  *
1109  * Used to combine as many buffers as needed into a single buffer whose size is
1110  * at least \a dest_size. This function is rather cheap in case the parent node
1111  * uses buffer pools and rather expensive otherwise.
1112  *
1113  * Note that if less than \a dest_size bytes are available in total, this
1114  * function does nothing and subsequent calls to btr_next_buffer() will still
1115  * return a buffer size less than \a dest_size.
1116  */
1117 void btr_merge(struct btr_node *btrn, size_t dest_size)
1118 {
1119         if (need_buffer_pool_merge(btrn))
1120                 return merge_input_pool(btrn, dest_size);
1121         for (;;) {
1122                 char *buf;
1123                 size_t len = btr_next_buffer(btrn, &buf);
1124                 if (len >= dest_size)
1125                         return;
1126                 PARA_DEBUG_LOG("input size = %zu < %zu = dest\n", len, dest_size);
1127                 if (merge_input(btrn) < 2)
1128                         return;
1129         }
1130 }
1131
1132 static bool btr_eof(struct btr_node *btrn)
1133 {
1134         char *buf;
1135         size_t len = btr_next_buffer(btrn, &buf);
1136
1137         return (len == 0 && btr_no_parent(btrn));
1138 }
1139
1140 static void log_tree_recursively(struct btr_node *btrn, int loglevel, int depth)
1141 {
1142         struct btr_node *ch;
1143         const char spaces[] = "                 ", *space = spaces + 16 - depth;
1144
1145         if (depth > 16)
1146                 return;
1147         para_log(loglevel, "%s%s\n", space, btrn->name);
1148         FOR_EACH_CHILD(ch, btrn)
1149                 log_tree_recursively(ch, loglevel, depth + 1);
1150 }
1151
1152 /**
1153  * Write the current buffer (sub-)tree to the log.
1154  *
1155  * \param btrn Start logging at this node.
1156  * \param loglevel Set severity with which the tree should be logged.
1157  */
1158 void btr_log_tree(struct btr_node *btrn, int loglevel)
1159 {
1160         return log_tree_recursively(btrn, loglevel, 0);
1161 }
1162
1163 /**
1164  * Find the node with the given name in the buffer tree.
1165  *
1166  * \param name The name of the node to search.
1167  * \param root Where to start the search.
1168  *
1169  * \return A pointer to the node with the given name on success. If \a name is
1170  * \p NULL, the function returns \a root. If there is no node with the given
1171  * name, \p NULL is returned.
1172  */
1173 struct btr_node *btr_search_node(const char *name, struct btr_node *root)
1174 {
1175         struct btr_node *ch;
1176
1177         if (!name)
1178                 return root;
1179         if (!strcmp(root->name, name))
1180                 return root;
1181         FOR_EACH_CHILD(ch, root) {
1182                 struct btr_node *result = btr_search_node(name, ch);
1183                 if (result)
1184                         return result;
1185         }
1186         return NULL;
1187 }
1188
1189 /** 640K ought to be enough for everybody ;) */
1190 #define BTRN_MAX_PENDING (96 * 1024)
1191
1192 /**
1193  * Return the current state of a buffer tree node.
1194  *
1195  * \param btrn The node whose state should be queried.
1196  * \param min_iqs The minimal input queue size.
1197  * \param type The supposed type of \a btrn.
1198  *
1199  * Most users of the buffer tree subsystem call this function from both
1200  * their ->pre_monitor() and ->post_monitor() methods.
1201  *
1202  * \return Negative if an error condition was detected, zero if there
1203  * is nothing to do and positive otherwise.
1204  *
1205  * Examples:
1206  *
1207  * - If a non-root node has no parent and an empty input queue, the function
1208  * returns \p -E_BTR_EOF. Similarly, if a non-leaf node has no children, \p
1209  * -E_BTR_NO_CHILD is returned.
1210  *
1211  * - If less than \a min_iqs many bytes are available in the input queue and no
1212  * EOF condition was detected, the function returns zero.
1213  *
1214  * - If there's plenty of data left in the input queue of the children of \a
1215  * btrn, the function also returns zero in order to bound the memory usage of
1216  * the buffer tree.
1217  */
1218 int btr_node_status(struct btr_node *btrn, size_t min_iqs,
1219         enum btr_node_type type)
1220 {
1221         if (type != BTR_NT_LEAF && btr_no_children(btrn))
1222                 return -E_BTR_NO_CHILD;
1223         if (type != BTR_NT_ROOT && btr_eof(btrn))
1224                 return -E_EOF;
1225
1226         if (btr_get_output_queue_size(btrn) > BTRN_MAX_PENDING)
1227                 return 0;
1228         if (type == BTR_NT_ROOT)
1229                 return 1;
1230         if (min_iqs_available(min_iqs, btrn))
1231                 return 1;
1232         return btr_no_parent(btrn);
1233 }
1234
1235 /**
1236  * Get the time of the first I/O for a buffer tree node.
1237  *
1238  * \param btrn The node whose I/O time should be obtained.
1239  * \param tv Result pointer.
1240  *
1241  * Mainly useful for the time display of para_audiod.
1242  */
1243 void btr_get_node_start(struct btr_node *btrn, struct timeval *tv)
1244 {
1245         *tv = btrn->start;
1246 }
1247
1248 /**
1249  * Get the parent node of a buffer tree node.
1250  *
1251  * \param btrn The node whose parent should be returned.
1252  *
1253  * \a btrn must not be \p NULL.
1254  *
1255  * \return The parent of \a btrn, or \p NULL if \a btrn is the
1256  * root node of the buffer tree.
1257  */
1258 struct btr_node *btr_parent(struct btr_node *btrn)
1259 {
1260         return btrn->parent;
1261 }