source: trunk/libtransmission/cache.c @ 10978

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

(trunk libT) #1521 "memory cache to reduce disk IO" -- apply Longinus' libt_fixCache.patch version 3

File size: 12.1 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 max_blocks;
52    size_t max_bytes;
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  int       pos;
67  int       rank;
68  time_t    last_block_time;
69  tr_bool   is_multi_piece;
70  tr_bool   is_piece_done;
71  unsigned  len;
72};
73
74
75/* return a count of how many contiguous blocks there are starting at this pos */
76static int
77getBlockRun( const tr_cache * cache, int pos, struct run_info * info )
78{
79    int i;
80    const int n = tr_ptrArraySize( &cache->blocks );
81    const struct cache_block ** blocks = (const struct cache_block**) tr_ptrArrayBase( &cache->blocks );
82    const struct cache_block * ref = blocks[pos];
83    tr_block_index_t block = ref->block;
84
85    for( i=pos; i<n; ++i, ++block ) {
86        const struct cache_block * b = blocks[i];
87        if( b->block != block ) break;
88        if( b->tor != ref->tor ) break;
89//fprintf( stderr, "pos %d tor %d block %zu time %zu\n", i, b->tor->uniqueId, (size_t)b->block, (size_t)b->time );
90    }
91
92//fprintf( stderr, "run is %d long from [%d to %d)\n", (int)(i-pos), i, (int)pos );
93    if( info != NULL ) {
94        const struct cache_block * b = blocks[i-1];
95        info->last_block_time = b->time;
96        info->is_piece_done = tr_cpPieceIsComplete( &b->tor->completion, b->piece );
97        info->is_multi_piece = b->piece != blocks[pos]->piece ? TRUE : FALSE;
98        info->len = i - pos;
99        info->pos = pos;
100    }
101
102    return i-pos;
103}
104
105static int
106compareRuns( const void * va, const void * vb )
107{
108    const struct run_info a = *(const struct run_info*)va;
109    const struct run_info b = *(const struct run_info*)vb;
110    return b.rank - a.rank;
111}
112
113enum
114{
115    MULTIFLAG   = 0x1000,
116    DONEFLAG    = 0x2000,
117    SESSIONFLAG = 0x4000
118};
119/* Calculte runs
120 *   - Stale runs, runs sitting in cache for a long time or runs not growing, get priority.
121 */
122static void
123calcRuns( tr_cache * cache, struct run_info * runs )
124{
125    const int n = tr_ptrArraySize( &cache->blocks );
126    int i = 0, pos;
127    const time_t now = tr_time();
128
129    for( pos = 0; pos < n; pos += runs[i++].len )
130    {
131        int rank = getBlockRun( cache, pos, &runs[i] );
132
133        /* This adds ~2 to the relative length of a run for every minute it has
134         * languished in the cache. */
135        rank += ( now - runs[i].last_block_time ) / 32;
136
137        /* Flushing stale blocks should be a top priority as the probability of them
138         * growing is very small, for blocks on piece boundaries, and nonexistant for
139         * blocks inside pieces. */
140        rank |= runs[i].is_piece_done ? DONEFLAG : 0;
141
142        /* Move the multi piece runs higher */
143        rank |= runs[i].is_multi_piece ? MULTIFLAG : 0;
144
145        runs[i].rank = rank;
146//fprintf(stderr,"block run at pos %d of length %d and age %ld adjusted +%d\n",runs[i].pos,runs[i].len,now-runs[i].last_block_time,rank-runs[i].len);
147    }
148
149    //fprintf( stderr, "%d block runs\n", i-1 );
150    qsort( runs, i, sizeof( struct run_info ), compareRuns );
151    //return i;
152}
153
154static int
155flushContiguous( tr_cache * cache, int pos, int n, int rank )
156{
157    int i;
158    int err = 0;
159    uint8_t * buf = tr_new( uint8_t, n * MAX_BLOCK_SIZE );
160    uint8_t * walk = buf;
161    struct cache_block ** blocks = (struct cache_block**) tr_ptrArrayBase( &cache->blocks );
162
163    struct cache_block * b = blocks[pos];
164    tr_torrent * tor             = b->tor;
165    const tr_piece_index_t piece = b->piece;
166    const uint32_t offset        = b->offset;
167
168//fprintf( stderr, "flushing %d contiguous blocks [%d-%d) from cache to disk\n", n, pos, n+pos );
169
170    for( i=pos; i<pos+n; ++i ) {
171        b = blocks[i];
172        memcpy( walk, b->buf, b->length );
173        walk += b->length;
174        tr_free( b->buf );
175        tr_free( b );
176    }
177    tr_ptrArrayErase( &cache->blocks, pos, pos+n );
178
179    tr_tordbg( tor, "Writing to disk piece %d, offset %d, len %d", (int)piece, (int)offset, (int)(walk-buf) );
180    tr_ndbg( MY_NAME, "Removing %d blocks from cache, rank: %d - %d left", n, rank, tr_ptrArraySize(&cache->blocks) );
181    //fprintf( stderr, "%s - Writing to disk piece %d, offset %d, len %d\n", tr_torrentName(tor), (int)piece, (int)offset, (int)(walk-buf) );
182    //fprintf( stderr, "%s - Removing %d blocks from cache; %d left\n", MY_NAME, n, tr_ptrArraySize(&cache->blocks) );
183
184    err = tr_ioWrite( tor, piece, offset, walk-buf, buf );
185    tr_free( buf );
186
187    ++cache->disk_writes;
188    cache->disk_write_bytes += walk-buf;
189    return err;
190}
191
192static int
193flushRuns( tr_cache * cache, struct run_info * runs, int n )
194{
195    int i, j, err = 0;
196
197    for( i = 0; !err && i < n; ++i )
198    {
199        err = flushContiguous( cache, runs[i].pos, runs[i].len, runs[i].rank );
200        for( j = i + 1; j < n; ++j )
201            if( runs[j].pos > runs[i].pos )
202                runs[j].pos -= runs[i].len;
203    }
204
205    return err;
206}
207
208static int
209cacheTrim( tr_cache * cache )
210{
211    int err = 0;
212
213    if( tr_ptrArraySize( &cache->blocks ) > cache->max_blocks )
214    {
215        /* Amount of cache that should be removed by the flush. This influences how large
216         * runs can grow as well as how often flushes will happen. */
217        const int cacheCutoff = 1 + cache->max_blocks / 4;
218        struct run_info * runs = tr_new( struct run_info, tr_ptrArraySize( &cache->blocks ) );
219        int i = 0, j = 0;
220
221        calcRuns( cache, runs );
222        while( j < cacheCutoff )
223            j += runs[i++].len;
224        err = flushRuns( cache, runs, i );
225        tr_free( runs );
226    }
227
228    return err;
229}
230
231/***
232****
233***/
234
235static int
236getMaxBlocks( int64_t max_bytes )
237{
238    return max_bytes / (double)MAX_BLOCK_SIZE;
239}
240
241int
242tr_cacheSetLimit( tr_cache * cache, int64_t max_bytes )
243{
244    char buf[128];
245
246    cache->max_bytes = max_bytes;
247    cache->max_blocks = getMaxBlocks( max_bytes );
248
249    tr_formatter_mem_B( buf, cache->max_bytes, sizeof( buf ) );
250    tr_ndbg( MY_NAME, "Maximum cache size set to %s (%d blocks)", buf, cache->max_blocks );
251
252    return cacheTrim( cache );
253}
254
255int64_t
256tr_cacheGetLimit( const tr_cache * cache )
257{
258    return cache->max_bytes;
259}
260
261tr_cache *
262tr_cacheNew( int64_t max_bytes )
263{
264    tr_cache * cache = tr_new0( tr_cache, 1 );
265    cache->blocks = TR_PTR_ARRAY_INIT;
266    cache->max_bytes = max_bytes;
267    cache->max_blocks = getMaxBlocks( max_bytes );
268    return cache;
269}
270
271void
272tr_cacheFree( tr_cache * cache )
273{
274    assert( tr_ptrArrayEmpty( &cache->blocks ) );
275    tr_ptrArrayDestruct( &cache->blocks, NULL );
276    tr_free( cache );
277}
278
279/***
280****
281***/
282
283static int
284cache_block_compare( const void * va, const void * vb )
285{
286    const struct cache_block * a = va;
287    const struct cache_block * b = vb;
288
289    /* primary key: torrent id */
290    if( a->tor->uniqueId != b->tor->uniqueId )
291        return a->tor->uniqueId < b->tor->uniqueId ? -1 : 1;
292
293    /* secondary key: block # */
294    if( a->block != b->block )
295        return a->block < b->block ? -1 : 1;
296
297    /* they're equal */
298    return 0;
299}
300
301static struct cache_block *
302findBlock( tr_cache           * cache,
303           tr_torrent         * torrent, 
304           tr_piece_index_t     piece,
305           uint32_t             offset )
306{
307    struct cache_block key;
308    key.tor = torrent;
309    key.block = _tr_block( torrent, piece, offset );
310    return tr_ptrArrayFindSorted( &cache->blocks, &key, cache_block_compare );
311}
312
313int
314tr_cacheWriteBlock( tr_cache         * cache,
315                    tr_torrent       * torrent,
316                    tr_piece_index_t   piece,
317                    uint32_t           offset,
318                    uint32_t           length,
319                    const uint8_t    * writeme )
320{
321    struct cache_block * cb = findBlock( cache, torrent, piece, offset );
322
323    if( cb == NULL )
324    {
325        cb = tr_new( struct cache_block, 1 );
326        cb->tor = torrent;
327        cb->piece = piece;
328        cb->offset = offset;
329        cb->length = length;
330        cb->block = _tr_block( torrent, piece, offset );
331        cb->buf = NULL;
332        tr_ptrArrayInsertSorted( &cache->blocks, cb, cache_block_compare );
333    }
334
335    cb->time = tr_time();
336
337    tr_free( cb->buf );
338    cb->buf = tr_memdup( writeme, cb->length );
339
340    ++cache->cache_writes;
341    cache->cache_write_bytes += cb->length;
342
343    return cacheTrim( cache );
344}
345
346int
347tr_cacheReadBlock( tr_cache         * cache,
348                   tr_torrent       * torrent,
349                   tr_piece_index_t   piece,
350                   uint32_t           offset,
351                   uint32_t           len,
352                   uint8_t          * setme )
353{
354    int err = 0;
355    struct cache_block * cb = findBlock( cache, torrent, piece, offset );
356
357    if( cb )
358        memcpy( setme, cb->buf, len );
359    else
360        err = tr_ioRead( torrent, piece, offset, len, setme );
361
362    return err;
363}
364
365int
366tr_cachePrefetchBlock( tr_cache         * cache,
367                       tr_torrent       * torrent,
368                       tr_piece_index_t   piece,
369                       uint32_t           offset,
370                       uint32_t           len )
371{
372    int err = 0;
373    struct cache_block * cb = findBlock( cache, torrent, piece, offset );
374
375    if( cb == NULL )
376        err = tr_ioPrefetch( torrent, piece, offset, len );
377
378    return err;
379}
380
381/***
382****
383***/
384
385static int
386findPiece( tr_cache * cache, tr_torrent * torrent, tr_piece_index_t piece )
387{
388    struct cache_block key;
389    key.tor = torrent;
390    key.block = tr_torPieceFirstBlock( torrent, piece );
391    return tr_ptrArrayLowerBound( &cache->blocks, &key, cache_block_compare, NULL );
392}
393
394int tr_cacheFlushDone( tr_cache * cache )
395{
396    int err = 0;
397
398    if( tr_ptrArraySize( &cache->blocks ) > 0 )
399    {
400        struct run_info * runs = tr_new0( struct run_info, tr_ptrArraySize( &cache->blocks ) );
401        int i = 0;
402
403        calcRuns( cache, runs );
404        while( runs[i].is_piece_done || runs[i].is_multi_piece )
405            runs[i++].rank |= SESSIONFLAG;
406        err = flushRuns( cache, runs, i );
407        tr_free( runs );
408    }
409
410    return err;
411}
412
413int
414tr_cacheFlushFile( tr_cache * cache, tr_torrent * torrent, tr_file_index_t i )
415{
416    int err = 0;
417    const tr_file * file = &torrent->info.files[i];
418    const tr_block_index_t begin = tr_torPieceFirstBlock( torrent, file->firstPiece );
419    const tr_block_index_t end  = tr_torPieceFirstBlock( torrent, file->lastPiece ) + tr_torPieceCountBlocks( torrent, file->lastPiece );
420    const int pos = findPiece( cache, torrent, file->firstPiece );
421    dbgmsg( "flushing file %d from cache to disk: blocks [%zu...%zu)", (int)i, (size_t)begin, (size_t)end );
422
423    /* flush out all the blocks in that file */
424    while( !err && ( pos < tr_ptrArraySize( &cache->blocks ) ) )
425    {
426        const struct cache_block * b = tr_ptrArrayNth( &cache->blocks, pos );
427        if( b->tor != torrent ) break;
428        if( ( b->block < begin ) || ( b->block >= end ) ) break;
429        err = flushContiguous( cache, pos, getBlockRun( cache, pos, NULL ), 0 );
430    }
431
432    return err;
433}
434
435int
436tr_cacheFlushTorrent( tr_cache * cache, tr_torrent * torrent )
437{
438    int err = 0;
439    const int pos = findPiece( cache, torrent, 0 );
440
441    /* flush out all the blocks in that torrent */
442    while( !err && ( pos < tr_ptrArraySize( &cache->blocks ) ) )
443    {
444        const struct cache_block * b = tr_ptrArrayNth( &cache->blocks, pos );
445        if( b->tor != torrent ) break;
446        err = flushContiguous( cache, pos, getBlockRun( cache, pos, NULL ), 0 );
447    }
448
449    return err;
450}
Note: See TracBrowser for help on using the repository browser.