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