RC4: Fix invalid read.
[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  * This function always succeeds (or calls exit()). The returned pointer must
261  * be freed using btr_free_node() after the node has been removed from the
262  * buffer tree via btr_remove_node().
263  */
264 struct btr_node *btr_new_node(struct btr_node_description *bnd)
265 {
266         struct btr_node *btrn = para_malloc(sizeof(*btrn));
267
268         btrn->name = para_strdup(bnd->name);
269         btrn->parent = bnd->parent;
270         btrn->execute = bnd->handler;
271         btrn->context = bnd->context;
272         btrn->start.tv_sec = 0;
273         btrn->start.tv_usec = 0;
274         INIT_LIST_HEAD(&btrn->children);
275         INIT_LIST_HEAD(&btrn->input_queue);
276         if (!bnd->child) {
277                 if (bnd->parent) {
278                         list_add_tail(&btrn->node, &bnd->parent->children);
279                         PARA_INFO_LOG("new leaf node: %s (child of %s)\n",
280                                 bnd->name, bnd->parent->name);
281                 } else
282                         PARA_INFO_LOG("added %s as btr root\n", bnd->name);
283                 goto out;
284         }
285         if (!bnd->parent) {
286                 assert(!bnd->child->parent);
287                 PARA_INFO_LOG("new root: %s (was %s)\n",
288                         bnd->name, bnd->child->name);
289                 btrn->parent = NULL;
290                 list_add_tail(&bnd->child->node, &btrn->children);
291                 /* link it in */
292                 bnd->child->parent = btrn;
293                 goto out;
294         }
295         PARA_EMERG_LOG("inserting internal nodes not yet supported.\n");
296         exit(EXIT_FAILURE);
297         assert(bnd->child->parent == bnd->parent);
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 = para_calloc(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
322                 free(btrb->buf);
323 }
324
325 static struct btr_buffer_reference *get_first_input_br(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 /*
334  * Deallocate the reference, release the resources if refcount drops to zero.
335  */
336 static void btr_drop_buffer_reference(struct btr_buffer_reference *br)
337 {
338         struct btr_buffer *btrb = br->btrb;
339
340         list_del(&br->node);
341         free(br);
342         btrb->refcount--;
343         if (btrb->refcount == 0) {
344                 dealloc_buffer(btrb);
345                 free(btrb);
346         }
347 }
348
349 static void add_btrb_to_children(struct btr_buffer *btrb,
350                 struct btr_node *btrn, size_t consumed)
351 {
352         struct btr_node *ch;
353
354         if (btrn->start.tv_sec == 0)
355                 btrn->start = *now;
356         FOR_EACH_CHILD(ch, btrn) {
357                 struct btr_buffer_reference *br = para_calloc(sizeof(*br));
358                 br->btrb = btrb;
359                 br->consumed = consumed;
360                 list_add_tail(&br->node, &ch->input_queue);
361                 btrb->refcount++;
362                 if (ch->start.tv_sec == 0)
363                         ch->start = *now;
364         }
365 }
366
367 /**
368  * Insert a malloced buffer into the buffer tree.
369  *
370  * \param buf The buffer to insert.
371  * \param size The size of \a buf in bytes.
372  * \param btrn Position in the buffer tree to create the output.
373  *
374  * This creates references to \a buf and adds these references to each child of
375  * \a btrn. The buffer will be freed using standard free() once no buffer tree
376  * node is referencing it any more.
377  *
378  * Note that this function must not be used if \a buf was obtained from a
379  * buffer pool. Use btr_add_output_pool() in this case.
380  */
381 void btr_add_output(char *buf, size_t size, struct btr_node *btrn)
382 {
383         struct btr_buffer *btrb;
384
385         assert(size != 0);
386         if (list_empty(&btrn->children)) {
387                 free(buf);
388                 return;
389         }
390         btrb = new_btrb(buf, size);
391         add_btrb_to_children(btrb, btrn, 0);
392 }
393
394 /**
395  * Feed data to child nodes of a buffer tree node.
396  *
397  * \param btrp The buffer pool.
398  * \param size The number of bytes to be allocated and fed to each child.
399  * \param btrn The node whose children are to be fed.
400  *
401  * This function allocates the amount of bytes from the buffer pool area,
402  * starting at the current value of the write head, and creates buffer
403  * references to the resulting part of the buffer pool area, one for each child
404  * of \a btrn. The references are then fed into the input queue of each child.
405  */
406 void btr_add_output_pool(struct btr_pool *btrp, size_t size,
407                 struct btr_node *btrn)
408 {
409         struct btr_buffer *btrb;
410         char *buf;
411         size_t avail;
412
413         assert(size != 0);
414         if (list_empty(&btrn->children))
415                 return;
416         avail = btr_pool_get_buffer(btrp, &buf);
417         assert(avail >= size);
418         btr_pool_allocate(btrp, size);
419         btrb = new_btrb(buf, size);
420         btrb->pool = btrp;
421         add_btrb_to_children(btrb, btrn, 0);
422 }
423
424 /**
425  * Copy data to write head of a buffer pool and feed it to all children nodes.
426  *
427  * \param src The source buffer.
428  * \param n The size of the source buffer in bytes.
429  * \param btrp The destination buffer pool.
430  * \param btrn Add the data as output of this node.
431  *
432  * This is expensive. The caller must make sure the data fits into the buffer
433  * pool area.
434  */
435 void btr_copy(const void *src, size_t n, struct btr_pool *btrp,
436         struct btr_node *btrn)
437 {
438         char *buf;
439         size_t sz, copy;
440
441         if (n == 0)
442                 return;
443         assert(n <= btr_pool_unused(btrp));
444         sz = btr_pool_get_buffer(btrp, &buf);
445         copy = PARA_MIN(sz, n);
446         memcpy(buf, src, copy);
447         btr_add_output_pool(btrp, copy, btrn);
448         if (copy == n)
449                 return;
450         sz = btr_pool_get_buffer(btrp, &buf);
451         assert(sz >= n - copy);
452         memcpy(buf, src + copy, n - copy);
453         btr_add_output_pool(btrp, n - copy, btrn);
454 }
455
456 static void btr_pushdown_br(struct btr_buffer_reference *br, struct btr_node *btrn)
457 {
458         add_btrb_to_children(br->btrb, btrn, br->consumed);
459         btr_drop_buffer_reference(br);
460 }
461
462 /**
463  * Feed all buffer references of the input queue through the output channel.
464  *
465  * \param btrn The node whose buffer references should be pushed down.
466  *
467  * This function is useful for filters that do not change the contents of the
468  * buffers at all, like the wav filter or the amp filter if no amplification
469  * was specified. This function is rather cheap.
470  *
471  * \sa \ref btr_pushdown_one().
472  */
473 void btr_pushdown(struct btr_node *btrn)
474 {
475         struct btr_buffer_reference *br, *tmp;
476
477         FOR_EACH_BUFFER_REF_SAFE(br, tmp, btrn)
478                 btr_pushdown_br(br, btrn);
479 }
480
481 /**
482  * Feed the next buffer of the input queue through the output channel.
483  *
484  * \param btrn The node whose first input queue buffer should be pushed down.
485  *
486  * This works like \ref btr_pushdown() but pushes down only one buffer
487  * reference.
488  */
489 void btr_pushdown_one(struct btr_node *btrn)
490 {
491         struct btr_buffer_reference *br;
492
493         if (list_empty(&btrn->input_queue))
494                 return;
495         br = list_first_entry(&btrn->input_queue, struct btr_buffer_reference, node);
496         btr_pushdown_br(br, btrn);
497 }
498
499 /*
500  * Find out whether a node is a leaf node.
501  *
502  * \param btrn The node to check.
503  *
504  * \return True if this node has no children. False otherwise.
505  */
506 static bool btr_no_children(struct btr_node *btrn)
507 {
508         return list_empty(&btrn->children);
509 }
510
511 /**
512  * Find out whether a node is an orphan node.
513  *
514  * \param btrn The buffer tree node.
515  *
516  * \return True if \a btrn has no parent.
517  *
518  * This function will always return true for the root node.  However in case
519  * nodes have been removed from the tree, other nodes may become orphans too.
520  */
521 bool btr_no_parent(struct btr_node *btrn)
522 {
523         return !btrn->parent;
524 }
525
526 /**
527  * Find out whether it is OK to change an input buffer.
528  *
529  * \param btrn The buffer tree node to check.
530  *
531  * This is used by filters that produce exactly the same amount of output as
532  * there is input. The amp filter which multiplies each sample by some number
533  * is an example of such a filter. If there are no other nodes in the buffer
534  * tree that read the same input stream (i.e. if \a btrn has no siblings), a
535  * node may modify its input buffer directly and push down the modified buffer
536  * to its children, thereby avoiding to allocate a possibly large additional
537  * buffer.
538  *
539  * Since the buffer tree may change at any time, this function should be called
540  * during each post_select call.
541  *
542  * \return True if \a btrn has no siblings.
543  */
544 bool btr_inplace_ok(struct btr_node *btrn)
545 {
546         if (!btrn->parent)
547                 return true;
548         return list_is_singular(&btrn->parent->children);
549 }
550
551 static inline size_t br_available_bytes(struct btr_buffer_reference *br)
552 {
553         return br->btrb->size - br->consumed;
554 }
555
556 static size_t btr_get_buffer_by_reference(struct btr_buffer_reference *br, char **buf)
557 {
558         if (buf)
559                 *buf = br->btrb->buf + br->consumed;
560         return br_available_bytes(br);
561 }
562
563 /**
564  * Obtain the next buffer of the input queue of a buffer tree node.
565  *
566  * \param btrn The node whose input queue is to be queried.
567  * \param bufp Result pointer.
568  *
569  * \return The number of bytes that can be read from buf. Zero if the input
570  * buffer queue is empty. In this case the value of \a bufp is undefined.
571  */
572 size_t btr_next_buffer(struct btr_node *btrn, char **bufp)
573 {
574         struct btr_buffer_reference *br;
575         char *buf, *result = NULL;
576         size_t sz, rv = 0;
577
578         FOR_EACH_BUFFER_REF(br, btrn) {
579                 sz = btr_get_buffer_by_reference(br, &buf);
580                 if (!result) {
581                         result = buf;
582                         rv = sz;
583                         if (!br->btrb->pool)
584                                 break;
585                         continue;
586                 }
587                 if (!br->btrb->pool)
588                         break;
589                 if (result + rv != buf)
590                         break;
591                 rv += sz;
592         }
593         if (bufp)
594                 *bufp = result;
595         return rv;
596 }
597
598 /**
599  * Deallocate the given number of bytes from the input queue.
600  *
601  * \param btrn The buffer tree node.
602  * \param numbytes The number of bytes to be deallocated.
603  *
604  * This function must be used to get rid of existing buffer references in the
605  * node's input queue. If no references to a buffer remain, the underlying
606  * buffers are either freed (in the non-buffer pool case) or the read head of
607  * the buffer pool is being advanced.
608  *
609  * Note that \a numbytes may be smaller than the buffer size. In this case the
610  * buffer is not deallocated and subsequent calls to btr_next_buffer() return
611  * the remaining part of the buffer.
612  */
613 void btr_consume(struct btr_node *btrn, size_t numbytes)
614 {
615         struct btr_buffer_reference *br, *tmp;
616         size_t sz;
617
618         if (numbytes == 0)
619                 return;
620         br = get_first_input_br(btrn);
621         assert(br);
622
623         if (br->wrap_count == 0) {
624                 /*
625                  * No wrap buffer. Drop buffer references whose buffer
626                  * has been fully used. */
627                 FOR_EACH_BUFFER_REF_SAFE(br, tmp, btrn) {
628                         if (br->consumed + numbytes <= br->btrb->size) {
629                                 br->consumed += numbytes;
630                                 if (br->consumed == br->btrb->size)
631                                         btr_drop_buffer_reference(br);
632                                 return;
633                         }
634                         numbytes -= br->btrb->size - br->consumed;
635                         btr_drop_buffer_reference(br);
636                 }
637                 assert(false);
638         }
639         /*
640          * We have a wrap buffer, consume from it. If in total, i.e. including
641          * previous calls to brt_consume(), less than wrap_count has been
642          * consumed, there's nothing more we can do.
643          *
644          * Otherwise we drop the wrap buffer and consume from subsequent
645          * buffers of the input queue the correct amount of bytes. This is the
646          * total number of bytes that have been consumed from the wrap buffer.
647          */
648         PARA_DEBUG_LOG("consuming %zu/%zu bytes from wrap buffer\n", numbytes,
649                 br_available_bytes(br));
650
651         assert(numbytes <= br_available_bytes(br));
652         if (br->consumed + numbytes < br->wrap_count) {
653                 br->consumed += numbytes;
654                 return;
655         }
656         PARA_DEBUG_LOG("dropping wrap buffer (%zu bytes)\n", br->btrb->size);
657         /* get rid of the wrap buffer */
658         sz = br->consumed + numbytes;
659         btr_drop_buffer_reference(br);
660         return btr_consume(btrn, sz);
661 }
662
663 void btr_drain(struct btr_node *btrn)
664 {
665         struct btr_buffer_reference *br, *tmp;
666
667         FOR_EACH_BUFFER_REF_SAFE(br, tmp, btrn)
668                 btr_drop_buffer_reference(br);
669 }
670
671 /**
672  * Free all resources allocated by btr_new_node().
673  *
674  * \param btrn Pointer to a btr node obtained by \ref btr_new_node().
675  *
676  * Like free(3), it is OK to call this with a \p NULL pointer argument.
677  */
678 void btr_free_node(struct btr_node *btrn)
679 {
680         if (!btrn)
681                 return;
682         free(btrn->name);
683         free(btrn);
684 }
685
686 /**
687  * Remove a node from a buffer tree.
688  *
689  * \param btrn The node to remove.
690  *
691  * This makes all child nodes of \a btrn orphans and removes \a btrn from the
692  * list of children of its parent. Moreover, the input queue of \a btrn is
693  * flushed if it is not empty.
694  *
695  * \sa \ref btr_splice_out_node.
696  */
697 void btr_remove_node(struct btr_node *btrn)
698 {
699         struct btr_node *ch;
700
701         if (!btrn)
702                 return;
703         PARA_NOTICE_LOG("removing btr node %s from buffer tree\n", btrn->name);
704         FOR_EACH_CHILD(ch, btrn)
705                 ch->parent = NULL;
706         btr_drain(btrn);
707         if (btrn->parent)
708                 list_del(&btrn->node);
709 }
710
711 /**
712  * Return the amount of available input bytes of a buffer tree node.
713  *
714  * \param btrn The node whose input size should be computed.
715  *
716  * \return The total number of bytes available in the node's input
717  * queue.
718  *
719  * This simply iterates over all buffer references in the input queue and
720  * returns the sum of the sizes of all references.
721  */
722 size_t btr_get_input_queue_size(struct btr_node *btrn)
723 {
724         struct btr_buffer_reference *br;
725         size_t size = 0, wrap_consumed = 0;
726
727         FOR_EACH_BUFFER_REF(br, btrn) {
728                 if (br->wrap_count != 0) {
729                         wrap_consumed = br->consumed;
730                         continue;
731                 }
732                 size += br_available_bytes(br);
733         }
734         assert(wrap_consumed <= size);
735         size -= wrap_consumed;
736         return size;
737 }
738
739 /**
740  * Remove a node from the buffer tree, reconnecting parent and children.
741  *
742  * \param btrn The node to splice out.
743  *
744  * This function is used by buffer tree nodes that do not exist during the
745  * whole lifetime of the buffer tree. Unlike btr_remove_node(), calling
746  * btr_splice_out_node() does not split the tree into disconnected components
747  * but reconnects the buffer tree by making all child nodes of \a btrn children
748  * of the parent of \a btrn.
749  */
750 void btr_splice_out_node(struct btr_node *btrn)
751 {
752         struct btr_node *ch, *tmp;
753
754         assert(btrn);
755         PARA_NOTICE_LOG("splicing out %s\n", btrn->name);
756         btr_pushdown(btrn);
757         if (btrn->parent)
758                 list_del(&btrn->node);
759         FOR_EACH_CHILD_SAFE(ch, tmp, btrn) {
760                 PARA_INFO_LOG("parent(%s): %s\n", ch->name,
761                         btrn->parent? btrn->parent->name : "NULL");
762                 ch->parent = btrn->parent;
763                 if (btrn->parent)
764                         list_move(&ch->node, &btrn->parent->children);
765         }
766         assert(list_empty(&btrn->children));
767 }
768
769 /**
770  * Return number of queued output bytes of a buffer tree node.
771  *
772  * \param btrn The node whose output queue size should be computed.
773  *
774  * This function iterates over all children of the given node and returns the
775  * size of the largest input queue.
776  */
777 size_t btr_get_output_queue_size(struct btr_node *btrn)
778 {
779         size_t max_size = 0;
780         struct btr_node *ch;
781
782         FOR_EACH_CHILD(ch, btrn) {
783                 size_t size = btr_get_input_queue_size(ch);
784                 max_size = PARA_MAX(max_size, size);
785         }
786         return max_size;
787 }
788
789 /**
790  * Execute a inter-node command on a parent node.
791  *
792  * \param btrn The node to start looking.
793  * \param command The command to execute.
794  * \param value_result Additional arguments and result value.
795  *
796  * This function traverses the buffer tree upwards and looks for parent nodes
797  * of \a btrn that understands \a command. On the first such node the command
798  * is executed, and the result is stored in \a value_result.
799  *
800  * \return \p -ENOTSUP if no parent node of \a btrn understands \a command.
801  * Otherwise the return value of the command handler is returned.
802  */
803 int btr_exec_up(struct btr_node *btrn, const char *command, char **value_result)
804 {
805         int ret;
806
807         for (; btrn; btrn = btrn->parent) {
808                 struct btr_node *parent = btrn->parent;
809                 if (!parent)
810                         return -ERRNO_TO_PARA_ERROR(ENOTSUP);
811                 if (!parent->execute)
812                         continue;
813                 PARA_INFO_LOG("parent: %s, cmd: %s\n", parent->name, command);
814                 ret = parent->execute(parent, command, value_result);
815                 if (ret == -ERRNO_TO_PARA_ERROR(ENOTSUP))
816                         continue;
817                 if (ret < 0)
818                         return ret;
819                 if (value_result && *value_result)
820                         PARA_NOTICE_LOG("%s(%s): %s\n", command, parent->name,
821                                 *value_result);
822                 return 1;
823         }
824         return -ERRNO_TO_PARA_ERROR(ENOTSUP);
825 }
826
827 /**
828  * Obtain the context of a buffer node tree.
829  *
830  * The returned pointer equals the context pointer used at creation time of the
831  * node.
832  *
833  * \sa btr_new_node(), struct \ref btr_node_description.
834  */
835 void *btr_context(struct btr_node *btrn)
836 {
837         return btrn->context;
838 }
839
840 static bool need_buffer_pool_merge(struct btr_node *btrn)
841 {
842         struct btr_buffer_reference *br = get_first_input_br(btrn);
843
844         if (!br)
845                 return false;
846         if (br->wrap_count != 0)
847                 return true;
848         if (br->btrb->pool)
849                 return true;
850         return false;
851 }
852
853 static void merge_input_pool(struct btr_node *btrn, size_t dest_size)
854 {
855         struct btr_buffer_reference *br, *wbr = NULL;
856         int num_refs; /* including wrap buffer */
857         char *buf, *buf1 = NULL, *buf2 = NULL;
858         size_t sz, sz1 = 0, sz2 = 0, wb_consumed = 0;
859
860         br = get_first_input_br(btrn);
861         if (!br || br_available_bytes(br) >= dest_size)
862                 return;
863         num_refs = 0;
864         FOR_EACH_BUFFER_REF(br, btrn) {
865                 num_refs++;
866                 sz = btr_get_buffer_by_reference(br, &buf);
867                 if (sz == 0)
868                         break;
869                 if (br->wrap_count != 0) {
870                         assert(!wbr);
871                         assert(num_refs == 1);
872                         wbr = br;
873                         if (sz >= dest_size)
874                                 return;
875                         wb_consumed = br->consumed;
876                         continue;
877                 }
878                 if (!buf1) {
879                         buf1 = buf;
880                         sz1 = sz;
881                         goto next;
882                 }
883                 if (buf1 + sz1 == buf) {
884                         sz1 += sz;
885                         goto next;
886                 }
887                 if (!buf2) {
888                         buf2 = buf;
889                         sz2 = sz;
890                         goto next;
891                 }
892                 assert(buf2 + sz2 == buf);
893                 sz2 += sz;
894 next:
895                 if (sz1 + sz2 >= dest_size + wb_consumed)
896                         break;
897         }
898         if (!buf2) /* nothing to do */
899                 return;
900         assert(buf1 && sz2 > 0);
901         /*
902          * If the second buffer is large, we only take the first part of it to
903          * avoid having to memcpy() huge buffers.
904          */
905         sz2 = PARA_MIN(sz2, (size_t)(64 * 1024));
906         if (!wbr) {
907                 /* Make a new wrap buffer combining buf1 and buf2. */
908                 sz = sz1 + sz2;
909                 buf = para_malloc(sz);
910                 PARA_DEBUG_LOG("merging input buffers: (%p:%zu, %p:%zu) -> %p:%zu\n",
911                         buf1, sz1, buf2, sz2, buf, sz);
912                 memcpy(buf, buf1, sz1);
913                 memcpy(buf + sz1, buf2, sz2);
914                 br = para_calloc(sizeof(*br));
915                 br->btrb = new_btrb(buf, sz);
916                 br->btrb->refcount = 1;
917                 br->consumed = 0;
918                 /* This is a wrap buffer */
919                 br->wrap_count = sz1;
920                 para_list_add(&br->node, &btrn->input_queue);
921                 return;
922         }
923         /*
924          * We already have a wrap buffer, but it is too small. It might be
925          * partially used.
926          */
927         if (wbr->wrap_count == sz1 && wbr->btrb->size >= sz1 + sz2) /* nothing we can do about it */
928                 return;
929         sz = sz1 + sz2 - wbr->btrb->size; /* amount of new data */
930         PARA_DEBUG_LOG("increasing wrap buffer %zu -> %zu\n", wbr->btrb->size,
931                 wbr->btrb->size + sz);
932         wbr->btrb->size += sz;
933         wbr->btrb->buf = para_realloc(wbr->btrb->buf, wbr->btrb->size);
934         /* copy the new data to the end of the reallocated buffer */
935         assert(sz2 >= sz);
936         memcpy(wbr->btrb->buf + wbr->btrb->size - sz, buf2 + sz2 - sz, sz);
937 }
938
939 /**
940  * Merge the first two input buffers into one.
941  *
942  * This is a quite expensive operation.
943  *
944  * \return The number of buffers that have been available (zero, one or two).
945  */
946 static int merge_input(struct btr_node *btrn)
947 {
948         struct btr_buffer_reference *brs[2], *br;
949         char *bufs[2], *buf;
950         size_t szs[2], sz;
951         int i;
952
953         if (list_empty(&btrn->input_queue))
954                 return 0;
955         if (list_is_singular(&btrn->input_queue))
956                 return 1;
957         i = 0;
958         /* get references to the first two buffers */
959         FOR_EACH_BUFFER_REF(br, btrn) {
960                 brs[i] = br;
961                 szs[i] = btr_get_buffer_by_reference(brs[i], bufs + i);
962                 i++;
963                 if (i == 2)
964                         break;
965         }
966         assert(i == 2);
967         /* make a new btrb that combines the two buffers and a br to it. */
968         sz = szs[0] + szs[1];
969         buf = para_malloc(sz);
970         PARA_DEBUG_LOG("%s: memory merging input buffers: (%zu, %zu) -> %zu\n",
971                 btrn->name, szs[0], szs[1], sz);
972         memcpy(buf, bufs[0], szs[0]);
973         memcpy(buf + szs[0], bufs[1], szs[1]);
974
975         br = para_calloc(sizeof(*br));
976         br->btrb = new_btrb(buf, sz);
977         br->btrb->refcount = 1;
978
979         /* replace the first two refs by the new one */
980         btr_drop_buffer_reference(brs[0]);
981         btr_drop_buffer_reference(brs[1]);
982         para_list_add(&br->node, &btrn->input_queue);
983         return 2;
984 }
985
986 /**
987  * Combine input queue buffers.
988  *
989  * \param btrn The buffer tree node whose input should be merged.
990  * \param dest_size Stop merging if a buffer of at least this size exists.
991  *
992  * Used to combine as many buffers as needed into a single buffer whose size is
993  * at least \a dest_size. This function is rather cheap in case the parent node
994  * uses buffer pools and rather expensive otherwise.
995  *
996  * Note that if less than \a dest_size bytes are available in total, this
997  * function does nothing and subsequent calls to btr_next_buffer() will still
998  * return a buffer size less than \a dest_size.
999  */
1000 void btr_merge(struct btr_node *btrn, size_t dest_size)
1001 {
1002         if (need_buffer_pool_merge(btrn))
1003                 return merge_input_pool(btrn, dest_size);
1004         for (;;) {
1005                 char *buf;
1006                 size_t len = btr_next_buffer(btrn, &buf);
1007                 if (len >= dest_size)
1008                         return;
1009                 PARA_DEBUG_LOG("input size = %zu < %zu = dest\n", len, dest_size);
1010                 if (merge_input(btrn) < 2)
1011                         return;
1012         }
1013 }
1014
1015 static bool btr_eof(struct btr_node *btrn)
1016 {
1017         char *buf;
1018         size_t len = btr_next_buffer(btrn, &buf);
1019
1020         return (len == 0 && btr_no_parent(btrn));
1021 }
1022
1023 static void log_tree_recursively(struct btr_node *btrn, int loglevel, int depth)
1024 {
1025         struct btr_node *ch;
1026         const char spaces[] = "                 ", *space = spaces + 16 - depth;
1027
1028         if (depth > 16)
1029                 return;
1030         para_log(loglevel, "%s%s\n", space, btrn->name);
1031         FOR_EACH_CHILD(ch, btrn)
1032                 log_tree_recursively(ch, loglevel, depth + 1);
1033 }
1034
1035 /**
1036  * Write the current buffer (sub-)tree to the log.
1037  *
1038  * \param btrn Start logging at this node.
1039  * \param loglevel Set severity with which the tree should be logged.
1040  */
1041 void btr_log_tree(struct btr_node *btrn, int loglevel)
1042 {
1043         return log_tree_recursively(btrn, loglevel, 0);
1044 }
1045
1046 /**
1047  * Find the node with the given name in the buffer tree.
1048  *
1049  * \param name The name of the node to search.
1050  * \param root Where to start the search.
1051  *
1052  * \return A pointer to the node with the given name on success. If \a name is
1053  * \p NULL, the function returns \a root. If there is no node with the given
1054  * name, \p NULL is returned.
1055  */
1056 struct btr_node *btr_search_node(const char *name, struct btr_node *root)
1057 {
1058         struct btr_node *ch;
1059
1060         if (!name)
1061                 return root;
1062         if (!strcmp(root->name, name))
1063                 return root;
1064         FOR_EACH_CHILD(ch, root) {
1065                 struct btr_node *result = btr_search_node(name, ch);
1066                 if (result)
1067                         return result;
1068         }
1069         return NULL;
1070 }
1071
1072 /** 640K ought to be enough for everybody ;) */
1073 #define BTRN_MAX_PENDING (96 * 1024)
1074
1075 /**
1076  * Return the current state of a buffer tree node.
1077  *
1078  * \param btrn The node whose state should be queried.
1079  * \param min_iqs The minimal input queue size.
1080  * \param type The supposed type of \a btrn.
1081  *
1082  * Most users of the buffer tree subsystem call this function from both
1083  * their pre_select and the post_select methods.
1084  *
1085  * \return Negative if an error condition was detected, zero if there
1086  * is nothing to do and positive otherwise.
1087  *
1088  * Examples:
1089  *
1090  * - If a non-root node has no parent and an empty input queue, the function
1091  * returns \p -E_BTR_EOF. Similarly, if a non-leaf node has no children, \p
1092  * -E_BTR_NO_CHILD is returned.
1093  *
1094  * - If less than \a min_iqs many bytes are available in the input queue and no
1095  * EOF condition was detected, the function returns zero.
1096  *
1097  * - If there's plenty of data left in the input queue of the children of \a
1098  * btrn, the function also returns zero in order to bound the memory usage of
1099  * the buffer tree.
1100  */
1101 int btr_node_status(struct btr_node *btrn, size_t min_iqs,
1102         enum btr_node_type type)
1103 {
1104         size_t iqs;
1105
1106         assert(btrn);
1107         if (type != BTR_NT_LEAF) {
1108                 if (btr_no_children(btrn))
1109                         return -E_BTR_NO_CHILD;
1110                 if (btr_get_output_queue_size(btrn) > BTRN_MAX_PENDING)
1111                         return 0;
1112         }
1113         if (type != BTR_NT_ROOT) {
1114                 if (btr_eof(btrn))
1115                         return -E_BTR_EOF;
1116                 iqs = btr_get_input_queue_size(btrn);
1117                 if (iqs == 0) /* we have a parent, because not eof */
1118                         return 0;
1119                 if (iqs < min_iqs && !btr_no_parent(btrn))
1120                         return 0;
1121         }
1122         return 1;
1123 }
1124
1125 /**
1126  * Get the time of the first I/O for a buffer tree node.
1127  *
1128  * \param btrn The node whose I/O time should be obtained.
1129  * \param tv Result pointer.
1130  *
1131  * Mainly useful for the time display of para_audiod.
1132  */
1133 void btr_get_node_start(struct btr_node *btrn, struct timeval *tv)
1134 {
1135         *tv = btrn->start;
1136 }