<p>I'm working on an embedded Linux project that interfaces an ARM9 to a hardware video encoder chip, and writes the video out to SD card or USB stick. The software architecture involves a kernel driver that reads data into a pool of buffers, and a userland app that writes the data to a file on the mounted removable device.</p>

<p>I am finding that above a certain data rate (around 750kbyte/sec) I start to see the userland video-writing app stalling for maybe half a second, about every 5 seconds. This is enough to cause the kernel driver to run out of buffers - and even if I could increase the number of buffers, the video data has to be synchronised (ideally within 40ms) with other things that are going on in real time. Between these 5 second "lag spikes", the writes complete well within 40ms (as far as the app is concerned - I appreciate they're buffered by the OS)</p>

<p>I think this lag spike is to do with the way Linux is flushing data out to disk - I note that pdflush is designed to wake up every 5s, my understanding is that this would be what does the writing. As soon as the stall is over the userland app is able to quickly service and write the backlog of buffers (that didn't overflow).</p>

<p>I think the device I'm writing to has reasonable ultimate throughput: copying a 15MB file from a memory fs and waiting for sync to complete (and the usb stick's light to stop flashing) gave me a write speed of around 2.7MBytes/sec.</p>

<p>I'm looking for two kinds of clues:</p>

<ol>
<li><p>How can I stop the bursty writing from stalling my app - perhaps process priorities, realtime patches, or tuning the filesystem code to write continuously rather than burstily?</p></li>
<li><p>How can I make my app(s) aware of what is going on with the filesystem in terms of write backlog and throughput to the card/stick? I have the ability to change the video bitrate in the hardware codec on the fly which would be much better than dropping frames, or imposing an artificial cap on maximum allowed bitrate.</p></li>
</ol>

<p>Some more info: this is a 200MHz ARM9 currently running a Montavista 2.6.10-based kernel.</p>

<p>Updates:<ul>
<li>Mounting the filesystem SYNC causes throughput to be much too poor.
<li>The removable media is FAT/FAT32 formatted and must be as the purpose of the design is that the media can be plugged into any Windows PC and read.
<li>Regularly calling sync() or fsync() say, every second causes regular stalls and unacceptably poor throughput
<li>I am using write() and open(O_WRONLY | O_CREAT | O_TRUNC) rather than fopen() etc.
<li>I can't immediately find anything online about the mentioned "Linux realtime filesystems". Links?
</ul></p>

<p>I hope this makes sense. First embedded Linux question on stackoverflow? :)</p>

[{'answer_id': 78200, 'author': 'jfs', 'author_id': 6223, 'author_profile': 'https://Stackoverflow.com/users/6223', 'pm_score': 0, 'selected': False, 'text': "<p>Well obvious first, have you tried explicitly telling the file to flush? I also think there might be some ioctl you can use to do it, but I honestly haven't done much C/POSIX file programming.</p>\n\n<p>Seeing you're on a Linux kernel you should be able to tune and rebuild the kernel to something that suits your needs better, eg. much more frequent but then also smaller flushes to the permanent storage.</p>\n\n<hr>\n\n<p>A quick check in my man pages finds this:</p>\n\n<pre>SYNC(2)                    Linux Programmer’s Manual                   SYNC(2)\n\nNAME\n       sync - commit buffer cache to disk\n\nSYNOPSIS\n       #include &lt;unistd.h&gt;\n\n       void sync(void);\n\n   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):\n\n       sync(): _BSD_SOURCE || _XOPEN_SOURCE >= 500\n\nDESCRIPTION\n       sync() first commits inodes to buffers, and then buffers to disk.\n\nERRORS\n       This function is always successful.</pre>\n"}, {'answer_id': 78231, 'author': 'Ori Pessach', 'author_id': 9047, 'author_profile': 'https://Stackoverflow.com/users/9047', 'pm_score': 1, 'selected': False, 'text': "<p>Without knowing more about your particular circumstances, I can only offer the following guesses:</p>\n\n<p>Try using fsync()/sync() to force the kernel to flush data to the storage device more frequently. It sounds like the kernel buffers all your writes and then ties up the bus or otherwise stalls your system while performing the actual write. With careful calls to fsync() you can try to schedule writes over the system bus in a more fine grained way.</p>\n\n<p>It might make sense to structure the application in such a way that the encoding/capture (you didn't mention video capture, so I'm making an assumption here - you might want to add more information) task runs in its own thread and buffers its output in userland - then, a second thread can handle writing to the device. This will give you a smoothing buffer to allow the encoder to always finish its writes without blocking.</p>\n\n<p>One thing that sounds suspicious is that you only see this problem at a certain data rate - if this really was a buffering issue, I'd expect the problem to happen less frequently at lower data rates, but I'd still expect to see this issue.</p>\n\n<p>In any case, more information might prove useful. What's your system's architecture? (In very general terms.)</p>\n\n<p>Given the additional information you provided, it sounds like the device's throughput is rather poor for small writes and frequent flushes. If you're sure that for larger writes you can get sufficient throughput (and I'm not sure that's the case, but the file system might be doing something stupid, like updating the FAT after every write) then having an encoding thread piping data to a writing thread with sufficient buffering in the writing thread to avoid stalls. I've used shared memory ring buffers in the past to implement this kind of scheme, but any IPC mechanism that would allow the writer to write to the I/O process without stalling unless the buffer is full should do the trick.</p>\n"}, {'answer_id': 78281, 'author': 'JBB', 'author_id': 12332, 'author_profile': 'https://Stackoverflow.com/users/12332', 'pm_score': 2, 'selected': False, 'text': "<p>Sounds like you're looking for linux realtime filesystems.  Be sure to search Google et al for that.</p>\n\n<p>XFS has a realtime option, though I haven't played with it. </p>\n\n<p>hdparm might let you turn off the caching altogether.</p>\n\n<p>Tuning the filesystem options (turn off all the extra unneeded file attributes) might reduce what you need to flush, thus speeding the flush. I doubt that'd help much, though.</p>\n\n<p>But my suggestion would be to avoid using the stick as a filesystem at all and instead use it as a raw device. Stuff data on it like you would using 'dd'. Then elsewhere read that raw data and write it out after baking.</p>\n\n<p>Of course, I don't know if that's an option for you.</p>\n"}, {'answer_id': 78284, 'author': 'Drew Frezell', 'author_id': 10954, 'author_profile': 'https://Stackoverflow.com/users/10954', 'pm_score': 3, 'selected': False, 'text': "<p>I'll throw out some suggestions, advice is cheap.</p>\n\n<ul>\n<li>make sure you are using a lower level API for writing to the disk, don't use user-mode caching functions like <code>fopen, fread, fwrite</code> use the lower level functions <code>open, read, write</code>.</li>\n<li>pass the <code>O_SYNC</code> flag when you open the file, this will cause each write operation to block until written to disk, which will remove the bursty behavior of your writes...with the expense of each write being slower.</li>\n<li>If you are doing reads/ioctls from a device to grab a chunk of video data, you may want to consider allocating a shared memory region between the application and kernel, otherwise you are getting hit with a bunch of <code>copy_to_user</code> calls when transferring video data buffers from kernel space to user space.</li>\n<li>You may need to validate that your USB flash device is fast enough with sustained transfers to write the data.</li>\n</ul>\n\n<p>Just a couple thoughts, hope this helps.</p>\n"}, {'answer_id': 83438, 'author': 'JBB', 'author_id': 12332, 'author_profile': 'https://Stackoverflow.com/users/12332', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://www.westnet.com/~gsmith/content/linux-pdflush.htm" rel="nofollow noreferrer">Here</a> is some information about tuning pdflush for write-heavy operations.</p>\n'}, {'answer_id': 84160, 'author': 'shodanex', 'author_id': 11589, 'author_profile': 'https://Stackoverflow.com/users/11589', 'pm_score': 1, 'selected': False, 'text': '<p>Has a debugging aid, you could use strace to see what operations is taking time.\nThere might be some surprising thing with the FAT/FAT32.</p>\n\n<p>Do you write into a single file, or in multiple file ?</p>\n\n<p>You can make a reading thread, that will maintain a pool of video buffer ready to be written in a queue. \nWhen a frame is received, it is added to the queue, and the writing thread is signaled</p>\n\n<p>Shared data</p>\n\n<pre><code>empty_buffer_queue\nready_buffer_queue\nvideo_data_ready_semaphore\n</code></pre>\n\n<p>Reading thread :</p>\n\n<pre><code>buf=get_buffer()\nbufer_to_write = buf_dequeue(empty_buffer_queue)\nmemcpy(bufer_to_write, buf)\nbuf_enqueue(bufer_to_write, ready_buffer_queue)\nsem_post(video_data_ready_semaphore)\n</code></pre>\n\n<p>Writing thread</p>\n\n<pre><code>sem_wait(vido_data_ready_semaphore)\nbufer_to_write = buf_dequeue(ready_buffer_queue)\nwrite_buffer\nbuf_enqueue(bufer_to_write, empty_buffer_queue)\n</code></pre>\n\n<p>If your writing threaded is blocked waiting for the kernel, this could work.\nHowever, if you are blocked inside the kerne space, then thereis nothing much you can do, except looking for a more recent kernel than your 2.6.10</p>\n'}, {'answer_id': 85358, 'author': 'pjz', 'author_id': 8002, 'author_profile': 'https://Stackoverflow.com/users/8002', 'pm_score': 0, 'selected': False, 'text': "<p>Doing your own flush()ing sounds right to me - you want to be in control, not leave it to the vagaries of the generic buffer layer.</p>\n\n<p>This may be obvious, but make sure you're not calling write() too often - make sure every write() has enough data to be written to make the syscall overhead worth it.  Also, in the other direction, don't call it too seldom, or it'll block for long enough to cause a problem.</p>\n\n<p>On a more difficult-to-reimplement track, have you tried switching to asynchronous i/o?  Using aio you could fire off a write and hand it one set of buffers while you're sucking video data into the other set, and when the write finishes you switch sets of buffers.</p>\n"}, {'answer_id': 93050, 'author': 'Zan Lynx', 'author_id': 13422, 'author_profile': 'https://Stackoverflow.com/users/13422', 'pm_score': 1, 'selected': False, 'text': "<p>A useful Linux function and alternative to sync or fsync is sync_file_range.  This lets you schedule data for writing without waiting for the in-kernel buffer system to get around to it.</p>\n\n<p>To avoid long pauses, make sure your IO queue (for example: /sys/block/hda/queue/nr_requests) is large enough.  That queue is where data goes in between being flushed from memory and arriving on disk.</p>\n\n<p>Note that sync_file_range isn't portable, and is only available in kernels 2.6.17 and later.</p>\n"}, {'answer_id': 215547, 'author': 'blueshift', 'author_id': 14200, 'author_profile': 'https://Stackoverflow.com/users/14200', 'pm_score': 4, 'selected': True, 'text': "<p>For the record, there turned out to be two main aspects that seem to have eliminated the problem in all but the most extreme cases. This system is still in development and hasn't been thoroughly torture-tested yet but is working fairly well (touch wood).</p>\n\n<p>The big win came from making the userland writer app multi-threaded. It is the calls to write() that block sometimes: other processes and threads still run. So long as I have a thread servicing the device driver and updating frame counts and other data to sychronise with other apps that are running, the data can be buffered and written out a few seconds later without breaking any deadlines. I tried a simple ping-pong double buffer first but that wasn't enough; small buffers would be overwhelmed and big ones just caused bigger pauses while the filesystem digested the writes. A pool of 10 1MB buffers queued between threads is working well now.</p>\n\n<p>The other aspect is keeping an eye on ultimate write throughput to physical media. For this I am keeping an eye on the stat Dirty: reported by /proc/meminfo. I have some rough and ready code to throttle the encoder if Dirty: climbs above a certain threshold, seems to vaguely work. More testing and tuning needed later. Fortunately I have lots of RAM (128M) to play with giving me a few seconds to see my backlog building up and throttle down smoothly.</p>\n\n<p>I'll try to remember to pop back and update this answer if I find I need to do anything else to deal with this issue. Thanks to the other answerers.</p>\n"}, {'answer_id': 4211588, 'author': 'David Cary', 'author_id': 238320, 'author_profile': 'https://Stackoverflow.com/users/238320', 'pm_score': 1, 'selected': False, 'text': '<p>I\'ve been told that after the host sends a command, MMC and SD cards "must respond within 0 to 8 bytes".</p>\n\n<p>However, the spec allows these cards to respond with "busy" until they have finished the operation, and apparently there is no limit to how long a card can claim to be busy (please, please tell me if there is such a limit).</p>\n\n<p>I see that some low-cost flash chips such as the M25P80 have a guaranteed "maximum single-sector erase time" of 3 seconds, although typically it "only" requires 0.6 seconds.</p>\n\n<p>That 0.6 seconds sounds suspiciously similar to your "stalling for maybe half a second".</p>\n\n<p>I suspect the tradeoff between cheap, slow flash chips and expensive, fast flash chips has something to do with the wide variation in USB flash drive results:</p>\n\n<ul>\n<li><a href="http://www.testfreaks.com/blog/information/16gb-usb-drive-comparison-17-drives-compared/" rel="nofollow">http://www.testfreaks.com/blog/information/16gb-usb-drive-comparison-17-drives-compared/</a></li>\n<li><a href="http://www.tomshardware.com/reviews/data-transfer-run,1037-10.html" rel="nofollow">http://www.tomshardware.com/reviews/data-transfer-run,1037-10.html</a></li>\n</ul>\n\n<p>I\'ve heard rumors that every time a flash sector is erased and then re-programmed, it takes a little bit longer than the last time.</p>\n\n<p>So if you have a time-critical application, you may need to (a) test your SD cards and USB sticks to make sure they meet the minimum latency, bandwidth, etc. required by your application, and (b) peridically re-test or pre-emptively replace these memory devices.</p>\n'}]
['https://Stackoverflow.com/questions/78157', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14200/']