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