source: trunk/libtransmission/cache.c @ 10923

Last change on this file since 10923 was 10923, checked in by charles, 12 years ago

(trunk libT) #1521 "memory cache to reduce disk IO" -- improve one of the debugging messages

File size: 10.5 KB
Line 
1/*
2 * This file Copyright (C) 2010 Mnemosyne LLC
3 *
4 * This file is licensed by the GPL version 2.  Works owned by the
5 * Transmission project are granted a special exemption to clause 2(b)
6 * so that the bulk of its code can remain under the MIT license.
7 * This exemption does not extend to derived works not owned by
8 * the Transmission project.
9 *
10 * $Id$
11 */
12
13#include "transmission.h"
14#include "cache.h"
15#include "inout.h"
16#include "peer-common.h" /* MAX_BLOCK_SIZE */
17#include "ptrarray.h"
18#include "torrent.h"
19#include "utils.h"
20
21#define MY_NAME "Cache"
22
23#define dbgmsg( ... ) \
24    do { \
25        if( tr_deepLoggingIsActive( ) ) \
26            tr_deepLog( __FILE__, __LINE__, MY_NAME, __VA_ARGS__ ); \
27    } while( 0 )
28
29
30/****
31*****
32****/
33
34struct cache_block
35{
36    tr_torrent * tor;
37
38    tr_piece_index_t piece;
39    uint32_t offset;
40    uint32_t length;
41
42    time_t time;
43    tr_block_index_t block;
44
45    uint8_t * buf;
46};
47
48struct tr_cache
49{
50    tr_ptrArray blocks;
51    int maxBlocks;
52    size_t maxMiB;
53
54    size_t disk_writes;
55    size_t disk_write_bytes;
56    size_t cache_writes;
57    size_t cache_write_bytes;
58};
59
60/****
61*****
62****/
63
64struct run_info
65{
66  time_t  last_block_time;
67  tr_bool is_aligned;
68};
69
70
71/* return a count of how many contiguous blocks there are starting at this pos */
72static int
73getBlockRun( const tr_cache * cache, int pos, struct run_info * info )
74{
75    int i;
76    const int n = tr_ptrArraySize( &cache->blocks );
77    const struct cache_block ** blocks = (const struct cache_block**) tr_ptrArrayBase( &cache->blocks );
78    const struct cache_block * ref = blocks[pos];
79    tr_block_index_t block = ref->block;
80
81    for( i=pos; i<n; ++i, ++block ) {
82        const struct cache_block * b = blocks[i];
83        if( b->block != block ) break;
84        if( b->tor != ref->tor ) break;
85//fprintf( stderr, "pos %d tor %d block %zu time %zu\n", i, b->tor->uniqueId, (size_t)b->block, (size_t)b->time );
86    }
87
88//fprintf( stderr, "run is %d long from [%d to %d)\n", (int)(i-pos), i, (int)pos );
89    if( info != NULL ) {
90        info->last_block_time = blocks[i-1]->time;
91        info->is_aligned = (blocks[pos]->block % 2 == 0) ? TRUE : FALSE;
92    }
93
94    return i-pos;
95}
96
97/* return the starting index of the longest contiguous run of blocks BUT:
98 *   1 - Length of run must be even.
99 *   2 - Run must begin with a even block.
100 *   3 - Oldest run is preferred.
101 */
102static int
103findChunk2Discard( tr_cache * cache, int * setme_n )
104{
105    const int n = tr_ptrArraySize( &cache->blocks );
106    int pos;
107    int bestpos = 0;
108    unsigned bestlen = 1;
109    unsigned jump;
110    time_t oldest_time = ~0;
111    struct run_info run;
112
113    for( pos=0; pos<n; pos+=jump )
114    {
115        unsigned len = getBlockRun( cache, pos, &run );
116        jump = len;
117
118        /* shortcut */
119        if( len < bestlen )
120            continue;
121
122        /* check alignment */
123        if( len % 2 == 0 ) {
124            if( !run.is_aligned )
125                /* Let it grow. Otherwise we contribute to fragmentation */
126                continue;
127        } else {
128            if( len != 1 ) {
129                --len;
130                if( !run.is_aligned ) {
131                    ++pos;
132                    --jump;
133                }
134            }
135        }
136
137        if( bestlen < len ) {
138            bestlen = len;
139            bestpos = pos;
140            oldest_time = run.last_block_time;
141        } else if( (bestlen == len) && (oldest_time > run.last_block_time) ) {
142            bestpos = pos;
143            oldest_time = run.last_block_time;
144        }
145    }
146
147//fprintf( stderr, "DISCARDED run is %d long from [%d to %d)\n", bestlen, bestpos, bestpos+bestlen );
148    *setme_n = bestlen;
149    return bestpos;
150}
151
152static int
153flushContiguous( tr_cache * cache, int pos, int n )
154{
155    int i;
156    int err = 0;
157    uint8_t * buf = tr_new( uint8_t, n * MAX_BLOCK_SIZE );
158    uint8_t * walk = buf;
159    struct cache_block ** blocks = (struct cache_block**) tr_ptrArrayBase( &cache->blocks );
160
161    struct cache_block * b = blocks[pos];
162    tr_torrent * tor             = b->tor;
163    const tr_piece_index_t piece = b->piece;
164    const uint32_t offset        = b->offset;
165
166//fprintf( stderr, "flushing %d contiguous blocks [%d-%d) from cache to disk\n", n, pos, n+pos );
167
168    for( i=pos; i<pos+n; ++i ) {
169        b = blocks[i];
170        memcpy( walk, b->buf, b->length );
171        walk += b->length;
172        tr_free( b->buf );
173        tr_free( b );
174    }
175    tr_ptrArrayErase( &cache->blocks, pos, pos+n );
176
177    tr_tordbg( tor, "Writing to disk piece %d, offset %d, len %d", (int)piece, (int)offset, (int)(walk-buf) );
178    tr_ndbg( MY_NAME, "Removing %d blocks from cache; %d left", n, tr_ptrArraySize(&cache->blocks) );
179    //fprintf( stderr, "%s - Writing to disk piece %d, offset %d, len %d\n", tr_torrentName(tor), (int)piece, (int)offset, (int)(walk-buf) );
180    //fprintf( stderr, "%s - Removing %d blocks from cache; %d left\n", MY_NAME, n, tr_ptrArraySize(&cache->blocks) );
181
182    err = tr_ioWrite( tor, piece, offset, walk-buf, buf );
183    tr_free( buf );
184
185    ++cache->disk_writes;
186    cache->disk_write_bytes += walk-buf;
187    return err;
188}
189
190static int
191cacheTrim( tr_cache * cache )
192{
193    int err = 0;
194
195    while( !err && ( tr_ptrArraySize( &cache->blocks ) > cache->maxBlocks ) )
196    {
197        int n;
198        const int i = findChunk2Discard( cache, &n );
199        err = flushContiguous( cache, i, n );
200    }
201
202    return err;
203}
204
205/***
206****
207***/
208
209static int
210getMaxBlocks( double maxMiB )
211{
212    const double maxBytes = maxMiB * (1024 * 1024);
213    return maxBytes / MAX_BLOCK_SIZE;
214}
215
216int
217tr_cacheSetLimit( tr_cache * cache, double maxMiB )
218{
219    cache->maxMiB = maxMiB;
220    cache->maxBlocks = getMaxBlocks( maxMiB );
221    tr_ndbg( MY_NAME, "Maximum cache size set to %.2f MiB (%d blocks)", maxMiB, cache->maxBlocks );
222    return cacheTrim( cache );
223}
224
225double
226tr_cacheGetLimit( const tr_cache * cache )
227{
228    return cache->maxMiB;
229}
230
231tr_cache *
232tr_cacheNew( double maxMiB )
233{
234    tr_cache * cache = tr_new0( tr_cache, 1 );
235    cache->blocks = TR_PTR_ARRAY_INIT;
236    cache->maxBlocks = getMaxBlocks( maxMiB );
237    return cache;
238}
239
240void
241tr_cacheFree( tr_cache * cache )
242{
243    assert( tr_ptrArrayEmpty( &cache->blocks ) );
244    tr_ptrArrayDestruct( &cache->blocks, NULL );
245    tr_free( cache );
246}
247
248/***
249****
250***/
251
252static int
253cache_block_compare( const void * va, const void * vb )
254{
255    const struct cache_block * a = va;
256    const struct cache_block * b = vb;
257
258    /* primary key: torrent id */
259    if( a->tor->uniqueId != b->tor->uniqueId )
260        return a->tor->uniqueId < b->tor->uniqueId ? -1 : 1;
261
262    /* secondary key: block # */
263    if( a->block != b->block )
264        return a->block < b->block ? -1 : 1;
265
266    /* they're equal */
267    return 0;
268}
269
270static struct cache_block *
271findBlock( tr_cache           * cache,
272           tr_torrent         * torrent, 
273           tr_piece_index_t     piece,
274           uint32_t             offset )
275{
276    struct cache_block key;
277    key.tor = torrent;
278    key.block = _tr_block( torrent, piece, offset );
279    return tr_ptrArrayFindSorted( &cache->blocks, &key, cache_block_compare );
280}
281
282int
283tr_cacheWriteBlock( tr_cache         * cache,
284                    tr_torrent       * torrent,
285                    tr_piece_index_t   piece,
286                    uint32_t           offset,
287                    uint32_t           length,
288                    const uint8_t    * writeme )
289{
290    struct cache_block * cb = findBlock( cache, torrent, piece, offset );
291
292    if( cb == NULL )
293    {
294        cb = tr_new( struct cache_block, 1 );
295        cb->tor = torrent;
296        cb->piece = piece;
297        cb->offset = offset;
298        cb->length = length;
299        cb->block = _tr_block( torrent, piece, offset );
300        cb->buf = NULL;
301        tr_ptrArrayInsertSorted( &cache->blocks, cb, cache_block_compare );
302    }
303
304    cb->time = tr_time();
305
306    tr_free( cb->buf );
307    cb->buf = tr_memdup( writeme, cb->length );
308
309    ++cache->cache_writes;
310    cache->cache_write_bytes += cb->length;
311
312    return cacheTrim( cache );
313}
314
315int
316tr_cacheReadBlock( tr_cache         * cache,
317                   tr_torrent       * torrent,
318                   tr_piece_index_t   piece,
319                   uint32_t           offset,
320                   uint32_t           len,
321                   uint8_t          * setme )
322{
323    int err = 0;
324    struct cache_block * cb = findBlock( cache, torrent, piece, offset );
325
326    if( cb )
327        memcpy( setme, cb->buf, len );
328    else
329        err = tr_ioRead( torrent, piece, offset, len, setme );
330
331    return err;
332}
333
334int
335tr_cachePrefetchBlock( tr_cache         * cache,
336                       tr_torrent       * torrent,
337                       tr_piece_index_t   piece,
338                       uint32_t           offset,
339                       uint32_t           len )
340{
341    int err = 0;
342    struct cache_block * cb = findBlock( cache, torrent, piece, offset );
343
344    if( cb == NULL )
345        err = tr_ioPrefetch( torrent, piece, offset, len );
346
347    return err;
348}
349
350/***
351****
352***/
353
354static int
355findPiece( tr_cache * cache, tr_torrent * torrent, tr_piece_index_t piece )
356{
357    struct cache_block key;
358    key.tor = torrent;
359    key.block = tr_torPieceFirstBlock( torrent, piece );
360    return tr_ptrArrayLowerBound( &cache->blocks, &key, cache_block_compare, NULL );
361}
362
363int
364tr_cacheFlushFile( tr_cache * cache, tr_torrent * torrent, tr_file_index_t i )
365{
366    int err = 0;
367    const tr_file * file = &torrent->info.files[i];
368    const tr_block_index_t begin = tr_torPieceFirstBlock( torrent, file->firstPiece );
369    const tr_block_index_t end  = tr_torPieceFirstBlock( torrent, file->lastPiece ) + tr_torPieceCountBlocks( torrent, file->lastPiece );
370    const int pos = findPiece( cache, torrent, file->firstPiece );
371    dbgmsg( "flushing file %d from cache to disk: blocks [%zu...%zu)", (int)i, (size_t)begin, (size_t)end );
372
373    /* flush out all the blocks in that file */
374    while( !err && ( pos < tr_ptrArraySize( &cache->blocks ) ) )
375    {
376        const struct cache_block * b = tr_ptrArrayNth( &cache->blocks, pos );
377        if( b->tor != torrent ) break;
378        if( ( b->block < begin ) || ( b->block >= end ) ) break;
379        err = flushContiguous( cache, pos, getBlockRun( cache, pos, NULL ) );
380    }
381
382    return err;
383}
384
385int
386tr_cacheFlushTorrent( tr_cache * cache, tr_torrent * torrent )
387{
388    int err = 0;
389    const int pos = findPiece( cache, torrent, 0 );
390
391    /* flush out all the blocks in that torrent */
392    while( !err && ( pos < tr_ptrArraySize( &cache->blocks ) ) )
393    {
394        const struct cache_block * b = tr_ptrArrayNth( &cache->blocks, pos );
395        if( b->tor != torrent ) break;
396        err = flushContiguous( cache, pos, getBlockRun( cache, pos, NULL ) );
397    }
398
399    return err;
400}
Note: See TracBrowser for help on using the repository browser.