source: trunk/libtransmission/fdlimit.c @ 8299

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

(trunk libT) convert tr_open_file_for_scanning() and tr_close_file() to use file descriptors instead of file pointers so that we don't have to mix and match between them

  • Property svn:keywords set to Date Rev Author Id
File size: 16.5 KB
Line 
1/******************************************************************************
2 * $Id: fdlimit.c 8299 2009-04-26 20:44:18Z charles $
3 *
4 * Copyright (c) 2005-2008 Transmission authors and contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *****************************************************************************/
24
25#ifndef WIN32
26 #define HAVE_GETRLIMIT
27#endif
28
29#ifdef HAVE_POSIX_FADVISE
30 #ifdef _XOPEN_SOURCE
31  #undef _XOPEN_SOURCE
32 #endif
33 #define _XOPEN_SOURCE 600
34#endif
35
36#include <assert.h>
37#include <errno.h>
38#include <inttypes.h>
39#include <stdio.h>
40#include <stdlib.h>
41#include <string.h>
42#ifdef SYS_DARWIN
43 #include <fcntl.h>
44#endif
45
46#ifdef HAVE_FALLOCATE
47 #include <linux/falloc.h>
48#endif
49
50#ifdef HAVE_XFS_XFS_H
51 #include <xfs/xfs.h>
52#endif
53
54#include <sys/types.h>
55#include <sys/stat.h>
56#ifdef HAVE_GETRLIMIT
57 #include <sys/time.h> /* getrlimit */
58 #include <sys/resource.h> /* getrlimit */
59#endif
60#include <unistd.h>
61#include <fcntl.h> /* O_LARGEFILE posix_fadvise */
62
63#include <evutil.h>
64
65#include "transmission.h"
66#include "fdlimit.h"
67#include "list.h"
68#include "net.h"
69#include "platform.h" /* tr_lock */
70#include "utils.h"
71
72#define dbgmsg( ... ) \
73    do { \
74        if( tr_deepLoggingIsActive( ) ) \
75            tr_deepLog( __FILE__, __LINE__, NULL, __VA_ARGS__ ); \
76    } while( 0 )
77
78/**
79***
80**/
81
82enum
83{
84    NOFILE_BUFFER = 512, /* the process' number of open files is
85                            globalMaxPeers + NOFILE_BUFFER */
86};
87
88struct tr_openfile
89{
90    tr_bool    isCheckedOut;
91    tr_bool    isWritable;
92    tr_bool    closeWhenDone;
93    char       filename[MAX_PATH_LENGTH];
94    int        fd;
95    uint64_t   date;
96};
97
98struct tr_fd_s
99{
100    int                   socketCount;
101    int                   socketLimit;
102
103    struct tr_openfile  * openFiles;
104    int                   openFileLimit;
105
106    tr_lock             * lock;
107};
108
109static struct tr_fd_s * gFd = NULL;
110
111/***
112****
113****  Local Files
114****
115***/
116
117#ifndef O_LARGEFILE
118 #define O_LARGEFILE 0
119#endif
120
121static tr_bool
122preallocateFileSparse( int fd, uint64_t length )
123{
124    const char zero = '\0';
125
126    if( length == 0 )
127        return TRUE;
128
129    if( lseek( fd, length-1, SEEK_SET ) == -1 )
130        return FALSE;
131    if( write( fd, &zero, 1 ) == -1 )
132        return FALSE;
133    if( ftruncate( fd, length ) == -1 )
134        return FALSE;
135
136    return TRUE;
137}
138
139static tr_bool
140preallocateFileFull( const char * filename, uint64_t length )
141{
142    tr_bool success = 0;
143
144#ifdef WIN32
145
146    HANDLE hFile = CreateFile( filename, GENERIC_WRITE, 0, 0, CREATE_NEW, 0, 0 );
147    if( hFile != INVALID_HANDLE_VALUE )
148    {
149        LARGE_INTEGER li;
150        li.QuadPart = length;
151        success = SetFilePointerEx( hFile, li, NULL, FILE_BEGIN ) && SetEndOfFile( hFile );
152        CloseHandle( hFile );
153    }
154
155#else
156
157    int flags = O_RDWR | O_CREAT | O_LARGEFILE;
158    int fd = open( filename, flags, 0666 );
159    if( fd >= 0 )
160    {
161# ifdef HAVE_XFS_XFS_H
162        if( !success && platform_test_xfs_fd( fd ) )
163        {
164            xfs_flock64_t fl;
165            fl.l_whence = 0;
166            fl.l_start = 0;
167            fl.l_len = length;
168            success = !xfsctl( NULL, fd, XFS_IOC_RESVSP64, &fl );
169        }
170# endif
171# ifdef SYS_DARWIN
172        if( !success )
173        {
174            fstore_t fst;
175            fst.fst_flags = F_ALLOCATECONTIG;
176            fst.fst_posmode = F_PEOFPOSMODE;
177            fst.fst_offset = 0;
178            fst.fst_length = length;
179            fst.fst_bytesalloc = 0;
180            success = !fcntl( fd, F_PREALLOCATE, &fst );
181        }
182# endif
183# ifdef HAVE_FALLOCATE
184        if( !success )
185        {
186            success = !fallocate( fd, FALLOC_FL_KEEP_SIZE, 0, length );
187        }
188# endif
189# ifdef HAVE_POSIX_FALLOCATE
190        if( !success )
191        {
192            success = !posix_fallocate( fd, 0, length );
193        }
194# endif
195
196        close( fd );
197    }
198
199#endif
200
201    return success;
202}
203
204int
205tr_open_file_for_scanning( const char * filename )
206{
207    int fd;
208    int flags;
209
210    /* build the flags */
211    flags = O_RDONLY;
212#ifdef O_SEQUENTIAL
213    if( sequential ) flags |= O_SEQUENTIAL;
214#endif
215#ifdef O_RANDOM
216    if( !sequential ) flags |= O_RANDOM
217#endif
218#ifdef O_BINARY
219    flags |= O_BINARY;
220#endif
221#ifdef O_LARGEFILE
222    flags |= O_LARGEFILE;
223#endif
224
225    /* open the file */
226    fd = open( filename, flags, 0666 );
227    if( fd >= 0 )
228    {
229#ifdef HAVE_POSIX_FADVISE
230        posix_fadvise( fd, 0, 0, POSIX_FADV_SEQUENTIAL );
231#endif
232#ifdef SYS_DARWIN
233        fcntl( fd, F_NOCACHE, 1 );
234        fcntl( fd, F_RDAHEAD, 1 );
235#endif
236    }
237
238    return fd;
239}
240
241void
242tr_close_file( int fd )
243{
244#if defined(HAVE_POSIX_FADVISE)
245    posix_fadvise( fd, 0, 0, POSIX_FADV_DONTNEED );
246#endif
247    close( fd );
248}
249
250/**
251 * returns 0 on success, or an errno value on failure.
252 * errno values include ENOENT if the parent folder doesn't exist,
253 * plus the errno values set by tr_mkdirp() and open().
254 */
255static int
256TrOpenFile( int                      i,
257            const char             * folder,
258            const char             * torrentFile,
259            tr_bool                  doWrite,
260            tr_preallocation_mode    preallocationMode,
261            uint64_t                 desiredFileSize )
262{
263    struct tr_openfile * file = &gFd->openFiles[i];
264    int                  flags;
265    char               * filename;
266    struct stat          sb;
267    int                  alreadyExisted;
268
269    /* confirm the parent folder exists */
270    if( stat( folder, &sb ) || !S_ISDIR( sb.st_mode ) )
271    {
272        tr_err( _( "Couldn't create \"%1$s\": parent folder \"%2$s\" does not exist" ), torrentFile, folder );
273        return ENOENT;
274    }
275
276    /* create subfolders, if any */
277    filename = tr_buildPath( folder, torrentFile, NULL );
278    if( doWrite )
279    {
280        char * tmp = tr_dirname( filename );
281        const int err = tr_mkdirp( tmp, 0777 ) ? errno : 0;
282        if( err ) {
283            tr_err( _( "Couldn't create \"%1$s\": %2$s" ), tmp, tr_strerror( err ) );
284            tr_free( tmp );
285            tr_free( filename );
286            return err;
287        }
288        tr_free( tmp );
289    }
290
291    alreadyExisted = !stat( filename, &sb ) && S_ISREG( sb.st_mode );
292
293    if( doWrite && !alreadyExisted && ( preallocationMode == TR_PREALLOCATE_FULL ) )
294        if( preallocateFileFull( filename, desiredFileSize ) )
295            tr_inf( _( "Preallocated file \"%s\"" ), filename );
296   
297    /* open the file */
298    flags = doWrite ? ( O_RDWR | O_CREAT ) : O_RDONLY;
299#ifdef O_RANDOM
300    flags |= O_RANDOM
301#endif
302#ifdef O_LARGEFILE
303    flags |= O_LARGEFILE;
304#endif
305#ifdef WIN32
306    flags |= O_BINARY;
307#endif
308    file->fd = open( filename, flags, 0666 );
309    if( file->fd == -1 )
310    {
311        const int err = errno;
312        tr_err( _( "Couldn't open \"%1$s\": %2$s" ), filename, tr_strerror( err ) );
313        tr_free( filename );
314        return err;
315    }
316
317    if( doWrite && !alreadyExisted && ( preallocationMode == TR_PREALLOCATE_SPARSE ) )
318        preallocateFileSparse( file->fd, desiredFileSize );
319
320#ifdef HAVE_POSIX_FADVISE
321    posix_fadvise( file->fd, 0, 0, POSIX_FADV_RANDOM );
322#endif
323
324    tr_free( filename );
325    return 0;
326}
327
328static int
329fileIsOpen( const struct tr_openfile * o )
330{
331    return o->fd >= 0;
332}
333
334static void
335TrCloseFile( int i )
336{
337    struct tr_openfile * o = &gFd->openFiles[i];
338
339    assert( i >= 0 );
340    assert( i < gFd->openFileLimit );
341    assert( fileIsOpen( o ) );
342
343    tr_close_file( o->fd );
344    close( o->fd );
345    o->fd = -1;
346    o->isCheckedOut = 0;
347}
348
349static int
350fileIsCheckedOut( const struct tr_openfile * o )
351{
352    return fileIsOpen( o ) && o->isCheckedOut;
353}
354
355/* returns an fd on success, or a -1 on failure and sets errno */
356int
357tr_fdFileCheckout( const char             * folder,
358                   const char             * torrentFile,
359                   tr_bool                  doWrite,
360                   tr_preallocation_mode    preallocationMode,
361                   uint64_t                 desiredFileSize )
362{
363    int i, winner = -1;
364    struct tr_openfile * o;
365    char filename[MAX_PATH_LENGTH];
366
367    assert( folder && *folder );
368    assert( torrentFile && *torrentFile );
369    assert( doWrite == 0 || doWrite == 1 );
370
371    tr_snprintf( filename, sizeof( filename ), "%s%c%s", folder, TR_PATH_DELIMITER, torrentFile );
372    dbgmsg( "looking for file '%s', writable %c", filename, doWrite ? 'y' : 'n' );
373
374    tr_lockLock( gFd->lock );
375
376    /* Is it already open? */
377    for( i = 0; i < gFd->openFileLimit; ++i )
378    {
379        o = &gFd->openFiles[i];
380
381        if( !fileIsOpen( o ) )
382            continue;
383
384        if( strcmp( filename, o->filename ) )
385            continue;
386
387        if( fileIsCheckedOut( o ) )
388        {
389            dbgmsg( "found it!  it's open, but checked out.  waiting..." );
390            tr_lockUnlock( gFd->lock );
391            tr_wait( 200 );
392            tr_lockLock( gFd->lock );
393            i = -1; /* reloop */
394            continue;
395        }
396
397        if( doWrite && !o->isWritable )
398        {
399            dbgmsg(
400                "found it!  it's open and available, but isn't writable. closing..." );
401            TrCloseFile( i );
402            break;
403        }
404
405        dbgmsg( "found it!  it's ready for use!" );
406        winner = i;
407        break;
408    }
409
410    dbgmsg(
411        "it's not already open.  looking for an open slot or an old file." );
412    while( winner < 0 )
413    {
414        uint64_t date = tr_date( ) + 1;
415
416        /* look for the file that's been open longest */
417        for( i = 0; i < gFd->openFileLimit; ++i )
418        {
419            o = &gFd->openFiles[i];
420
421            if( !fileIsOpen( o ) )
422            {
423                winner = i;
424                dbgmsg( "found an empty slot in %d", winner );
425                break;
426            }
427
428            if( date > o->date )
429            {
430                date = o->date;
431                winner = i;
432            }
433        }
434
435        if( winner >= 0 )
436        {
437            if( fileIsOpen( &gFd->openFiles[winner] ) )
438            {
439                dbgmsg( "closing file '%s', slot #%d",
440                        gFd->openFiles[winner].filename,
441                        winner );
442                TrCloseFile( winner );
443            }
444        }
445        else
446        {
447            dbgmsg( "everything's full!  waiting for someone else to finish something" );
448            tr_lockUnlock( gFd->lock );
449            tr_wait( 200 );
450            tr_lockLock( gFd->lock );
451        }
452    }
453
454    assert( winner >= 0 );
455    o = &gFd->openFiles[winner];
456    if( !fileIsOpen( o ) )
457    {
458        const int err = TrOpenFile( winner, folder, torrentFile, doWrite, preallocationMode, desiredFileSize );
459        if( err ) {
460            tr_lockUnlock( gFd->lock );
461            errno = err;
462            return -1;
463        }
464
465        dbgmsg( "opened '%s' in slot %d, doWrite %c", filename, winner,
466                doWrite ? 'y' : 'n' );
467        tr_strlcpy( o->filename, filename, sizeof( o->filename ) );
468        o->isWritable = doWrite;
469    }
470
471    dbgmsg( "checking out '%s' in slot %d", filename, winner );
472    o->isCheckedOut = 1;
473    o->closeWhenDone = 0;
474    o->date = tr_date( );
475    tr_lockUnlock( gFd->lock );
476    return o->fd;
477}
478
479void
480tr_fdFileReturn( int fd )
481{
482    int i;
483
484    tr_lockLock( gFd->lock );
485
486    for( i = 0; i < gFd->openFileLimit; ++i )
487    {
488        struct tr_openfile * o = &gFd->openFiles[i];
489        if( o->fd != fd )
490            continue;
491
492        dbgmsg( "releasing file '%s' in slot #%d", o->filename, i );
493        o->isCheckedOut = 0;
494        if( o->closeWhenDone )
495            TrCloseFile( i );
496
497        break;
498    }
499
500    tr_lockUnlock( gFd->lock );
501}
502
503void
504tr_fdFileClose( const char * filename )
505{
506    int i;
507
508    tr_lockLock( gFd->lock );
509
510    for( i = 0; i < gFd->openFileLimit; ++i )
511    {
512        struct tr_openfile * o = &gFd->openFiles[i];
513        if( !fileIsOpen( o ) || strcmp( filename, o->filename ) )
514            continue;
515
516        dbgmsg( "tr_fdFileClose closing '%s'", filename );
517
518        if( !o->isCheckedOut )
519        {
520            dbgmsg( "not checked out, so closing it now... '%s'", filename );
521            TrCloseFile( i );
522        }
523        else
524        {
525            dbgmsg(
526                "flagging file '%s', slot #%d to be closed when checked in",
527                gFd->openFiles[i].filename, i );
528            o->closeWhenDone = 1;
529        }
530    }
531
532    tr_lockUnlock( gFd->lock );
533}
534
535/***
536****
537****  Sockets
538****
539***/
540
541static int
542getSocketMax( struct tr_fd_s * gFd )
543{
544    return gFd->socketLimit;
545}
546
547int
548tr_fdSocketCreate( int domain, int type )
549{
550    int s = -1;
551
552    tr_lockLock( gFd->lock );
553
554    if( gFd->socketCount < getSocketMax( gFd ) )
555        if( ( s = socket( domain, type, 0 ) ) < 0 )
556        {
557#ifdef SYS_DARWIN
558            if( sockerrno != EAFNOSUPPORT )
559#endif
560            tr_err( _( "Couldn't create socket: %s" ),
561                   tr_strerror( sockerrno ) );
562            s = -sockerrno;
563        }
564
565    if( s > -1 )
566        ++gFd->socketCount;
567
568    assert( gFd->socketCount >= 0 );
569
570    tr_lockUnlock( gFd->lock );
571    return s;
572}
573
574int
575tr_fdSocketAccept( int           b,
576                   tr_address  * addr,
577                   tr_port     * port )
578{
579    int                s = -1;
580    unsigned int       len;
581    struct sockaddr_storage sock;
582
583    assert( addr );
584    assert( port );
585
586    tr_lockLock( gFd->lock );
587    if( gFd->socketCount < getSocketMax( gFd ) )
588    {
589        len = sizeof( struct sockaddr_storage );
590        s = accept( b, (struct sockaddr *) &sock, &len );
591    }
592    if( s > -1 )
593    {
594        /* "The ss_family field of the sockaddr_storage structure will always
595         * align with the family field of any protocol-specific structure." */ 
596        if( sock.ss_family == AF_INET ) 
597        { 
598            struct sockaddr_in * sock4 = (struct sockaddr_in *)&sock; 
599            addr->type = TR_AF_INET; 
600            addr->addr.addr4.s_addr = sock4->sin_addr.s_addr; 
601            *port = sock4->sin_port; 
602        } 
603        else 
604        { 
605            struct sockaddr_in6 * sock6 = (struct sockaddr_in6 *)&sock; 
606            addr->type = TR_AF_INET6; 
607            addr->addr.addr6 = sock6->sin6_addr;
608            *port = sock6->sin6_port; 
609        } 
610        ++gFd->socketCount;
611    }
612    tr_lockUnlock( gFd->lock );
613
614    return s;
615}
616
617static void
618socketClose( int fd )
619{
620    EVUTIL_CLOSESOCKET( fd );
621}
622
623void
624tr_fdSocketClose( int s )
625{
626    tr_lockLock( gFd->lock );
627
628    if( s >= 0 )
629    {
630        socketClose( s );
631        --gFd->socketCount;
632    }
633
634    assert( gFd->socketCount >= 0 );
635
636    tr_lockUnlock( gFd->lock );
637}
638
639/***
640****
641****  Startup / Shutdown
642****
643***/
644
645void
646tr_fdInit( size_t openFileLimit, size_t socketLimit )
647{
648    int i;
649
650    assert( gFd == NULL );
651    gFd = tr_new0( struct tr_fd_s, 1 );
652    gFd->openFiles = tr_new0( struct tr_openfile, openFileLimit );
653    gFd->openFileLimit = openFileLimit;
654    gFd->lock = tr_lockNew( );
655
656#ifdef HAVE_GETRLIMIT
657    {
658        struct rlimit rlim;
659        getrlimit( RLIMIT_NOFILE, &rlim );
660        rlim.rlim_cur = MIN( rlim.rlim_max,
661                            (rlim_t)( socketLimit + NOFILE_BUFFER ) );
662        setrlimit( RLIMIT_NOFILE, &rlim );
663        gFd->socketLimit = rlim.rlim_cur - NOFILE_BUFFER;
664        tr_dbg( "setrlimit( RLIMIT_NOFILE, %d )", (int)rlim.rlim_cur );
665    }
666#else
667    gFd->socketLimit = socketLimit;
668#endif
669    tr_dbg( "%zu usable file descriptors", socketLimit );
670
671    for( i = 0; i < gFd->openFileLimit; ++i )
672        gFd->openFiles[i].fd = -1;
673}
674
675void
676tr_fdClose( void )
677{
678    int i = 0;
679
680    for( i = 0; i < gFd->openFileLimit; ++i )
681        if( fileIsOpen( &gFd->openFiles[i] ) )
682            TrCloseFile( i );
683
684    tr_lockFree( gFd->lock );
685
686    tr_free( gFd->openFiles );
687    tr_free( gFd );
688    gFd = NULL;
689}
690
691void
692tr_fdSetPeerLimit( uint16_t n )
693{
694    assert( gFd != NULL && "tr_fdInit() must be called first!" );
695    gFd->socketLimit = n;
696}
697
698uint16_t
699tr_fdGetPeerLimit( void )
700{
701    return gFd ? gFd->socketLimit : -1;
702}
703
Note: See TracBrowser for help on using the repository browser.