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