2 * Copyright (C) 2009-2013 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file buffer_tree.c Buffer tree and buffer pool implementations. */
13 #include "buffer_tree.h"
17 /* whead = NULL means area full */
29 /** The number of references to this buffer. */
31 /* NULL means no buffer pool but a malloced buffer. */
32 struct btr_pool *pool;
33 /* Only relevant if pool is NULL. */
37 struct btr_buffer_reference {
38 struct btr_buffer *btrb;
40 /* Each buffer reference belongs to the buffer queue list of some buffer tree node. */
41 struct list_head node;
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. */
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.
59 struct list_head input_queue;
60 btr_command_handler execute;
65 * Create a new buffer pool.
67 * \param name The name of the new buffer pool.
68 * \param area_size The size in bytes of the pool area.
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
74 struct btr_pool *btr_pool_new(const char *name, size_t area_size)
76 struct btr_pool *btrp;
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);
89 * Deallocate resources used by a buffer pool.
91 * \param btrp A pointer obtained via btr_pool_new().
93 void btr_pool_free(struct btr_pool *btrp)
97 free(btrp->area_start);
103 * Return the size of the buffer pool area.
105 * \param btrp The buffer pool.
107 * \return The same value which was passed during creation time to
110 size_t btr_pool_size(struct btr_pool *btrp)
112 return btrp->area_end - btrp->area_start;
115 static size_t btr_pool_filled(struct btr_pool *btrp)
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);
125 * Get the number of unused bytes in the buffer pool.
127 * \param btrp The pool.
129 * \return The number of bytes that can currently be allocated.
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
136 size_t btr_pool_unused(struct btr_pool *btrp)
138 return btr_pool_size(btrp) - btr_pool_filled(btrp);
142 * Return maximal size available for one read. This is
143 * smaller than the value returned by btr_pool_unused().
145 static size_t btr_pool_available(struct btr_pool *btrp)
149 if (btrp->rhead <= btrp->whead)
150 return btrp->area_end - btrp->whead;
151 return btrp->rhead - btrp->whead;
155 * Obtain the current write head.
157 * \param btrp The buffer pool.
158 * \param result The write head is returned here.
160 * \return The maximal amount of bytes that may be written to the returned
163 size_t btr_pool_get_buffer(struct btr_pool *btrp, char **result)
166 *result = btrp->whead;
167 return btr_pool_available(btrp);
171 * Get references to buffers pointing to free space of the buffer pool area.
173 * \param btrp The buffer pool.
174 * \param iov The scatter array.
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.
181 int btr_pool_get_buffers(struct btr_pool *btrp, struct iovec iov[2])
186 sz = btr_pool_get_buffer(btrp, &buf);
190 iov[0].iov_base = buf;
191 unused = btr_pool_unused(btrp);
194 iov[1].iov_len = unused - sz;
195 iov[1].iov_base = btrp->area_start;
200 * Mark a part of the buffer pool area as allocated.
202 * \param btrp The buffer pool.
203 * \param size The amount of bytes to be allocated.
205 * This is usually called after the caller wrote to the buffer obtained by
206 * btr_pool_get_buffer().
208 static void btr_pool_allocate(struct btr_pool *btrp, size_t size)
214 assert(size <= btr_pool_available(btrp));
215 end = btrp->whead + size;
216 assert(end <= btrp->area_end);
218 if (end == btrp->area_end) {
219 PARA_DEBUG_LOG("%s: end of pool area reached\n", btrp->name);
220 end = btrp->area_start;
222 if (end == btrp->rhead) {
223 PARA_DEBUG_LOG("%s btrp buffer full\n", btrp->name);
224 end = NULL; /* buffer full */
229 static void btr_pool_deallocate(struct btr_pool *btrp, size_t size)
231 char *end = btrp->rhead + size;
235 assert(end <= btrp->area_end);
236 assert(size <= btr_pool_filled(btrp));
237 if (end == btrp->area_end)
238 end = btrp->area_start;
240 btrp->whead = btrp->rhead;
242 if (btrp->rhead == btrp->whead)
243 btrp->rhead = btrp->whead = btrp->area_start;
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)
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)
257 * Create a new buffer tree node.
259 * \param bnd Specifies how to create the new node.
261 * \return A pointer to the newly allocated node.
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().
267 struct btr_node *btr_new_node(struct btr_node_description *bnd)
269 struct btr_node *btrn = para_malloc(sizeof(*btrn));
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);
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);
285 PARA_INFO_LOG("added %s as btr root\n", bnd->name);
289 assert(!bnd->child->parent);
290 PARA_INFO_LOG("new root: %s (was %s)\n",
291 bnd->name, bnd->child->name);
293 list_add_tail(&bnd->child->node, &btrn->children);
295 bnd->child->parent = btrn;
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);
307 * Allocate a new btr buffer.
309 * The freshly allocated buffer will have a zero refcount and will
310 * not be associated with a btr pool.
312 static struct btr_buffer *new_btrb(char *buf, size_t size)
314 struct btr_buffer *btrb = para_calloc(sizeof(*btrb));
321 static void dealloc_buffer(struct btr_buffer *btrb)
324 btr_pool_deallocate(btrb->pool, btrb->size);
325 else if (!btrb->dont_free)
329 static struct btr_buffer_reference *get_first_input_br(struct btr_node *btrn)
331 if (list_empty(&btrn->input_queue))
333 return list_first_entry(&btrn->input_queue,
334 struct btr_buffer_reference, node);
338 * Deallocate the reference, release the resources if refcount drops to zero.
340 static void btr_drop_buffer_reference(struct btr_buffer_reference *br)
342 struct btr_buffer *btrb = br->btrb;
347 if (btrb->refcount == 0) {
348 dealloc_buffer(btrb);
353 static void add_btrb_to_children(struct btr_buffer *btrb,
354 struct btr_node *btrn, size_t consumed)
358 if (btrn->start.tv_sec == 0)
360 FOR_EACH_CHILD(ch, btrn) {
361 struct btr_buffer_reference *br = para_calloc(sizeof(*br));
363 br->consumed = consumed;
364 list_add_tail(&br->node, &ch->input_queue);
366 if (ch->start.tv_sec == 0)
372 * Insert a malloced buffer into the buffer tree.
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.
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.
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.
385 void btr_add_output(char *buf, size_t size, struct btr_node *btrn)
387 struct btr_buffer *btrb;
391 if (list_empty(&btrn->children)) {
395 btrb = new_btrb(buf, size);
396 add_btrb_to_children(btrb, btrn, 0);
400 * Insert a buffer into the buffer tree, non-freeing variant.
402 * \param buf See \ref btr_add_output().
403 * \param size See \ref btr_add_output().
404 * \param btrn See \ref btr_add_output().
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.
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
415 void btr_add_output_dont_free(const char *buf, size_t size, struct btr_node *btrn)
417 struct btr_buffer *btrb;
421 if (list_empty(&btrn->children))
423 btrb = new_btrb((char *)buf, size);
424 btrb->dont_free = true;
425 add_btrb_to_children(btrb, btrn, 0);
429 * Feed data to child nodes of a buffer tree node.
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.
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.
440 void btr_add_output_pool(struct btr_pool *btrp, size_t size,
441 struct btr_node *btrn)
443 struct btr_buffer *btrb;
449 if (list_empty(&btrn->children))
451 avail = btr_pool_get_buffer(btrp, &buf);
452 assert(avail >= size);
453 btr_pool_allocate(btrp, size);
454 btrb = new_btrb(buf, size);
456 add_btrb_to_children(btrb, btrn, 0);
460 * Copy data to write head of a buffer pool and feed it to all children nodes.
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.
467 * This is expensive. The caller must make sure the data fits into the buffer
470 void btr_copy(const void *src, size_t n, struct btr_pool *btrp,
471 struct btr_node *btrn)
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);
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);
491 static void btr_pushdown_br(struct btr_buffer_reference *br, struct btr_node *btrn)
493 add_btrb_to_children(br->btrb, btrn, br->consumed);
494 btr_drop_buffer_reference(br);
498 * Feed all buffer references of the input queue through the output channel.
500 * \param btrn The node whose buffer references should be pushed down.
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.
506 * \sa \ref btr_pushdown_one().
508 void btr_pushdown(struct btr_node *btrn)
510 struct btr_buffer_reference *br, *tmp;
512 FOR_EACH_BUFFER_REF_SAFE(br, tmp, btrn)
513 btr_pushdown_br(br, btrn);
517 * Feed the next buffer of the input queue through the output channel.
519 * \param btrn The node whose first input queue buffer should be pushed down.
521 * This works like \ref btr_pushdown() but pushes down only one buffer
524 void btr_pushdown_one(struct btr_node *btrn)
526 struct btr_buffer_reference *br;
528 if (list_empty(&btrn->input_queue))
530 br = list_first_entry(&btrn->input_queue, struct btr_buffer_reference, node);
531 btr_pushdown_br(br, btrn);
535 * Find out whether a node is a leaf node.
537 * \param btrn The node to check.
539 * \return True if this node has no children. False otherwise.
541 static bool btr_no_children(struct btr_node *btrn)
543 return list_empty(&btrn->children);
547 * Find out whether a node is an orphan node.
549 * \param btrn The buffer tree node.
551 * \return True if \a btrn has no parent.
553 * This function will always return true for the root node. However in case
554 * nodes have been removed from the tree, other nodes may become orphans too.
556 bool btr_no_parent(struct btr_node *btrn)
558 return !btrn->parent;
562 * Find out whether it is OK to change an input buffer.
564 * \param btrn The buffer tree node to check.
566 * This is used by filters that produce exactly the same amount of output as
567 * there is input. The amp filter which multiplies each sample by some number
568 * is an example of such a filter. If there are no other nodes in the buffer
569 * tree that read the same input stream (i.e. if \a btrn has no siblings), a
570 * node may modify its input buffer directly and push down the modified buffer
571 * to its children, thereby avoiding to allocate a possibly large additional
574 * Since the buffer tree may change at any time, this function should be called
575 * during each post_select call.
577 * \return True if \a btrn has no siblings.
579 bool btr_inplace_ok(struct btr_node *btrn)
581 struct btr_buffer_reference *br;
582 FOR_EACH_BUFFER_REF(br, btrn) {
583 struct btr_buffer *btrb = br->btrb;
584 if (btrb->refcount > 1)
586 if (btrb->dont_free == true)
592 static inline size_t br_available_bytes(struct btr_buffer_reference *br)
594 return br->btrb->size - br->consumed;
597 static size_t btr_get_buffer_by_reference(struct btr_buffer_reference *br, char **buf)
600 *buf = br->btrb->buf + br->consumed;
601 return br_available_bytes(br);
605 * Obtain the next buffer of the input queue, omitting data.
607 * \param btrn The node whose input queue is to be queried.
608 * \param omit Number of bytes to be omitted.
609 * \param bufp Result pointer. It is OK to pass \p NULL here.
611 * If a buffer tree node needs more input data but can not consume the data it
612 * already has (because it might be needed again later) this function can be
613 * used instead of btr_next_buffer() to get a reference to the buffer obtained
614 * by skipping the given number of bytes. Skipped input bytes are not consumed.
616 * With a zero \a omit argument, this function is equivalent to \ref
619 * \return Number of bytes in \a bufp. If there are less than or equal to \a
620 * omit many bytes available in the input queue of the buffer tree node pointed
621 * to by \a btrn, the function returns zero and the value of \a bufp is
624 size_t btr_next_buffer_omit(struct btr_node *btrn, size_t omit, char **bufp)
626 struct btr_buffer_reference *br;
627 size_t wrap_count, sz, rv = 0;
628 char *buf, *result = NULL;
630 br = get_first_input_br(btrn);
633 wrap_count = br->wrap_count;
634 if (wrap_count > 0) { /* we have a wrap buffer */
635 sz = btr_get_buffer_by_reference(br, &buf);
636 if (sz > omit) { /* and it's big enough */
640 * Wrap buffers are allocated by malloc(), so the next
641 * buffer ref will not align nicely, so we return the
642 * tail of the wrap buffer.
647 * The next wrap_count bytes exist twice, in the wrap buffer
648 * and as a buffer reference in the buffer tree pool.
653 * For buffer tree pools, the buffers in the list align, i.e. the next
654 * buffer in the list starts directly at the end of its predecessor. In
655 * this case we merge adjacent buffers and return one larger buffer
658 FOR_EACH_BUFFER_REF(br, btrn) {
659 sz = btr_get_buffer_by_reference(br, &buf);
661 if (result + rv != buf)
664 } else if (sz > omit) {
679 * Obtain the next buffer of the input queue of a buffer tree node.
681 * \param btrn The node whose input queue is to be queried.
682 * \param bufp Result pointer.
684 * \return The number of bytes that can be read from buf.
686 * The call of this function is is equivalent to calling \ref
687 * btr_next_buffer_omit() with an \a omit value of zero.
689 size_t btr_next_buffer(struct btr_node *btrn, char **bufp)
691 return btr_next_buffer_omit(btrn, 0, bufp);
695 * Deallocate the given number of bytes from the input queue.
697 * \param btrn The buffer tree node.
698 * \param numbytes The number of bytes to be deallocated.
700 * This function must be used to get rid of existing buffer references in the
701 * node's input queue. If no references to a buffer remain, the underlying
702 * buffers are either freed (in the non-buffer pool case) or the read head of
703 * the buffer pool is being advanced.
705 * Note that \a numbytes may be smaller than the buffer size. In this case the
706 * buffer is not deallocated and subsequent calls to btr_next_buffer() return
707 * the remaining part of the buffer.
709 void btr_consume(struct btr_node *btrn, size_t numbytes)
711 struct btr_buffer_reference *br, *tmp;
716 br = get_first_input_br(btrn);
719 if (br->wrap_count == 0) {
721 * No wrap buffer. Drop buffer references whose buffer
722 * has been fully used. */
723 FOR_EACH_BUFFER_REF_SAFE(br, tmp, btrn) {
724 if (br->consumed + numbytes <= br->btrb->size) {
725 br->consumed += numbytes;
726 if (br->consumed == br->btrb->size)
727 btr_drop_buffer_reference(br);
730 numbytes -= br->btrb->size - br->consumed;
731 btr_drop_buffer_reference(br);
736 * We have a wrap buffer, consume from it. If in total, i.e. including
737 * previous calls to brt_consume(), less than wrap_count has been
738 * consumed, there's nothing more we can do.
740 * Otherwise we drop the wrap buffer and consume from subsequent
741 * buffers of the input queue the correct amount of bytes. This is the
742 * total number of bytes that have been consumed from the wrap buffer.
744 PARA_DEBUG_LOG("consuming %zu/%zu bytes from wrap buffer\n", numbytes,
745 br_available_bytes(br));
747 assert(numbytes <= br_available_bytes(br));
748 if (br->consumed + numbytes < br->wrap_count) {
749 br->consumed += numbytes;
752 PARA_DEBUG_LOG("dropping wrap buffer (%zu bytes)\n", br->btrb->size);
753 /* get rid of the wrap buffer */
754 sz = br->consumed + numbytes;
755 btr_drop_buffer_reference(br);
756 return btr_consume(btrn, sz);
760 * Clear the input queue of a buffer tree node.
762 * \param btrn The node whose input queue should be cleared.
764 void btr_drain(struct btr_node *btrn)
766 struct btr_buffer_reference *br, *tmp;
768 FOR_EACH_BUFFER_REF_SAFE(br, tmp, btrn)
769 btr_drop_buffer_reference(br);
773 * Remove a node from a buffer tree.
775 * \param btrnp Determines the node to remove.
777 * This orphans all children of the node given by \a btrnp and removes this
778 * node from the child list of its parent. Moreover, the input queue is flushed
779 * and the node pointer given by \a btrp is set to \p NULL.
781 * \sa \ref btr_splice_out_node.
783 void btr_remove_node(struct btr_node **btrnp)
786 struct btr_node *btrn;
793 PARA_INFO_LOG("removing btr node %s from buffer tree\n", btrn->name);
794 FOR_EACH_CHILD(ch, btrn)
798 list_del(&btrn->node);
806 * Return the amount of available input bytes of a buffer tree node.
808 * \param btrn The node whose input size should be computed.
810 * \return The total number of bytes available in the node's input
813 * This simply iterates over all buffer references in the input queue and
814 * returns the sum of the sizes of all references.
816 size_t btr_get_input_queue_size(struct btr_node *btrn)
818 struct btr_buffer_reference *br;
819 size_t size = 0, wrap_consumed = 0;
821 FOR_EACH_BUFFER_REF(br, btrn) {
822 if (br->wrap_count != 0) {
823 wrap_consumed = br->consumed;
826 size += br_available_bytes(br);
828 assert(wrap_consumed <= size);
829 size -= wrap_consumed;
834 * Remove a node from the buffer tree, reconnecting parent and children.
836 * \param btrn The node to splice out.
838 * This function is used by buffer tree nodes that do not exist during the
839 * whole lifetime of the buffer tree. Unlike btr_remove_node(), calling
840 * btr_splice_out_node() does not split the tree into disconnected components
841 * but reconnects the buffer tree by making all child nodes of \a btrn children
842 * of the parent of \a btrn.
844 void btr_splice_out_node(struct btr_node *btrn)
846 struct btr_node *ch, *tmp;
849 PARA_NOTICE_LOG("splicing out %s\n", btrn->name);
852 list_del(&btrn->node);
853 FOR_EACH_CHILD_SAFE(ch, tmp, btrn) {
854 PARA_INFO_LOG("parent(%s): %s\n", ch->name,
855 btrn->parent? btrn->parent->name : "NULL");
856 ch->parent = btrn->parent;
858 list_move(&ch->node, &btrn->parent->children);
860 assert(list_empty(&btrn->children));
865 * Return number of queued output bytes of a buffer tree node.
867 * \param btrn The node whose output queue size should be computed.
869 * \return This function iterates over all children of the given node and
870 * returns the size of the largest input queue.
872 size_t btr_get_output_queue_size(struct btr_node *btrn)
877 FOR_EACH_CHILD(ch, btrn) {
878 size_t size = btr_get_input_queue_size(ch);
879 max_size = PARA_MAX(max_size, size);
885 * Execute an inter-node command on the given node or on a parent node.
887 * \param btrn The node to start looking.
888 * \param command The command to execute.
889 * \param value_result Additional arguments and result value.
891 * This function traverses the buffer tree from \a btrn upwards and looks for
892 * the first node that understands \a command. On this node \a command is
893 * executed, and the result is stored in \a value_result.
895 * \return \p -ENOTSUP if no parent node of \a btrn understands \a command.
896 * Otherwise the return value of the command handler is returned.
898 * \sa \ref receiver::execute, filter::execute, writer::execute.
900 int btr_exec_up(struct btr_node *btrn, const char *command, char **value_result)
904 for (; btrn; btrn = btrn->parent) {
907 PARA_INFO_LOG("executing %s on %s\n", command, btrn->name);
908 ret = btrn->execute(btrn, command, value_result);
909 if (ret == -ERRNO_TO_PARA_ERROR(ENOTSUP))
913 if (value_result && *value_result)
914 PARA_INFO_LOG("%s(%s): %s\n", command, btrn->name,
918 return -ERRNO_TO_PARA_ERROR(ENOTSUP);
922 * Obtain the context of a buffer node tree.
924 * \param btrn The node whose output queue size should be computed.
926 * \return A pointer to the \a context address specified at node creation time.
928 * \sa btr_new_node(), struct \ref btr_node_description.
930 void *btr_context(struct btr_node *btrn)
932 return btrn->context;
935 static bool need_buffer_pool_merge(struct btr_node *btrn)
937 struct btr_buffer_reference *br = get_first_input_br(btrn);
941 if (br->wrap_count != 0)
948 static void merge_input_pool(struct btr_node *btrn, size_t dest_size)
950 struct btr_buffer_reference *br, *wbr = NULL;
951 int num_refs; /* including wrap buffer */
952 char *buf, *buf1 = NULL, *buf2 = NULL;
953 size_t sz, sz1 = 0, sz2 = 0, wb_consumed = 0;
955 br = get_first_input_br(btrn);
956 if (!br || br_available_bytes(br) >= dest_size)
959 FOR_EACH_BUFFER_REF(br, btrn) {
961 sz = btr_get_buffer_by_reference(br, &buf);
964 if (br->wrap_count != 0) {
966 assert(num_refs == 1);
970 wb_consumed = br->consumed;
978 if (buf1 + sz1 == buf) {
987 assert(buf2 + sz2 == buf);
990 if (sz1 + sz2 >= dest_size + wb_consumed)
993 if (!buf2) /* nothing to do */
995 assert(buf1 && sz2 > 0);
997 * If the second buffer is large, we only take the first part of it to
998 * avoid having to memcpy() huge buffers.
1000 sz2 = PARA_MIN(sz2, (size_t)(64 * 1024));
1002 /* Make a new wrap buffer combining buf1 and buf2. */
1004 buf = para_malloc(sz);
1005 PARA_DEBUG_LOG("merging input buffers: (%p:%zu, %p:%zu) -> %p:%zu\n",
1006 buf1, sz1, buf2, sz2, buf, sz);
1007 memcpy(buf, buf1, sz1);
1008 memcpy(buf + sz1, buf2, sz2);
1009 br = para_calloc(sizeof(*br));
1010 br->btrb = new_btrb(buf, sz);
1011 br->btrb->refcount = 1;
1013 /* This is a wrap buffer */
1014 br->wrap_count = sz1;
1015 para_list_add(&br->node, &btrn->input_queue);
1019 * We already have a wrap buffer, but it is too small. It might be
1022 if (wbr->wrap_count == sz1 && wbr->btrb->size >= sz1 + sz2) /* nothing we can do about it */
1024 sz = sz1 + sz2 - wbr->btrb->size; /* amount of new data */
1025 PARA_DEBUG_LOG("increasing wrap buffer %zu -> %zu\n", wbr->btrb->size,
1026 wbr->btrb->size + sz);
1027 wbr->btrb->size += sz;
1028 wbr->btrb->buf = para_realloc(wbr->btrb->buf, wbr->btrb->size);
1029 /* copy the new data to the end of the reallocated buffer */
1031 memcpy(wbr->btrb->buf + wbr->btrb->size - sz, buf2 + sz2 - sz, sz);
1035 * Merge the first two input buffers into one.
1037 * This is a quite expensive operation.
1039 * \return The number of buffers that have been available (zero, one or two).
1041 static int merge_input(struct btr_node *btrn)
1043 struct btr_buffer_reference *brs[2], *br;
1044 char *bufs[2], *buf;
1048 if (list_empty(&btrn->input_queue))
1050 if (list_is_singular(&btrn->input_queue))
1053 /* get references to the first two buffers */
1054 FOR_EACH_BUFFER_REF(br, btrn) {
1056 szs[i] = btr_get_buffer_by_reference(brs[i], bufs + i);
1062 /* make a new btrb that combines the two buffers and a br to it. */
1063 sz = szs[0] + szs[1];
1064 buf = para_malloc(sz);
1065 PARA_DEBUG_LOG("%s: memory merging input buffers: (%zu, %zu) -> %zu\n",
1066 btrn->name, szs[0], szs[1], sz);
1067 memcpy(buf, bufs[0], szs[0]);
1068 memcpy(buf + szs[0], bufs[1], szs[1]);
1070 br = para_calloc(sizeof(*br));
1071 br->btrb = new_btrb(buf, sz);
1072 br->btrb->refcount = 1;
1074 /* replace the first two refs by the new one */
1075 btr_drop_buffer_reference(brs[0]);
1076 btr_drop_buffer_reference(brs[1]);
1077 para_list_add(&br->node, &btrn->input_queue);
1082 * Combine input queue buffers.
1084 * \param btrn The buffer tree node whose input should be merged.
1085 * \param dest_size Stop merging if a buffer of at least this size exists.
1087 * Used to combine as many buffers as needed into a single buffer whose size is
1088 * at least \a dest_size. This function is rather cheap in case the parent node
1089 * uses buffer pools and rather expensive otherwise.
1091 * Note that if less than \a dest_size bytes are available in total, this
1092 * function does nothing and subsequent calls to btr_next_buffer() will still
1093 * return a buffer size less than \a dest_size.
1095 void btr_merge(struct btr_node *btrn, size_t dest_size)
1097 if (need_buffer_pool_merge(btrn))
1098 return merge_input_pool(btrn, dest_size);
1101 size_t len = btr_next_buffer(btrn, &buf);
1102 if (len >= dest_size)
1104 PARA_DEBUG_LOG("input size = %zu < %zu = dest\n", len, dest_size);
1105 if (merge_input(btrn) < 2)
1110 static bool btr_eof(struct btr_node *btrn)
1113 size_t len = btr_next_buffer(btrn, &buf);
1115 return (len == 0 && btr_no_parent(btrn));
1118 static void log_tree_recursively(struct btr_node *btrn, int loglevel, int depth)
1120 struct btr_node *ch;
1121 const char spaces[] = " ", *space = spaces + 16 - depth;
1125 para_log(loglevel, "%s%s\n", space, btrn->name);
1126 FOR_EACH_CHILD(ch, btrn)
1127 log_tree_recursively(ch, loglevel, depth + 1);
1131 * Write the current buffer (sub-)tree to the log.
1133 * \param btrn Start logging at this node.
1134 * \param loglevel Set severity with which the tree should be logged.
1136 void btr_log_tree(struct btr_node *btrn, int loglevel)
1138 return log_tree_recursively(btrn, loglevel, 0);
1142 * Find the node with the given name in the buffer tree.
1144 * \param name The name of the node to search.
1145 * \param root Where to start the search.
1147 * \return A pointer to the node with the given name on success. If \a name is
1148 * \p NULL, the function returns \a root. If there is no node with the given
1149 * name, \p NULL is returned.
1151 struct btr_node *btr_search_node(const char *name, struct btr_node *root)
1153 struct btr_node *ch;
1157 if (!strcmp(root->name, name))
1159 FOR_EACH_CHILD(ch, root) {
1160 struct btr_node *result = btr_search_node(name, ch);
1167 /** 640K ought to be enough for everybody ;) */
1168 #define BTRN_MAX_PENDING (96 * 1024)
1171 * Return the current state of a buffer tree node.
1173 * \param btrn The node whose state should be queried.
1174 * \param min_iqs The minimal input queue size.
1175 * \param type The supposed type of \a btrn.
1177 * Most users of the buffer tree subsystem call this function from both
1178 * their pre_select and the post_select methods.
1180 * \return Negative if an error condition was detected, zero if there
1181 * is nothing to do and positive otherwise.
1185 * - If a non-root node has no parent and an empty input queue, the function
1186 * returns \p -E_BTR_EOF. Similarly, if a non-leaf node has no children, \p
1187 * -E_BTR_NO_CHILD is returned.
1189 * - If less than \a min_iqs many bytes are available in the input queue and no
1190 * EOF condition was detected, the function returns zero.
1192 * - If there's plenty of data left in the input queue of the children of \a
1193 * btrn, the function also returns zero in order to bound the memory usage of
1196 int btr_node_status(struct btr_node *btrn, size_t min_iqs,
1197 enum btr_node_type type)
1202 if (type != BTR_NT_LEAF) {
1203 if (btr_no_children(btrn))
1204 return -E_BTR_NO_CHILD;
1205 if (btr_get_output_queue_size(btrn) > BTRN_MAX_PENDING)
1208 if (type != BTR_NT_ROOT) {
1211 iqs = btr_get_input_queue_size(btrn);
1212 if (iqs == 0) /* we have a parent, because not eof */
1214 if (iqs < min_iqs && !btr_no_parent(btrn))
1221 * Get the time of the first I/O for a buffer tree node.
1223 * \param btrn The node whose I/O time should be obtained.
1224 * \param tv Result pointer.
1226 * Mainly useful for the time display of para_audiod.
1228 void btr_get_node_start(struct btr_node *btrn, struct timeval *tv)
1233 struct btr_node *btr_parent(struct btr_node *btrn)
1235 return btrn->parent;