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