Fix a dircache NULL-pointer dereference.
[kugel-rb.git] / apps / buffering.c
blob664a178db0f3c63aa19009a52a2c38605e76df10
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2007 Nicolas Pennequin
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
22 #include "config.h"
23 #include <stdio.h>
24 #include <string.h>
25 #include <stdlib.h>
26 #include <ctype.h>
27 #include "buffering.h"
29 #include "storage.h"
30 #include "system.h"
31 #include "thread.h"
32 #include "file.h"
33 #include "panic.h"
34 #include "memory.h"
35 #include "lcd.h"
36 #include "font.h"
37 #include "button.h"
38 #include "kernel.h"
39 #include "tree.h"
40 #include "debug.h"
41 #include "sprintf.h"
42 #include "settings.h"
43 #include "codecs.h"
44 #include "audio.h"
45 #include "mp3_playback.h"
46 #include "usb.h"
47 #include "screens.h"
48 #include "playlist.h"
49 #include "pcmbuf.h"
50 #include "bmp.h"
51 #include "appevents.h"
52 #include "metadata.h"
53 #ifdef HAVE_ALBUMART
54 #include "albumart.h"
55 #include "jpeg_load.h"
56 #include "bmp.h"
57 #endif
59 #define GUARD_BUFSIZE (32*1024)
61 /* Define LOGF_ENABLE to enable logf output in this file */
62 /*#define LOGF_ENABLE*/
63 #include "logf.h"
65 /* macros to enable logf for queues
66 logging on SYS_TIMEOUT can be disabled */
67 #ifdef SIMULATOR
68 /* Define this for logf output of all queuing except SYS_TIMEOUT */
69 #define BUFFERING_LOGQUEUES
70 /* Define this to logf SYS_TIMEOUT messages */
71 /* #define BUFFERING_LOGQUEUES_SYS_TIMEOUT */
72 #endif
74 #ifdef BUFFERING_LOGQUEUES
75 #define LOGFQUEUE logf
76 #else
77 #define LOGFQUEUE(...)
78 #endif
80 #ifdef BUFFERING_LOGQUEUES_SYS_TIMEOUT
81 #define LOGFQUEUE_SYS_TIMEOUT logf
82 #else
83 #define LOGFQUEUE_SYS_TIMEOUT(...)
84 #endif
86 /* default point to start buffer refill */
87 #define BUFFERING_DEFAULT_WATERMARK (1024*128)
88 /* amount of data to read in one read() call */
89 #define BUFFERING_DEFAULT_FILECHUNK (1024*32)
91 #define BUF_HANDLE_MASK 0x7FFFFFFF
94 /* assert(sizeof(struct memory_handle)%4==0) */
95 struct memory_handle {
96 int id; /* A unique ID for the handle */
97 enum data_type type; /* Type of data buffered with this handle */
98 char path[MAX_PATH]; /* Path if data originated in a file */
99 int fd; /* File descriptor to path (-1 if closed) */
100 size_t start; /* Start index of the handle's data buffer,
101 for use by reset_handle. */
102 size_t data; /* Start index of the handle's data */
103 volatile size_t ridx; /* Read pointer, relative to the main buffer */
104 size_t widx; /* Write pointer */
105 size_t filesize; /* File total length */
106 size_t filerem; /* Remaining bytes of file NOT in buffer */
107 volatile size_t available; /* Available bytes to read from buffer */
108 size_t offset; /* Offset at which we started reading the file */
109 struct memory_handle *next;
111 /* invariant: filesize == offset + available + filerem */
113 static char *buffer;
114 static char *guard_buffer;
116 static size_t buffer_len;
118 static volatile size_t buf_widx; /* current writing position */
119 static volatile size_t buf_ridx; /* current reading position */
120 /* buf_*idx are values relative to the buffer, not real pointers. */
122 /* Configuration */
123 static size_t conf_watermark = 0; /* Level to trigger filebuf fill */
124 #if MEM > 8
125 static size_t high_watermark = 0; /* High watermark for rebuffer */
126 #endif
128 /* current memory handle in the linked list. NULL when the list is empty. */
129 static struct memory_handle *cur_handle;
130 /* first memory handle in the linked list. NULL when the list is empty. */
131 static struct memory_handle *first_handle;
133 static int num_handles; /* number of handles in the list */
135 static int base_handle_id;
137 static struct mutex llist_mutex;
138 static struct mutex llist_mod_mutex;
140 /* Handle cache (makes find_handle faster).
141 This is global so that move_handle and rm_handle can invalidate it. */
142 static struct memory_handle *cached_handle = NULL;
144 static struct {
145 size_t remaining; /* Amount of data needing to be buffered */
146 size_t wasted; /* Amount of space available for freeing */
147 size_t buffered; /* Amount of data currently in the buffer */
148 size_t useful; /* Amount of data still useful to the user */
149 } data_counters;
152 /* Messages available to communicate with the buffering thread */
153 enum {
154 Q_BUFFER_HANDLE = 1, /* Request buffering of a handle, this should not be
155 used in a low buffer situation. */
156 Q_RESET_HANDLE, /* (internal) Request resetting of a handle to its
157 offset (the offset has to be set beforehand) */
158 Q_CLOSE_HANDLE, /* Request closing a handle */
159 Q_BASE_HANDLE, /* Set the reference handle for buf_useful_data */
161 /* Configuration: */
162 Q_START_FILL, /* Request that the buffering thread initiate a buffer
163 fill at its earliest convenience */
164 Q_HANDLE_ADDED, /* Inform the buffering thread that a handle was added,
165 (which means the disk is spinning) */
168 /* Buffering thread */
169 static void buffering_thread(void);
170 static long buffering_stack[(DEFAULT_STACK_SIZE + 0x2000)/sizeof(long)];
171 static const char buffering_thread_name[] = "buffering";
172 static unsigned int buffering_thread_id = 0;
173 static struct event_queue buffering_queue;
174 static struct queue_sender_list buffering_queue_sender_list;
178 /* Ring buffer helper functions */
180 static inline uintptr_t ringbuf_offset(const void *ptr)
182 return (uintptr_t)(ptr - (void*)buffer);
185 /* Buffer pointer (p) plus value (v), wrapped if necessary */
186 static inline uintptr_t ringbuf_add(uintptr_t p, size_t v)
188 uintptr_t res = p + v;
189 if (res >= buffer_len)
190 res -= buffer_len; /* wrap if necssary */
191 return res;
195 /* Buffer pointer (p) minus value (v), wrapped if necessary */
196 static inline uintptr_t ringbuf_sub(uintptr_t p, size_t v)
198 uintptr_t res = p;
199 if (p < v)
200 res += buffer_len; /* wrap */
202 return res - v;
206 /* How far value (v) plus buffer pointer (p1) will cross buffer pointer (p2) */
207 static inline ssize_t ringbuf_add_cross(uintptr_t p1, size_t v, uintptr_t p2)
209 ssize_t res = p1 + v - p2;
210 if (p1 >= p2) /* wrap if necessary */
211 res -= buffer_len;
213 return res;
216 /* Bytes available in the buffer */
217 #define BUF_USED ringbuf_sub(buf_widx, buf_ridx)
220 LINKED LIST MANAGEMENT
221 ======================
223 add_handle : Add a handle to the list
224 rm_handle : Remove a handle from the list
225 find_handle : Get a handle pointer from an ID
226 move_handle : Move a handle in the buffer (with or without its data)
228 These functions only handle the linked list structure. They don't touch the
229 contents of the struct memory_handle headers. They also change the buf_*idx
230 pointers when necessary and manage the handle IDs.
232 The first and current (== last) handle are kept track of.
233 A new handle is added at buf_widx and becomes the current one.
234 buf_widx always points to the current writing position for the current handle
235 buf_ridx always points to the location of the first handle.
236 buf_ridx == buf_widx means the buffer is empty.
240 /* Add a new handle to the linked list and return it. It will have become the
241 new current handle.
242 data_size must contain the size of what will be in the handle.
243 can_wrap tells us whether this type of data may wrap on buffer
244 alloc_all tells us if we must immediately be able to allocate data_size
245 returns a valid memory handle if all conditions for allocation are met.
246 NULL if there memory_handle itself cannot be allocated or if the
247 data_size cannot be allocated and alloc_all is set. This function's
248 only potential side effect is to allocate space for the cur_handle
249 if it returns NULL.
251 static struct memory_handle *add_handle(size_t data_size, bool can_wrap,
252 bool alloc_all)
254 /* gives each handle a unique id */
255 static int cur_handle_id = 0;
256 size_t shift;
257 size_t new_widx;
258 size_t len;
259 int overlap;
261 if (num_handles >= BUF_MAX_HANDLES)
262 return NULL;
264 mutex_lock(&llist_mutex);
265 mutex_lock(&llist_mod_mutex);
267 if (cur_handle && cur_handle->filerem > 0) {
268 /* the current handle hasn't finished buffering. We can only add
269 a new one if there is already enough free space to finish
270 the buffering. */
271 size_t req = cur_handle->filerem + sizeof(struct memory_handle);
272 if (ringbuf_add_cross(cur_handle->widx, req, buf_ridx) >= 0) {
273 /* Not enough space */
274 mutex_unlock(&llist_mod_mutex);
275 mutex_unlock(&llist_mutex);
276 return NULL;
277 } else {
278 /* Allocate the remainder of the space for the current handle */
279 buf_widx = ringbuf_add(cur_handle->widx, cur_handle->filerem);
283 /* align to 4 bytes up */
284 new_widx = ringbuf_add(buf_widx, 3) & ~3;
286 len = data_size + sizeof(struct memory_handle);
288 /* First, will the handle wrap? */
289 /* If the handle would wrap, move to the beginning of the buffer,
290 * or if the data must not but would wrap, move it to the beginning */
291 if( (new_widx + sizeof(struct memory_handle) > buffer_len) ||
292 (!can_wrap && (new_widx + len > buffer_len)) ) {
293 new_widx = 0;
296 /* How far we shifted buf_widx to align things, must be < buffer_len */
297 shift = ringbuf_sub(new_widx, buf_widx);
299 /* How much space are we short in the actual ring buffer? */
300 overlap = ringbuf_add_cross(buf_widx, shift + len, buf_ridx);
301 if (overlap >= 0 && (alloc_all || (unsigned)overlap > data_size)) {
302 /* Not enough space for required allocations */
303 mutex_unlock(&llist_mod_mutex);
304 mutex_unlock(&llist_mutex);
305 return NULL;
308 /* There is enough space for the required data, advance the buf_widx and
309 * initialize the struct */
310 buf_widx = new_widx;
312 struct memory_handle *new_handle =
313 (struct memory_handle *)(&buffer[buf_widx]);
315 /* only advance the buffer write index of the size of the struct */
316 buf_widx = ringbuf_add(buf_widx, sizeof(struct memory_handle));
318 new_handle->id = cur_handle_id;
319 /* Wrap signed int is safe and 0 doesn't happen */
320 cur_handle_id = (cur_handle_id + 1) & BUF_HANDLE_MASK;
321 new_handle->next = NULL;
322 num_handles++;
324 if (!first_handle)
325 /* the new handle is the first one */
326 first_handle = new_handle;
328 if (cur_handle)
329 cur_handle->next = new_handle;
331 cur_handle = new_handle;
333 mutex_unlock(&llist_mod_mutex);
334 mutex_unlock(&llist_mutex);
335 return new_handle;
338 /* Delete a given memory handle from the linked list
339 and return true for success. Nothing is actually erased from memory. */
340 static bool rm_handle(const struct memory_handle *h)
342 if (h == NULL)
343 return true;
345 mutex_lock(&llist_mutex);
346 mutex_lock(&llist_mod_mutex);
348 if (h == first_handle) {
349 first_handle = h->next;
350 if (h == cur_handle) {
351 /* h was the first and last handle: the buffer is now empty */
352 cur_handle = NULL;
353 buf_ridx = buf_widx = 0;
354 } else {
355 /* update buf_ridx to point to the new first handle */
356 buf_ridx = (size_t)ringbuf_offset(first_handle);
358 } else {
359 struct memory_handle *m = first_handle;
360 /* Find the previous handle */
361 while (m && m->next != h) {
362 m = m->next;
364 if (m && m->next == h) {
365 m->next = h->next;
366 if (h == cur_handle) {
367 cur_handle = m;
368 buf_widx = cur_handle->widx;
370 } else {
371 mutex_unlock(&llist_mod_mutex);
372 mutex_unlock(&llist_mutex);
373 return false;
377 /* Invalidate the cache to prevent it from keeping the old location of h */
378 if (h == cached_handle)
379 cached_handle = NULL;
381 num_handles--;
383 mutex_unlock(&llist_mod_mutex);
384 mutex_unlock(&llist_mutex);
385 return true;
388 /* Return a pointer to the memory handle of given ID.
389 NULL if the handle wasn't found */
390 static struct memory_handle *find_handle(int handle_id)
392 if (handle_id < 0)
393 return NULL;
395 mutex_lock(&llist_mutex);
397 /* simple caching because most of the time the requested handle
398 will either be the same as the last, or the one after the last */
399 if (cached_handle)
401 if (cached_handle->id == handle_id) {
402 mutex_unlock(&llist_mutex);
403 return cached_handle;
404 } else if (cached_handle->next &&
405 (cached_handle->next->id == handle_id)) {
406 cached_handle = cached_handle->next;
407 mutex_unlock(&llist_mutex);
408 return cached_handle;
412 struct memory_handle *m = first_handle;
413 while (m && m->id != handle_id) {
414 m = m->next;
416 /* This condition can only be reached with !m or m->id == handle_id */
417 if (m)
418 cached_handle = m;
420 mutex_unlock(&llist_mutex);
421 return m;
424 /* Move a memory handle and data_size of its data delta bytes along the buffer.
425 delta maximum bytes available to move the handle. If the move is performed
426 it is set to the actual distance moved.
427 data_size is the amount of data to move along with the struct.
428 returns a valid memory_handle if the move is successful
429 NULL if the handle is NULL, the move would be less than the size of
430 a memory_handle after correcting for wraps or if the handle is not
431 found in the linked list for adjustment. This function has no side
432 effects if NULL is returned. */
433 static bool move_handle(struct memory_handle **h, size_t *delta,
434 size_t data_size, bool can_wrap)
436 struct memory_handle *dest;
437 const struct memory_handle *src;
438 int32_t *here;
439 int32_t *there;
440 int32_t *end;
441 int32_t *begin;
442 size_t final_delta = *delta, size_to_move, n;
443 uintptr_t oldpos, newpos;
444 intptr_t overlap, overlap_old;
446 if (h == NULL || (src = *h) == NULL)
447 return false;
449 size_to_move = sizeof(struct memory_handle) + data_size;
451 /* Align to four bytes, down */
452 final_delta &= ~3;
453 if (final_delta < sizeof(struct memory_handle)) {
454 /* It's not legal to move less than the size of the struct */
455 return false;
458 mutex_lock(&llist_mutex);
459 mutex_lock(&llist_mod_mutex);
461 oldpos = ringbuf_offset(src);
462 newpos = ringbuf_add(oldpos, final_delta);
463 overlap = ringbuf_add_cross(newpos, size_to_move, buffer_len - 1);
464 overlap_old = ringbuf_add_cross(oldpos, size_to_move, buffer_len -1);
466 if (overlap > 0) {
467 /* Some part of the struct + data would wrap, maybe ok */
468 size_t correction = 0;
469 /* If the overlap lands inside the memory_handle */
470 if (!can_wrap) {
471 /* Otherwise the overlap falls in the data area and must all be
472 * backed out. This may become conditional if ever we move
473 * data that is allowed to wrap (ie audio) */
474 correction = overlap;
475 } else if ((uintptr_t)overlap > data_size) {
476 /* Correct the position and real delta to prevent the struct from
477 * wrapping, this guarantees an aligned delta, I think */
478 correction = overlap - data_size;
480 if (correction) {
481 /* Align correction to four bytes up */
482 correction = (correction + 3) & ~3;
483 if (final_delta < correction + sizeof(struct memory_handle)) {
484 /* Delta cannot end up less than the size of the struct */
485 mutex_unlock(&llist_mod_mutex);
486 mutex_unlock(&llist_mutex);
487 return false;
489 newpos -= correction;
490 overlap -= correction;/* Used below to know how to split the data */
491 final_delta -= correction;
495 dest = (struct memory_handle *)(&buffer[newpos]);
497 if (src == first_handle) {
498 first_handle = dest;
499 buf_ridx = newpos;
500 } else {
501 struct memory_handle *m = first_handle;
502 while (m && m->next != src) {
503 m = m->next;
505 if (m && m->next == src) {
506 m->next = dest;
507 } else {
508 mutex_unlock(&llist_mod_mutex);
509 mutex_unlock(&llist_mutex);
510 return false;
515 /* Update the cache to prevent it from keeping the old location of h */
516 if (src == cached_handle)
517 cached_handle = dest;
519 /* the cur_handle pointer might need updating */
520 if (src == cur_handle)
521 cur_handle = dest;
524 /* Copying routine takes into account that the handles have a
525 * distance between each other which is a multiple of four. Faster 2 word
526 * copy may be ok but do this for safety and because wrapped copies should
527 * be fairly uncommon */
529 here = (int32_t *)((ringbuf_add(oldpos, size_to_move - 1) & ~3)+ (intptr_t)buffer);
530 there =(int32_t *)((ringbuf_add(newpos, size_to_move - 1) & ~3)+ (intptr_t)buffer);
531 end = (int32_t *)(( intptr_t)buffer + buffer_len - 4);
532 begin =(int32_t *)buffer;
534 n = (size_to_move & ~3)/4;
536 if ( overlap_old > 0 || overlap > 0 ) {
537 /* Old or moved handle wraps */
538 while (n--) {
539 if (here < begin)
540 here = end;
541 if (there < begin)
542 there = end;
543 *there-- = *here--;
545 } else {
546 /* both handles do not wrap */
547 memmove(dest,src,size_to_move);
551 /* Update the caller with the new location of h and the distance moved */
552 *h = dest;
553 *delta = final_delta;
554 mutex_unlock(&llist_mod_mutex);
555 mutex_unlock(&llist_mutex);
556 return dest;
561 BUFFER SPACE MANAGEMENT
562 =======================
564 update_data_counters: Updates the values in data_counters
565 buffer_is_low : Returns true if the amount of useful data in the buffer is low
566 buffer_handle : Buffer data for a handle
567 reset_handle : Reset write position and data buffer of a handle to its offset
568 rebuffer_handle : Seek to a nonbuffered part of a handle by rebuffering the data
569 shrink_handle : Free buffer space by moving a handle
570 fill_buffer : Call buffer_handle for all handles that have data to buffer
572 These functions are used by the buffering thread to manage buffer space.
575 static void update_data_counters(void)
577 struct memory_handle *m = find_handle(base_handle_id);
578 bool is_useful = m==NULL;
580 size_t buffered = 0;
581 size_t wasted = 0;
582 size_t remaining = 0;
583 size_t useful = 0;
585 mutex_lock(&llist_mutex);
587 m = first_handle;
588 while (m) {
589 buffered += m->available;
590 wasted += ringbuf_sub(m->ridx, m->data);
591 remaining += m->filerem;
593 if (m->id == base_handle_id)
594 is_useful = true;
596 if (is_useful)
597 useful += ringbuf_sub(m->widx, m->ridx);
599 m = m->next;
602 mutex_unlock(&llist_mutex);
604 data_counters.buffered = buffered;
605 data_counters.wasted = wasted;
606 data_counters.remaining = remaining;
607 data_counters.useful = useful;
610 static inline bool buffer_is_low(void)
612 update_data_counters();
613 return data_counters.useful < (conf_watermark / 2);
616 /* Buffer data for the given handle.
617 Return whether or not the buffering should continue explicitly. */
618 static bool buffer_handle(int handle_id)
620 logf("buffer_handle(%d)", handle_id);
621 struct memory_handle *h = find_handle(handle_id);
622 bool stop = false;
624 if (!h)
625 return true;
627 if (h->filerem == 0) {
628 /* nothing left to buffer */
629 return true;
632 if (h->fd < 0) /* file closed, reopen */
634 if (*h->path)
635 h->fd = open(h->path, O_RDONLY);
637 if (h->fd < 0)
639 /* could not open the file, truncate it where it is */
640 h->filesize -= h->filerem;
641 h->filerem = 0;
642 return true;
645 if (h->offset)
646 lseek(h->fd, h->offset, SEEK_SET);
649 trigger_cpu_boost();
651 if (h->type == TYPE_ID3)
653 if (!get_metadata((struct mp3entry *)(buffer + h->data), h->fd, h->path))
655 /* metadata parsing failed: clear the buffer. */
656 memset(buffer + h->data, 0, sizeof(struct mp3entry));
658 close(h->fd);
659 h->fd = -1;
660 h->filerem = 0;
661 h->available = sizeof(struct mp3entry);
662 h->widx += sizeof(struct mp3entry);
663 send_event(BUFFER_EVENT_FINISHED, &h->id);
664 return true;
667 while (h->filerem > 0 && !stop)
669 /* max amount to copy */
670 size_t copy_n = MIN( MIN(h->filerem, BUFFERING_DEFAULT_FILECHUNK),
671 buffer_len - h->widx);
673 ssize_t overlap;
674 uintptr_t next_handle = ringbuf_offset(h->next);
676 /* stop copying if it would overwrite the reading position */
677 if (ringbuf_add_cross(h->widx, copy_n, buf_ridx) >= 0)
678 return false;
680 /* FIXME: This would overwrite the next handle
681 * If this is true, then there's a handle even though we have still
682 * data to buffer. This should NEVER EVER happen! (but it does :( ) */
683 if (h->next && (overlap
684 = ringbuf_add_cross(h->widx, copy_n, next_handle)) > 0)
686 /* stop buffering data for now and post-pone buffering the rest */
687 stop = true;
688 DEBUGF( "%s(): Preventing handle corruption: h1.id:%d h2.id:%d"
689 " copy_n:%lu overlap:%ld h1.filerem:%lu\n", __func__,
690 h->id, h->next->id, (unsigned long)copy_n, overlap,
691 (unsigned long)h->filerem);
692 copy_n -= overlap;
695 /* rc is the actual amount read */
696 int rc = read(h->fd, &buffer[h->widx], copy_n);
698 if (rc < 0)
700 /* Some kind of filesystem error, maybe recoverable if not codec */
701 if (h->type == TYPE_CODEC) {
702 logf("Partial codec");
703 break;
706 DEBUGF("File ended %ld bytes early\n", (long)h->filerem);
707 h->filesize -= h->filerem;
708 h->filerem = 0;
709 break;
712 /* Advance buffer */
713 h->widx = ringbuf_add(h->widx, rc);
714 if (h == cur_handle)
715 buf_widx = h->widx;
716 h->available += rc;
717 h->filerem -= rc;
719 /* If this is a large file, see if we need to break or give the codec
720 * more time */
721 if (h->type == TYPE_PACKET_AUDIO &&
722 pcmbuf_is_lowdata() && !buffer_is_low())
724 sleep(1);
726 else
728 yield();
731 if (!queue_empty(&buffering_queue))
732 break;
735 if (h->filerem == 0) {
736 /* finished buffering the file */
737 close(h->fd);
738 h->fd = -1;
739 send_event(BUFFER_EVENT_FINISHED, &h->id);
742 return !stop;
745 /* Reset writing position and data buffer of a handle to its current offset.
746 Use this after having set the new offset to use. */
747 static void reset_handle(int handle_id)
749 size_t alignment_pad;
751 logf("reset_handle(%d)", handle_id);
753 struct memory_handle *h = find_handle(handle_id);
754 if (!h)
755 return;
757 /* Align to desired storage alignment */
758 alignment_pad = (h->offset - (size_t)(&buffer[h->start]))
759 & STORAGE_ALIGN_MASK;
760 h->ridx = h->widx = h->data = ringbuf_add(h->start, alignment_pad);
762 if (h == cur_handle)
763 buf_widx = h->widx;
764 h->available = 0;
765 h->filerem = h->filesize - h->offset;
767 if (h->fd >= 0) {
768 lseek(h->fd, h->offset, SEEK_SET);
772 /* Seek to a nonbuffered part of a handle by rebuffering the data. */
773 static void rebuffer_handle(int handle_id, size_t newpos)
775 struct memory_handle *h = find_handle(handle_id);
776 if (!h)
777 return;
779 /* When seeking foward off of the buffer, if it is a short seek don't
780 rebuffer the whole track, just read enough to satisfy */
781 if (newpos > h->offset && newpos - h->offset < BUFFERING_DEFAULT_FILECHUNK)
783 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id);
784 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
785 h->ridx = h->data + newpos;
786 return;
789 h->offset = newpos;
791 /* Reset the handle to its new offset */
792 LOGFQUEUE("buffering >| Q_RESET_HANDLE %d", handle_id);
793 queue_send(&buffering_queue, Q_RESET_HANDLE, handle_id);
795 uintptr_t next = ringbuf_offset(h->next);
796 if (ringbuf_sub(next, h->data) < h->filesize - newpos)
798 /* There isn't enough space to rebuffer all of the track from its new
799 offset, so we ask the user to free some */
800 DEBUGF("%s(): space is needed\n", __func__);
801 send_event(BUFFER_EVENT_REBUFFER, &handle_id);
804 /* Now we ask for a rebuffer */
805 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", handle_id);
806 queue_send(&buffering_queue, Q_BUFFER_HANDLE, handle_id);
809 static bool close_handle(int handle_id)
811 struct memory_handle *h = find_handle(handle_id);
813 /* If the handle is not found, it is closed */
814 if (!h)
815 return true;
817 if (h->fd >= 0) {
818 close(h->fd);
819 h->fd = -1;
822 /* rm_handle returns true unless the handle somehow persists after exit */
823 return rm_handle(h);
826 /* Free buffer space by moving the handle struct right before the useful
827 part of its data buffer or by moving all the data. */
828 static void shrink_handle(struct memory_handle *h)
830 size_t delta;
832 if (!h)
833 return;
835 if (h->next && h->filerem == 0 &&
836 (h->type == TYPE_ID3 || h->type == TYPE_CUESHEET ||
837 h->type == TYPE_BITMAP || h->type == TYPE_CODEC ||
838 h->type == TYPE_ATOMIC_AUDIO))
840 /* metadata handle: we can move all of it */
841 uintptr_t handle_distance =
842 ringbuf_sub(ringbuf_offset(h->next), h->data);
843 delta = handle_distance - h->available;
845 /* The value of delta might change for alignment reasons */
846 if (!move_handle(&h, &delta, h->available, h->type==TYPE_CODEC))
847 return;
849 size_t olddata = h->data;
850 h->data = ringbuf_add(h->data, delta);
851 h->ridx = ringbuf_add(h->ridx, delta);
852 h->widx = ringbuf_add(h->widx, delta);
854 if (h->type == TYPE_ID3 && h->filesize == sizeof(struct mp3entry)) {
855 /* when moving an mp3entry we need to readjust its pointers. */
856 adjust_mp3entry((struct mp3entry *)&buffer[h->data],
857 (void *)&buffer[h->data],
858 (const void *)&buffer[olddata]);
859 } else if (h->type == TYPE_BITMAP) {
860 /* adjust the bitmap's pointer */
861 struct bitmap *bmp = (struct bitmap *)&buffer[h->data];
862 bmp->data = &buffer[h->data + sizeof(struct bitmap)];
865 else
867 /* only move the handle struct */
868 delta = ringbuf_sub(h->ridx, h->data);
869 if (!move_handle(&h, &delta, 0, true))
870 return;
872 h->data = ringbuf_add(h->data, delta);
873 h->start = ringbuf_add(h->start, delta);
874 h->available -= delta;
875 h->offset += delta;
879 /* Fill the buffer by buffering as much data as possible for handles that still
880 have data left to buffer
881 Return whether or not to continue filling after this */
882 static bool fill_buffer(void)
884 logf("fill_buffer()");
885 struct memory_handle *m;
886 shrink_handle(first_handle);
887 m = first_handle;
888 while (queue_empty(&buffering_queue) && m) {
889 if (m->filerem > 0) {
890 if (!buffer_handle(m->id)) {
891 m = NULL;
892 break;
895 m = m->next;
898 if (m) {
899 return true;
901 else
903 /* only spin the disk down if the filling wasn't interrupted by an
904 event arriving in the queue. */
905 storage_sleep();
906 return false;
910 #ifdef HAVE_ALBUMART
911 /* Given a file descriptor to a bitmap file, write the bitmap data to the
912 buffer, with a struct bitmap and the actual data immediately following.
913 Return value is the total size (struct + data). */
914 static int load_image(int fd, const char *path, struct dim *dim)
916 int rc;
917 struct bitmap *bmp = (struct bitmap *)&buffer[buf_widx];
919 /* get the desired image size */
920 bmp->width = dim->width, bmp->height = dim->height;
921 /* FIXME: alignment may be needed for the data buffer. */
922 bmp->data = &buffer[buf_widx + sizeof(struct bitmap)];
923 #ifndef HAVE_JPEG
924 (void) path;
925 #endif
926 #if (LCD_DEPTH > 1) || defined(HAVE_REMOTE_LCD) && (LCD_REMOTE_DEPTH > 1)
927 bmp->maskdata = NULL;
928 #endif
930 int free = (int)MIN(buffer_len - BUF_USED, buffer_len - buf_widx)
931 - sizeof(struct bitmap);
933 #ifdef HAVE_JPEG
934 int pathlen = strlen(path);
935 if (strcmp(path + pathlen - 4, ".bmp"))
936 rc = read_jpeg_fd(fd, bmp, free, FORMAT_NATIVE|FORMAT_DITHER|
937 FORMAT_RESIZE|FORMAT_KEEP_ASPECT, NULL);
938 else
939 #endif
940 rc = read_bmp_fd(fd, bmp, free, FORMAT_NATIVE|FORMAT_DITHER|
941 FORMAT_RESIZE|FORMAT_KEEP_ASPECT, NULL);
942 return rc + (rc > 0 ? sizeof(struct bitmap) : 0);
944 #endif
948 MAIN BUFFERING API CALLS
949 ========================
951 bufopen : Request the opening of a new handle for a file
952 bufalloc : Open a new handle for data other than a file.
953 bufclose : Close an open handle
954 bufseek : Set the read pointer in a handle
955 bufadvance : Move the read pointer in a handle
956 bufread : Copy data from a handle into a given buffer
957 bufgetdata : Give a pointer to the handle's data
959 These functions are exported, to allow interaction with the buffer.
960 They take care of the content of the structs, and rely on the linked list
961 management functions for all the actual handle management work.
965 /* Reserve space in the buffer for a file.
966 filename: name of the file to open
967 offset: offset at which to start buffering the file, useful when the first
968 (offset-1) bytes of the file aren't needed.
969 type: one of the data types supported (audio, image, cuesheet, others
970 user_data: user data passed possibly passed in subcalls specific to a
971 data_type (only used for image (albumart) buffering so far )
972 return value: <0 if the file cannot be opened, or one file already
973 queued to be opened, otherwise the handle for the file in the buffer
975 int bufopen(const char *file, size_t offset, enum data_type type,
976 void *user_data)
978 #ifndef HAVE_ALBUMART
979 /* currently only used for aa loading */
980 (void)user_data;
981 #endif
982 if (type == TYPE_ID3)
984 /* ID3 case: allocate space, init the handle and return. */
986 struct memory_handle *h = add_handle(sizeof(struct mp3entry), false, true);
987 if (!h)
988 return ERR_BUFFER_FULL;
990 h->fd = -1;
991 h->filesize = sizeof(struct mp3entry);
992 h->filerem = sizeof(struct mp3entry);
993 h->offset = 0;
994 h->data = buf_widx;
995 h->ridx = buf_widx;
996 h->widx = buf_widx;
997 h->available = 0;
998 h->type = type;
999 strlcpy(h->path, file, MAX_PATH);
1001 buf_widx += sizeof(struct mp3entry); /* safe because the handle
1002 can't wrap */
1004 /* Inform the buffering thread that we added a handle */
1005 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h->id);
1006 queue_post(&buffering_queue, Q_HANDLE_ADDED, h->id);
1008 return h->id;
1011 /* Other cases: there is a little more work. */
1013 int fd = open(file, O_RDONLY);
1014 if (fd < 0)
1015 return ERR_FILE_ERROR;
1017 size_t size = filesize(fd);
1018 bool can_wrap = type==TYPE_PACKET_AUDIO || type==TYPE_CODEC;
1020 size_t adjusted_offset = offset;
1021 if (adjusted_offset > size)
1022 adjusted_offset = 0;
1024 /* Reserve extra space because alignment can move data forward */
1025 struct memory_handle *h = add_handle(size-adjusted_offset+STORAGE_ALIGN_MASK,
1026 can_wrap, false);
1027 if (!h)
1029 DEBUGF("%s(): failed to add handle\n", __func__);
1030 close(fd);
1031 return ERR_BUFFER_FULL;
1034 strlcpy(h->path, file, MAX_PATH);
1035 h->offset = adjusted_offset;
1037 /* Don't bother to storage align bitmaps because they are not
1038 * loaded directly into the buffer.
1040 if (type != TYPE_BITMAP)
1042 size_t alignment_pad;
1044 /* Remember where data area starts, for use by reset_handle */
1045 h->start = buf_widx;
1047 /* Align to desired storage alignment */
1048 alignment_pad = (adjusted_offset - (size_t)(&buffer[buf_widx]))
1049 & STORAGE_ALIGN_MASK;
1050 buf_widx = ringbuf_add(buf_widx, alignment_pad);
1053 h->ridx = buf_widx;
1054 h->widx = buf_widx;
1055 h->data = buf_widx;
1056 h->available = 0;
1057 h->filerem = 0;
1058 h->type = type;
1060 #ifdef HAVE_ALBUMART
1061 if (type == TYPE_BITMAP)
1063 /* Bitmap file: we load the data instead of the file */
1064 int rc;
1065 mutex_lock(&llist_mod_mutex); /* Lock because load_bitmap yields */
1066 rc = load_image(fd, file, (struct dim*)user_data);
1067 mutex_unlock(&llist_mod_mutex);
1068 if (rc <= 0)
1070 rm_handle(h);
1071 close(fd);
1072 return ERR_FILE_ERROR;
1074 h->filerem = 0;
1075 h->filesize = rc;
1076 h->available = rc;
1077 h->widx = buf_widx + rc; /* safe because the data doesn't wrap */
1078 buf_widx += rc; /* safe too */
1080 else
1081 #endif
1083 h->filerem = size - adjusted_offset;
1084 h->filesize = size;
1085 h->available = 0;
1086 h->widx = buf_widx;
1089 if (type == TYPE_CUESHEET) {
1090 h->fd = fd;
1091 /* Immediately start buffering those */
1092 LOGFQUEUE("buffering >| Q_BUFFER_HANDLE %d", h->id);
1093 queue_send(&buffering_queue, Q_BUFFER_HANDLE, h->id);
1094 } else {
1095 /* Other types will get buffered in the course of normal operations */
1096 h->fd = -1;
1097 close(fd);
1099 /* Inform the buffering thread that we added a handle */
1100 LOGFQUEUE("buffering > Q_HANDLE_ADDED %d", h->id);
1101 queue_post(&buffering_queue, Q_HANDLE_ADDED, h->id);
1104 logf("bufopen: new hdl %d", h->id);
1105 return h->id;
1108 /* Open a new handle from data that needs to be copied from memory.
1109 src is the source buffer from which to copy data. It can be NULL to simply
1110 reserve buffer space.
1111 size is the requested size. The call will only be successful if the
1112 requested amount of data can entirely fit in the buffer without wrapping.
1113 Return value is the handle id for success or <0 for failure.
1115 int bufalloc(const void *src, size_t size, enum data_type type)
1117 struct memory_handle *h = add_handle(size, false, true);
1119 if (!h)
1120 return ERR_BUFFER_FULL;
1122 if (src) {
1123 if (type == TYPE_ID3 && size == sizeof(struct mp3entry)) {
1124 /* specially take care of struct mp3entry */
1125 copy_mp3entry((struct mp3entry *)&buffer[buf_widx],
1126 (const struct mp3entry *)src);
1127 } else {
1128 memcpy(&buffer[buf_widx], src, size);
1132 h->fd = -1;
1133 *h->path = 0;
1134 h->filesize = size;
1135 h->filerem = 0;
1136 h->offset = 0;
1137 h->ridx = buf_widx;
1138 h->widx = buf_widx + size; /* this is safe because the data doesn't wrap */
1139 h->data = buf_widx;
1140 h->available = size;
1141 h->type = type;
1143 buf_widx += size; /* safe too */
1145 logf("bufalloc: new hdl %d", h->id);
1146 return h->id;
1149 /* Close the handle. Return true for success and false for failure */
1150 bool bufclose(int handle_id)
1152 logf("bufclose(%d)", handle_id);
1154 LOGFQUEUE("buffering >| Q_CLOSE_HANDLE %d", handle_id);
1155 return queue_send(&buffering_queue, Q_CLOSE_HANDLE, handle_id);
1158 /* Set reading index in handle (relatively to the start of the file).
1159 Access before the available data will trigger a rebuffer.
1160 Return 0 for success and < 0 for failure:
1161 -1 if the handle wasn't found
1162 -2 if the new requested position was beyond the end of the file
1164 int bufseek(int handle_id, size_t newpos)
1166 struct memory_handle *h = find_handle(handle_id);
1167 if (!h)
1168 return ERR_HANDLE_NOT_FOUND;
1170 if (newpos > h->filesize) {
1171 /* access beyond the end of the file */
1172 return ERR_INVALID_VALUE;
1174 else if (newpos < h->offset || h->offset + h->available < newpos) {
1175 /* access before or after buffered data. A rebuffer is needed. */
1176 rebuffer_handle(handle_id, newpos);
1178 else {
1179 h->ridx = ringbuf_add(h->data, newpos - h->offset);
1181 return 0;
1184 /* Advance the reading index in a handle (relatively to its current position).
1185 Return 0 for success and < 0 for failure */
1186 int bufadvance(int handle_id, off_t offset)
1188 const struct memory_handle *h = find_handle(handle_id);
1189 if (!h)
1190 return ERR_HANDLE_NOT_FOUND;
1192 size_t newpos = h->offset + ringbuf_sub(h->ridx, h->data) + offset;
1193 return bufseek(handle_id, newpos);
1196 /* Used by bufread and bufgetdata to prepare the buffer and retrieve the
1197 * actual amount of data available for reading. This function explicitly
1198 * does not check the validity of the input handle. It does do range checks
1199 * on size and returns a valid (and explicit) amount of data for reading */
1200 static struct memory_handle *prep_bufdata(int handle_id, size_t *size,
1201 bool guardbuf_limit)
1203 struct memory_handle *h = find_handle(handle_id);
1204 if (!h)
1205 return NULL;
1207 size_t avail = ringbuf_sub(h->widx, h->ridx);
1209 if (avail == 0 && h->filerem == 0)
1211 /* File is finished reading */
1212 *size = 0;
1213 return h;
1216 if (*size == 0 || *size > avail + h->filerem)
1217 *size = avail + h->filerem;
1219 if (guardbuf_limit && h->type == TYPE_PACKET_AUDIO && *size > GUARD_BUFSIZE)
1221 logf("data request > guardbuf");
1222 /* If more than the size of the guardbuf is requested and this is a
1223 * bufgetdata, limit to guard_bufsize over the end of the buffer */
1224 *size = MIN(*size, buffer_len - h->ridx + GUARD_BUFSIZE);
1225 /* this ensures *size <= buffer_len - h->ridx + GUARD_BUFSIZE */
1228 if (h->filerem > 0 && avail < *size)
1230 /* Data isn't ready. Request buffering */
1231 buf_request_buffer_handle(handle_id);
1232 /* Wait for the data to be ready */
1235 sleep(1);
1236 /* it is not safe for a non-buffering thread to sleep while
1237 * holding a handle */
1238 h = find_handle(handle_id);
1239 if (!h)
1240 return NULL;
1241 avail = ringbuf_sub(h->widx, h->ridx);
1243 while (h->filerem > 0 && avail < *size);
1246 *size = MIN(*size,avail);
1247 return h;
1250 /* Copy data from the given handle to the dest buffer.
1251 Return the number of bytes copied or < 0 for failure (handle not found).
1252 The caller is blocked until the requested amount of data is available.
1254 ssize_t bufread(int handle_id, size_t size, void *dest)
1256 const struct memory_handle *h;
1257 size_t adjusted_size = size;
1259 h = prep_bufdata(handle_id, &adjusted_size, false);
1260 if (!h)
1261 return ERR_HANDLE_NOT_FOUND;
1263 if (h->ridx + adjusted_size > buffer_len)
1265 /* the data wraps around the end of the buffer */
1266 size_t read = buffer_len - h->ridx;
1267 memcpy(dest, &buffer[h->ridx], read);
1268 memcpy(dest+read, buffer, adjusted_size - read);
1270 else
1272 memcpy(dest, &buffer[h->ridx], adjusted_size);
1275 return adjusted_size;
1278 /* Update the "data" pointer to make the handle's data available to the caller.
1279 Return the length of the available linear data or < 0 for failure (handle
1280 not found).
1281 The caller is blocked until the requested amount of data is available.
1282 size is the amount of linear data requested. it can be 0 to get as
1283 much as possible.
1284 The guard buffer may be used to provide the requested size. This means it's
1285 unsafe to request more than the size of the guard buffer.
1287 ssize_t bufgetdata(int handle_id, size_t size, void **data)
1289 const struct memory_handle *h;
1290 size_t adjusted_size = size;
1292 h = prep_bufdata(handle_id, &adjusted_size, true);
1293 if (!h)
1294 return ERR_HANDLE_NOT_FOUND;
1296 if (h->ridx + adjusted_size > buffer_len)
1298 /* the data wraps around the end of the buffer :
1299 use the guard buffer to provide the requested amount of data. */
1300 size_t copy_n = h->ridx + adjusted_size - buffer_len;
1301 /* prep_bufdata ensures adjusted_size <= buffer_len - h->ridx + GUARD_BUFSIZE,
1302 so copy_n <= GUARD_BUFSIZE */
1303 memcpy(guard_buffer, (const unsigned char *)buffer, copy_n);
1306 if (data)
1307 *data = &buffer[h->ridx];
1309 return adjusted_size;
1312 ssize_t bufgettail(int handle_id, size_t size, void **data)
1314 size_t tidx;
1316 const struct memory_handle *h;
1318 h = find_handle(handle_id);
1320 if (!h)
1321 return ERR_HANDLE_NOT_FOUND;
1323 if (h->filerem)
1324 return ERR_HANDLE_NOT_DONE;
1326 /* We don't support tail requests of > guardbuf_size, for simplicity */
1327 if (size > GUARD_BUFSIZE)
1328 return ERR_INVALID_VALUE;
1330 tidx = ringbuf_sub(h->widx, size);
1332 if (tidx + size > buffer_len)
1334 size_t copy_n = tidx + size - buffer_len;
1335 memcpy(guard_buffer, (const unsigned char *)buffer, copy_n);
1338 *data = &buffer[tidx];
1339 return size;
1342 ssize_t bufcuttail(int handle_id, size_t size)
1344 struct memory_handle *h;
1345 size_t adjusted_size = size;
1347 h = find_handle(handle_id);
1349 if (!h)
1350 return ERR_HANDLE_NOT_FOUND;
1352 if (h->filerem)
1353 return ERR_HANDLE_NOT_DONE;
1355 if (h->available < adjusted_size)
1356 adjusted_size = h->available;
1358 h->available -= adjusted_size;
1359 h->filesize -= adjusted_size;
1360 h->widx = ringbuf_sub(h->widx, adjusted_size);
1361 if (h == cur_handle)
1362 buf_widx = h->widx;
1364 return adjusted_size;
1369 SECONDARY EXPORTED FUNCTIONS
1370 ============================
1372 buf_get_offset
1373 buf_handle_offset
1374 buf_request_buffer_handle
1375 buf_set_base_handle
1376 buf_used
1377 register_buffering_callback
1378 unregister_buffering_callback
1380 These functions are exported, to allow interaction with the buffer.
1381 They take care of the content of the structs, and rely on the linked list
1382 management functions for all the actual handle management work.
1385 /* Get a handle offset from a pointer */
1386 ssize_t buf_get_offset(int handle_id, void *ptr)
1388 const struct memory_handle *h = find_handle(handle_id);
1389 if (!h)
1390 return ERR_HANDLE_NOT_FOUND;
1392 return (size_t)ptr - (size_t)&buffer[h->ridx];
1395 ssize_t buf_handle_offset(int handle_id)
1397 const struct memory_handle *h = find_handle(handle_id);
1398 if (!h)
1399 return ERR_HANDLE_NOT_FOUND;
1400 return h->offset;
1403 void buf_request_buffer_handle(int handle_id)
1405 LOGFQUEUE("buffering >| Q_START_FILL %d",handle_id);
1406 queue_send(&buffering_queue, Q_START_FILL, handle_id);
1409 void buf_set_base_handle(int handle_id)
1411 LOGFQUEUE("buffering > Q_BASE_HANDLE %d", handle_id);
1412 queue_post(&buffering_queue, Q_BASE_HANDLE, handle_id);
1415 /* Return the amount of buffer space used */
1416 size_t buf_used(void)
1418 return BUF_USED;
1421 void buf_set_watermark(size_t bytes)
1423 conf_watermark = bytes;
1426 static void shrink_buffer_inner(struct memory_handle *h)
1428 if (h == NULL)
1429 return;
1431 shrink_buffer_inner(h->next);
1433 shrink_handle(h);
1436 static void shrink_buffer(void)
1438 logf("shrink_buffer()");
1439 shrink_buffer_inner(first_handle);
1442 void buffering_thread(void)
1444 bool filling = false;
1445 struct queue_event ev;
1447 while (true)
1449 if (!filling) {
1450 cancel_cpu_boost();
1453 queue_wait_w_tmo(&buffering_queue, &ev, filling ? 5 : HZ/2);
1455 switch (ev.id)
1457 case Q_START_FILL:
1458 LOGFQUEUE("buffering < Q_START_FILL %d", (int)ev.data);
1459 /* Call buffer callbacks here because this is one of two ways
1460 * to begin a full buffer fill */
1461 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1462 shrink_buffer();
1463 queue_reply(&buffering_queue, 1);
1464 filling |= buffer_handle((int)ev.data);
1465 break;
1467 case Q_BUFFER_HANDLE:
1468 LOGFQUEUE("buffering < Q_BUFFER_HANDLE %d", (int)ev.data);
1469 queue_reply(&buffering_queue, 1);
1470 buffer_handle((int)ev.data);
1471 break;
1473 case Q_RESET_HANDLE:
1474 LOGFQUEUE("buffering < Q_RESET_HANDLE %d", (int)ev.data);
1475 queue_reply(&buffering_queue, 1);
1476 reset_handle((int)ev.data);
1477 break;
1479 case Q_CLOSE_HANDLE:
1480 LOGFQUEUE("buffering < Q_CLOSE_HANDLE %d", (int)ev.data);
1481 queue_reply(&buffering_queue, close_handle((int)ev.data));
1482 break;
1484 case Q_HANDLE_ADDED:
1485 LOGFQUEUE("buffering < Q_HANDLE_ADDED %d", (int)ev.data);
1486 /* A handle was added: the disk is spinning, so we can fill */
1487 filling = true;
1488 break;
1490 case Q_BASE_HANDLE:
1491 LOGFQUEUE("buffering < Q_BASE_HANDLE %d", (int)ev.data);
1492 base_handle_id = (int)ev.data;
1493 break;
1495 #ifndef SIMULATOR
1496 case SYS_USB_CONNECTED:
1497 LOGFQUEUE("buffering < SYS_USB_CONNECTED");
1498 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1499 usb_wait_for_disconnect(&buffering_queue);
1500 break;
1501 #endif
1503 case SYS_TIMEOUT:
1504 LOGFQUEUE_SYS_TIMEOUT("buffering < SYS_TIMEOUT");
1505 break;
1508 update_data_counters();
1510 /* If the buffer is low, call the callbacks to get new data */
1511 if (num_handles > 0 && data_counters.useful <= conf_watermark)
1512 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1514 #if 0
1515 /* TODO: This needs to be fixed to use the idle callback, disable it
1516 * for simplicity until its done right */
1517 #if MEM > 8
1518 /* If the disk is spinning, take advantage by filling the buffer */
1519 else if (storage_disk_is_active() && queue_empty(&buffering_queue))
1521 if (num_handles > 0 && data_counters.useful <= high_watermark)
1522 send_event(BUFFER_EVENT_BUFFER_LOW, 0);
1524 if (data_counters.remaining > 0 && BUF_USED <= high_watermark)
1526 /* This is a new fill, shrink the buffer up first */
1527 if (!filling)
1528 shrink_buffer();
1529 filling = fill_buffer();
1530 update_data_counters();
1533 #endif
1534 #endif
1536 if (queue_empty(&buffering_queue)) {
1537 if (filling) {
1538 if (data_counters.remaining > 0 && BUF_USED < buffer_len)
1539 filling = fill_buffer();
1540 else if (data_counters.remaining == 0)
1541 filling = false;
1543 else if (ev.id == SYS_TIMEOUT)
1545 if (data_counters.remaining > 0 &&
1546 data_counters.useful <= conf_watermark) {
1547 shrink_buffer();
1548 filling = fill_buffer();
1555 void buffering_init(void)
1557 mutex_init(&llist_mutex);
1558 mutex_init(&llist_mod_mutex);
1559 #ifdef HAVE_PRIORITY_SCHEDULING
1560 /* This behavior not safe atm */
1561 mutex_set_preempt(&llist_mutex, false);
1562 mutex_set_preempt(&llist_mod_mutex, false);
1563 #endif
1565 conf_watermark = BUFFERING_DEFAULT_WATERMARK;
1567 queue_init(&buffering_queue, true);
1568 buffering_thread_id = create_thread( buffering_thread, buffering_stack,
1569 sizeof(buffering_stack), CREATE_THREAD_FROZEN,
1570 buffering_thread_name IF_PRIO(, PRIORITY_BUFFERING)
1571 IF_COP(, CPU));
1573 queue_enable_queue_send(&buffering_queue, &buffering_queue_sender_list,
1574 buffering_thread_id);
1577 /* Initialise the buffering subsystem */
1578 bool buffering_reset(char *buf, size_t buflen)
1580 if (!buf || !buflen)
1581 return false;
1583 buffer = buf;
1584 /* Preserve alignment when wrapping around */
1585 buffer_len = buflen & ~STORAGE_ALIGN_MASK;
1586 guard_buffer = buf + buflen;
1588 buf_widx = 0;
1589 buf_ridx = 0;
1591 first_handle = NULL;
1592 cur_handle = NULL;
1593 cached_handle = NULL;
1594 num_handles = 0;
1595 base_handle_id = -1;
1597 /* Set the high watermark as 75% full...or 25% empty :) */
1598 #if MEM > 8
1599 high_watermark = 3*buflen / 4;
1600 #endif
1602 thread_thaw(buffering_thread_id);
1604 return true;
1607 void buffering_get_debugdata(struct buffering_debug *dbgdata)
1609 update_data_counters();
1610 dbgdata->num_handles = num_handles;
1611 dbgdata->data_rem = data_counters.remaining;
1612 dbgdata->wasted_space = data_counters.wasted;
1613 dbgdata->buffered_data = data_counters.buffered;
1614 dbgdata->useful_data = data_counters.useful;
1615 dbgdata->watermark = conf_watermark;