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