source: trunk/libtransmission/fdlimit.c @ 7720

Last change on this file since 7720 was 7720, checked in by charles, 13 years ago

(trunk libT) make file preallocation optional via settings.json. choices are: full, sparse, and none

  • Property svn:keywords set to Date Rev Author Id
File size: 14.8 KB
Line 
1/******************************************************************************
2 * $Id: fdlimit.c 7720 2009-01-16 16:38:16Z 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#include <assert.h>
30#include <errno.h>
31#include <inttypes.h>
32#include <stdio.h>
33#include <stdlib.h>
34#include <string.h>
35#ifdef SYS_DARWIN
36 #include <fcntl.h>
37#endif
38
39#ifdef HAVE_FALLOCATE
40 #include <linux/falloc.h>
41#endif
42
43#include <sys/types.h>
44#include <sys/stat.h>
45#ifdef HAVE_GETRLIMIT
46 #include <sys/time.h> /* getrlimit */
47 #include <sys/resource.h> /* getrlimit */
48#endif
49#include <unistd.h>
50#include <fcntl.h> /* O_LARGEFILE */
51
52#include <event.h>
53#include <evutil.h>
54
55#include "transmission.h"
56#include "fdlimit.h"
57#include "list.h"
58#include "net.h"
59#include "platform.h" /* tr_lock */
60#include "utils.h"
61
62#define dbgmsg( ... ) \
63    do { \
64        if( tr_deepLoggingIsActive( ) ) \
65            tr_deepLog( __FILE__, __LINE__, NULL, __VA_ARGS__ ); \
66    } while( 0 )
67
68/**
69***
70**/
71
72enum
73{
74    NOFILE_BUFFER = 512, /* the process' number of open files is
75                            globalMaxPeers + NOFILE_BUFFER */
76};
77
78struct tr_openfile
79{
80    tr_bool    isCheckedOut;
81    tr_bool    isWritable;
82    tr_bool    closeWhenDone;
83    char       filename[MAX_PATH_LENGTH];
84    int        fd;
85    uint64_t   date;
86};
87
88struct tr_fd_s
89{
90    int                   socketCount;
91    int                   socketLimit;
92
93    struct tr_openfile  * openFiles;
94    int                   openFileLimit;
95
96    tr_lock             * lock;
97};
98
99static struct tr_fd_s * gFd = NULL;
100
101/***
102****
103****  Local Files
104****
105***/
106
107#ifndef O_LARGEFILE
108 #define O_LARGEFILE 0
109#endif
110
111static tr_bool
112preallocateFileSparse( int fd, uint64_t length )
113{
114    const char zero = '\0';
115
116    if( length == 0 )
117        return TRUE;
118
119    if( lseek( fd, length-1, SEEK_SET ) == -1 )
120        return FALSE;
121    if( write( fd, &zero, 1 ) == -1 )
122        return FALSE;
123    if( ftruncate( fd, length ) == -1 )
124        return FALSE;
125
126    return TRUE;
127}
128
129static tr_bool
130preallocateFileFull( const char * filename, uint64_t length )
131{
132    tr_bool success = 0;
133
134#ifdef WIN32
135
136    HANDLE hFile = CreateFile( filename, GENERIC_WRITE, 0, 0, CREATE_NEW, 0, 0 );
137    if( hFile != INVALID_HANDLE_VALUE )
138    {
139        LARGE_INTEGER li;
140        li.QuadPart = length;
141        success = SetFilePointerEx( hFile, li, NULL, FILE_BEGIN ) && SetEndOfFile( hFile );
142        CloseHandle( hFile );
143    }
144
145#else
146
147    int flags = O_RDWR | O_CREAT | O_LARGEFILE;
148    int fd = open( filename, flags, 0666 );
149    if( fd >= 0 )
150    {
151       
152# ifdef HAVE_FALLOCATE
153
154        success = !fallocate( fd, FALLOC_FL_KEEP_SIZE, 0, length );
155
156# elif defined(HAVE_POSIX_FALLOCATE)
157
158        success = !posix_fallocate( fd, 0, length );
159
160# elif defined(SYS_DARWIN)
161
162        fstore_t fst;
163        fst.fst_flags = F_ALLOCATECONTIG;
164        fst.fst_posmode = F_PEOFPOSMODE;
165        fst.fst_offset = 0;
166        fst.fst_length = length;
167        fst.fst_bytesalloc = 0;
168        success = !fcntl( fd, F_PREALLOCATE, &fst );
169
170# else
171
172        #warning no known method to preallocate files on this platform
173        success = 0;
174
175# endif
176
177        close( fd );
178    }
179
180#endif
181
182    return success;
183}
184
185/**
186 * returns 0 on success, or an errno value on failure.
187 * errno values include ENOENT if the parent folder doesn't exist,
188 * plus the errno values set by tr_mkdirp() and open().
189 */
190static int
191TrOpenFile( int                      i,
192            const char             * folder,
193            const char             * torrentFile,
194            tr_bool                  doWrite,
195            tr_preallocation_mode    preallocationMode,
196            uint64_t                 desiredFileSize )
197{
198    struct tr_openfile * file = &gFd->openFiles[i];
199    int                  flags;
200    char               * filename;
201    struct stat          sb;
202    int                  alreadyExisted;
203
204    /* confirm the parent folder exists */
205    if( stat( folder, &sb ) || !S_ISDIR( sb.st_mode ) )
206        return ENOENT;
207
208    /* create subfolders, if any */
209    filename = tr_buildPath( folder, torrentFile, NULL );
210    if( doWrite )
211    {
212        char * tmp = tr_dirname( filename );
213        const int err = tr_mkdirp( tmp, 0777 ) ? errno : 0;
214        tr_free( tmp );
215        if( err ) {
216            tr_free( filename );
217            return err;
218        }
219    }
220
221    alreadyExisted = !stat( filename, &sb ) && S_ISREG( sb.st_mode );
222
223    if( doWrite && !alreadyExisted && ( preallocationMode == TR_PREALLOCATE_FULL ) )
224        if( preallocateFileFull( filename, desiredFileSize ) )
225            tr_inf( _( "Preallocated file \"%s\"" ), filename );
226   
227    /* open the file */
228    flags = doWrite ? ( O_RDWR | O_CREAT ) : O_RDONLY;
229#ifdef O_LARGEFILE
230    flags |= O_LARGEFILE;
231#endif
232#ifdef WIN32
233    flags |= O_BINARY;
234#endif
235    file->fd = open( filename, flags, 0666 );
236    if( file->fd == -1 )
237    {
238        const int err = errno;
239        tr_err( _( "Couldn't open \"%1$s\": %2$s" ), filename,
240               tr_strerror( err ) );
241        tr_free( filename );
242        return err;
243    }
244
245    if( doWrite && !alreadyExisted && ( preallocationMode == TR_PREALLOCATE_SPARSE ) )
246        preallocateFileSparse( file->fd, desiredFileSize );
247
248    tr_free( filename );
249    return 0;
250}
251
252static int
253fileIsOpen( const struct tr_openfile * o )
254{
255    return o->fd >= 0;
256}
257
258static void
259TrCloseFile( int i )
260{
261    struct tr_openfile * o = &gFd->openFiles[i];
262
263    assert( i >= 0 );
264    assert( i < gFd->openFileLimit );
265    assert( fileIsOpen( o ) );
266
267    close( o->fd );
268    o->fd = -1;
269    o->isCheckedOut = 0;
270}
271
272static int
273fileIsCheckedOut( const struct tr_openfile * o )
274{
275    return fileIsOpen( o ) && o->isCheckedOut;
276}
277
278/* returns an fd on success, or a -1 on failure and sets errno */
279int
280tr_fdFileCheckout( const char             * folder,
281                   const char             * torrentFile,
282                   tr_bool                  doWrite,
283                   tr_preallocation_mode    preallocationMode,
284                   uint64_t                 desiredFileSize )
285{
286    int i, winner = -1;
287    struct tr_openfile * o;
288    char filename[MAX_PATH_LENGTH];
289
290    assert( folder && *folder );
291    assert( torrentFile && *torrentFile );
292    assert( doWrite == 0 || doWrite == 1 );
293
294    tr_snprintf( filename, sizeof( filename ), "%s%c%s", folder, TR_PATH_DELIMITER, torrentFile );
295    dbgmsg( "looking for file '%s', writable %c", filename, doWrite ? 'y' : 'n' );
296
297    tr_lockLock( gFd->lock );
298
299    /* Is it already open? */
300    for( i = 0; i < gFd->openFileLimit; ++i )
301    {
302        o = &gFd->openFiles[i];
303
304        if( !fileIsOpen( o ) )
305            continue;
306
307        if( strcmp( filename, o->filename ) )
308            continue;
309
310        if( fileIsCheckedOut( o ) )
311        {
312            dbgmsg( "found it!  it's open, but checked out.  waiting..." );
313            tr_lockUnlock( gFd->lock );
314            tr_wait( 200 );
315            tr_lockLock( gFd->lock );
316            i = -1; /* reloop */
317            continue;
318        }
319
320        if( doWrite && !o->isWritable )
321        {
322            dbgmsg(
323                "found it!  it's open and available, but isn't writable. closing..." );
324            TrCloseFile( i );
325            break;
326        }
327
328        dbgmsg( "found it!  it's ready for use!" );
329        winner = i;
330        break;
331    }
332
333    dbgmsg(
334        "it's not already open.  looking for an open slot or an old file." );
335    while( winner < 0 )
336    {
337        uint64_t date = tr_date( ) + 1;
338
339        /* look for the file that's been open longest */
340        for( i = 0; i < gFd->openFileLimit; ++i )
341        {
342            o = &gFd->openFiles[i];
343
344            if( !fileIsOpen( o ) )
345            {
346                winner = i;
347                dbgmsg( "found an empty slot in %d", winner );
348                break;
349            }
350
351            if( date > o->date )
352            {
353                date = o->date;
354                winner = i;
355            }
356        }
357
358        if( winner >= 0 )
359        {
360            if( fileIsOpen( &gFd->openFiles[winner] ) )
361            {
362                dbgmsg( "closing file '%s', slot #%d",
363                        gFd->openFiles[winner].filename,
364                        winner );
365                TrCloseFile( winner );
366            }
367        }
368        else
369        {
370            dbgmsg(
371                "everything's full!  waiting for someone else to finish something" );
372            tr_lockUnlock( gFd->lock );
373            tr_wait( 200 );
374            tr_lockLock( gFd->lock );
375        }
376    }
377
378    assert( winner >= 0 );
379    o = &gFd->openFiles[winner];
380    if( !fileIsOpen( o ) )
381    {
382        const int err = TrOpenFile( winner, folder, torrentFile, doWrite, preallocationMode, desiredFileSize );
383        if( err ) {
384            tr_lockUnlock( gFd->lock );
385            errno = err;
386            return -1;
387        }
388
389        dbgmsg( "opened '%s' in slot %d, doWrite %c", filename, winner,
390                doWrite ? 'y' : 'n' );
391        tr_strlcpy( o->filename, filename, sizeof( o->filename ) );
392        o->isWritable = doWrite;
393    }
394
395    dbgmsg( "checking out '%s' in slot %d", filename, winner );
396    o->isCheckedOut = 1;
397    o->closeWhenDone = 0;
398    o->date = tr_date( );
399    tr_lockUnlock( gFd->lock );
400    return o->fd;
401}
402
403void
404tr_fdFileReturn( int fd )
405{
406    int i;
407
408    tr_lockLock( gFd->lock );
409
410    for( i = 0; i < gFd->openFileLimit; ++i )
411    {
412        struct tr_openfile * o = &gFd->openFiles[i];
413        if( o->fd != fd )
414            continue;
415
416        dbgmsg( "releasing file '%s' in slot #%d", o->filename, i );
417        o->isCheckedOut = 0;
418        if( o->closeWhenDone )
419            TrCloseFile( i );
420
421        break;
422    }
423
424    tr_lockUnlock( gFd->lock );
425}
426
427void
428tr_fdFileClose( const char * filename )
429{
430    int i;
431
432    tr_lockLock( gFd->lock );
433
434    for( i = 0; i < gFd->openFileLimit; ++i )
435    {
436        struct tr_openfile * o = &gFd->openFiles[i];
437        if( !fileIsOpen( o ) || strcmp( filename, o->filename ) )
438            continue;
439
440        dbgmsg( "tr_fdFileClose closing '%s'", filename );
441
442        if( !o->isCheckedOut )
443        {
444            dbgmsg( "not checked out, so closing it now... '%s'", filename );
445            TrCloseFile( i );
446        }
447        else
448        {
449            dbgmsg(
450                "flagging file '%s', slot #%d to be closed when checked in",
451                gFd->openFiles[i].filename, i );
452            o->closeWhenDone = 1;
453        }
454    }
455
456    tr_lockUnlock( gFd->lock );
457}
458
459/***
460****
461****  Sockets
462****
463***/
464
465static int
466getSocketMax( struct tr_fd_s * gFd )
467{
468    return gFd->socketLimit;
469}
470
471int
472tr_fdSocketCreate( int domain, int type )
473{
474    int s = -1;
475
476    tr_lockLock( gFd->lock );
477
478    if( gFd->socketCount < getSocketMax( gFd ) )
479        if( ( s = socket( domain, type, 0 ) ) < 0 )
480        {
481#ifdef SYS_DARWIN
482            if( sockerrno != EAFNOSUPPORT )
483#endif
484            tr_err( _( "Couldn't create socket: %s" ),
485                   tr_strerror( sockerrno ) );
486            s = -sockerrno;
487        }
488
489    if( s > -1 )
490        ++gFd->socketCount;
491
492    assert( gFd->socketCount >= 0 );
493
494    tr_lockUnlock( gFd->lock );
495    return s;
496}
497
498int
499tr_fdSocketAccept( int           b,
500                   tr_address  * addr,
501                   tr_port     * port )
502{
503    int                s = -1;
504    unsigned int       len;
505    struct sockaddr_storage sock;
506
507    assert( addr );
508    assert( port );
509
510    tr_lockLock( gFd->lock );
511    if( gFd->socketCount < getSocketMax( gFd ) )
512    {
513        len = sizeof( struct sockaddr_storage );
514        s = accept( b, (struct sockaddr *) &sock, &len );
515    }
516    if( s > -1 )
517    {
518        /* "The ss_family field of the sockaddr_storage structure will always
519         * align with the family field of any protocol-specific structure." */ 
520        if( sock.ss_family == AF_INET ) 
521        { 
522            struct sockaddr_in * sock4 = (struct sockaddr_in *)&sock; 
523            addr->type = TR_AF_INET; 
524            addr->addr.addr4.s_addr = sock4->sin_addr.s_addr; 
525            *port = sock4->sin_port; 
526        } 
527        else 
528        { 
529            struct sockaddr_in6 * sock6 = (struct sockaddr_in6 *)&sock; 
530            addr->type = TR_AF_INET6; 
531            addr->addr.addr6 = sock6->sin6_addr;
532            *port = sock6->sin6_port; 
533        } 
534        ++gFd->socketCount;
535    }
536    tr_lockUnlock( gFd->lock );
537
538    return s;
539}
540
541static void
542socketClose( int fd )
543{
544    EVUTIL_CLOSESOCKET( fd );
545}
546
547void
548tr_fdSocketClose( int s )
549{
550    tr_lockLock( gFd->lock );
551
552    if( s >= 0 )
553    {
554        socketClose( s );
555        --gFd->socketCount;
556    }
557
558    assert( gFd->socketCount >= 0 );
559
560    tr_lockUnlock( gFd->lock );
561}
562
563/***
564****
565****  Startup / Shutdown
566****
567***/
568
569void
570tr_fdInit( size_t openFileLimit, size_t socketLimit )
571{
572    int i;
573
574    assert( gFd == NULL );
575    gFd = tr_new0( struct tr_fd_s, 1 );
576    gFd->openFiles = tr_new0( struct tr_openfile, openFileLimit );
577    gFd->openFileLimit = openFileLimit;
578    gFd->lock = tr_lockNew( );
579
580#ifdef HAVE_GETRLIMIT
581    {
582        struct rlimit rlim;
583        getrlimit( RLIMIT_NOFILE, &rlim );
584        rlim.rlim_cur = MIN( rlim.rlim_max,
585                            (rlim_t)( socketLimit + NOFILE_BUFFER ) );
586        setrlimit( RLIMIT_NOFILE, &rlim );
587        gFd->socketLimit = rlim.rlim_cur - NOFILE_BUFFER;
588        tr_dbg( "setrlimit( RLIMIT_NOFILE, %d )", (int)rlim.rlim_cur );
589    }
590#else
591    gFd->socketLimit = socketLimit;
592#endif
593    tr_dbg( "%zu usable file descriptors", socketLimit );
594
595    for( i = 0; i < gFd->openFileLimit; ++i )
596        gFd->openFiles[i].fd = -1;
597}
598
599void
600tr_fdClose( void )
601{
602    int i = 0;
603
604    for( i = 0; i < gFd->openFileLimit; ++i )
605        if( fileIsOpen( &gFd->openFiles[i] ) )
606            TrCloseFile( i );
607
608    tr_lockFree( gFd->lock );
609
610    tr_free( gFd );
611    gFd = NULL;
612}
613
614void
615tr_fdSetPeerLimit( uint16_t n )
616{
617    assert( gFd != NULL && "tr_fdInit() must be called first!" );
618    gFd->socketLimit = n;
619}
620
621uint16_t
622tr_fdGetPeerLimit( void )
623{
624    return gFd ? gFd->socketLimit : -1;
625}
626
Note: See TracBrowser for help on using the repository browser.