source: trunk/libtransmission/fdlimit.c @ 8343

Last change on this file since 8343 was 8343, checked in by charles, 14 years ago

(trunk libT) remove some oddness in tr_open_file_for_scanning()

  • Property svn:keywords set to Date Rev Author Id
File size: 16.4 KB
Line 
1/******************************************************************************
2 * $Id: fdlimit.c 8343 2009-05-06 13:33:40Z 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    flags |= O_SEQUENTIAL;
214#endif
215#ifdef O_BINARY
216    flags |= O_BINARY;
217#endif
218#ifdef O_LARGEFILE
219    flags |= O_LARGEFILE;
220#endif
221
222    /* open the file */
223    fd = open( filename, flags, 0666 );
224    if( fd >= 0 )
225    {
226#ifdef HAVE_POSIX_FADVISE
227        posix_fadvise( fd, 0, 0, POSIX_FADV_SEQUENTIAL );
228#endif
229#ifdef SYS_DARWIN
230        fcntl( fd, F_NOCACHE, 1 );
231        fcntl( fd, F_RDAHEAD, 1 );
232#endif
233    }
234
235    return fd;
236}
237
238void
239tr_close_file( int fd )
240{
241#if defined(HAVE_POSIX_FADVISE)
242    posix_fadvise( fd, 0, 0, POSIX_FADV_DONTNEED );
243#endif
244    close( fd );
245}
246
247/**
248 * returns 0 on success, or an errno value on failure.
249 * errno values include ENOENT if the parent folder doesn't exist,
250 * plus the errno values set by tr_mkdirp() and open().
251 */
252static int
253TrOpenFile( int                      i,
254            const char             * folder,
255            const char             * torrentFile,
256            tr_bool                  doWrite,
257            tr_preallocation_mode    preallocationMode,
258            uint64_t                 desiredFileSize )
259{
260    struct tr_openfile * file = &gFd->openFiles[i];
261    int                  flags;
262    char               * filename;
263    struct stat          sb;
264    int                  alreadyExisted;
265
266    /* confirm the parent folder exists */
267    if( stat( folder, &sb ) || !S_ISDIR( sb.st_mode ) )
268    {
269        tr_err( _( "Couldn't create \"%1$s\": parent folder \"%2$s\" does not exist" ), torrentFile, folder );
270        return ENOENT;
271    }
272
273    /* create subfolders, if any */
274    filename = tr_buildPath( folder, torrentFile, NULL );
275    if( doWrite )
276    {
277        char * tmp = tr_dirname( filename );
278        const int err = tr_mkdirp( tmp, 0777 ) ? errno : 0;
279        if( err ) {
280            tr_err( _( "Couldn't create \"%1$s\": %2$s" ), tmp, tr_strerror( err ) );
281            tr_free( tmp );
282            tr_free( filename );
283            return err;
284        }
285        tr_free( tmp );
286    }
287
288    alreadyExisted = !stat( filename, &sb ) && S_ISREG( sb.st_mode );
289
290    if( doWrite && !alreadyExisted && ( preallocationMode == TR_PREALLOCATE_FULL ) )
291        if( preallocateFileFull( filename, desiredFileSize ) )
292            tr_inf( _( "Preallocated file \"%s\"" ), filename );
293   
294    /* open the file */
295    flags = doWrite ? ( O_RDWR | O_CREAT ) : O_RDONLY;
296#ifdef O_RANDOM
297    flags |= O_RANDOM
298#endif
299#ifdef O_LARGEFILE
300    flags |= O_LARGEFILE;
301#endif
302#ifdef WIN32
303    flags |= O_BINARY;
304#endif
305    file->fd = open( filename, flags, 0666 );
306    if( file->fd == -1 )
307    {
308        const int err = errno;
309        tr_err( _( "Couldn't open \"%1$s\": %2$s" ), filename, tr_strerror( err ) );
310        tr_free( filename );
311        return err;
312    }
313
314    if( doWrite && !alreadyExisted && ( preallocationMode == TR_PREALLOCATE_SPARSE ) )
315        preallocateFileSparse( file->fd, desiredFileSize );
316
317#ifdef HAVE_POSIX_FADVISE
318    posix_fadvise( file->fd, 0, 0, POSIX_FADV_RANDOM );
319#endif
320
321    tr_free( filename );
322    return 0;
323}
324
325static int
326fileIsOpen( const struct tr_openfile * o )
327{
328    return o->fd >= 0;
329}
330
331static void
332TrCloseFile( int i )
333{
334    struct tr_openfile * o = &gFd->openFiles[i];
335
336    assert( i >= 0 );
337    assert( i < gFd->openFileLimit );
338    assert( fileIsOpen( o ) );
339
340    tr_close_file( o->fd );
341    o->fd = -1;
342    o->isCheckedOut = 0;
343}
344
345static int
346fileIsCheckedOut( const struct tr_openfile * o )
347{
348    return fileIsOpen( o ) && o->isCheckedOut;
349}
350
351/* returns an fd on success, or a -1 on failure and sets errno */
352int
353tr_fdFileCheckout( const char             * folder,
354                   const char             * torrentFile,
355                   tr_bool                  doWrite,
356                   tr_preallocation_mode    preallocationMode,
357                   uint64_t                 desiredFileSize )
358{
359    int i, winner = -1;
360    struct tr_openfile * o;
361    char filename[MAX_PATH_LENGTH];
362
363    assert( folder && *folder );
364    assert( torrentFile && *torrentFile );
365    assert( doWrite == 0 || doWrite == 1 );
366
367    tr_snprintf( filename, sizeof( filename ), "%s%c%s", folder, TR_PATH_DELIMITER, torrentFile );
368    dbgmsg( "looking for file '%s', writable %c", filename, doWrite ? 'y' : 'n' );
369
370    tr_lockLock( gFd->lock );
371
372    /* Is it already open? */
373    for( i = 0; i < gFd->openFileLimit; ++i )
374    {
375        o = &gFd->openFiles[i];
376
377        if( !fileIsOpen( o ) )
378            continue;
379
380        if( strcmp( filename, o->filename ) )
381            continue;
382
383        if( fileIsCheckedOut( o ) )
384        {
385            dbgmsg( "found it!  it's open, but checked out.  waiting..." );
386            tr_lockUnlock( gFd->lock );
387            tr_wait( 200 );
388            tr_lockLock( gFd->lock );
389            i = -1; /* reloop */
390            continue;
391        }
392
393        if( doWrite && !o->isWritable )
394        {
395            dbgmsg(
396                "found it!  it's open and available, but isn't writable. closing..." );
397            TrCloseFile( i );
398            break;
399        }
400
401        dbgmsg( "found it!  it's ready for use!" );
402        winner = i;
403        break;
404    }
405
406    dbgmsg(
407        "it's not already open.  looking for an open slot or an old file." );
408    while( winner < 0 )
409    {
410        uint64_t date = tr_date( ) + 1;
411
412        /* look for the file that's been open longest */
413        for( i = 0; i < gFd->openFileLimit; ++i )
414        {
415            o = &gFd->openFiles[i];
416
417            if( !fileIsOpen( o ) )
418            {
419                winner = i;
420                dbgmsg( "found an empty slot in %d", winner );
421                break;
422            }
423
424            if( date > o->date )
425            {
426                date = o->date;
427                winner = i;
428            }
429        }
430
431        if( winner >= 0 )
432        {
433            if( fileIsOpen( &gFd->openFiles[winner] ) )
434            {
435                dbgmsg( "closing file '%s', slot #%d",
436                        gFd->openFiles[winner].filename,
437                        winner );
438                TrCloseFile( winner );
439            }
440        }
441        else
442        {
443            dbgmsg( "everything's full!  waiting for someone else to finish something" );
444            tr_lockUnlock( gFd->lock );
445            tr_wait( 200 );
446            tr_lockLock( gFd->lock );
447        }
448    }
449
450    assert( winner >= 0 );
451    o = &gFd->openFiles[winner];
452    if( !fileIsOpen( o ) )
453    {
454        const int err = TrOpenFile( winner, folder, torrentFile, doWrite, preallocationMode, desiredFileSize );
455        if( err ) {
456            tr_lockUnlock( gFd->lock );
457            errno = err;
458            return -1;
459        }
460
461        dbgmsg( "opened '%s' in slot %d, doWrite %c", filename, winner,
462                doWrite ? 'y' : 'n' );
463        tr_strlcpy( o->filename, filename, sizeof( o->filename ) );
464        o->isWritable = doWrite;
465    }
466
467    dbgmsg( "checking out '%s' in slot %d", filename, winner );
468    o->isCheckedOut = 1;
469    o->closeWhenDone = 0;
470    o->date = tr_date( );
471    tr_lockUnlock( gFd->lock );
472    return o->fd;
473}
474
475void
476tr_fdFileReturn( int fd )
477{
478    int i;
479
480    tr_lockLock( gFd->lock );
481
482    for( i = 0; i < gFd->openFileLimit; ++i )
483    {
484        struct tr_openfile * o = &gFd->openFiles[i];
485        if( o->fd != fd )
486            continue;
487
488        dbgmsg( "releasing file '%s' in slot #%d", o->filename, i );
489        o->isCheckedOut = 0;
490        if( o->closeWhenDone )
491            TrCloseFile( i );
492
493        break;
494    }
495
496    tr_lockUnlock( gFd->lock );
497}
498
499void
500tr_fdFileClose( const char * filename )
501{
502    int i;
503
504    tr_lockLock( gFd->lock );
505
506    for( i = 0; i < gFd->openFileLimit; ++i )
507    {
508        struct tr_openfile * o = &gFd->openFiles[i];
509        if( !fileIsOpen( o ) || strcmp( filename, o->filename ) )
510            continue;
511
512        dbgmsg( "tr_fdFileClose closing '%s'", filename );
513
514        if( !o->isCheckedOut )
515        {
516            dbgmsg( "not checked out, so closing it now... '%s'", filename );
517            TrCloseFile( i );
518        }
519        else
520        {
521            dbgmsg(
522                "flagging file '%s', slot #%d to be closed when checked in",
523                gFd->openFiles[i].filename, i );
524            o->closeWhenDone = 1;
525        }
526    }
527
528    tr_lockUnlock( gFd->lock );
529}
530
531/***
532****
533****  Sockets
534****
535***/
536
537static int
538getSocketMax( struct tr_fd_s * gFd )
539{
540    return gFd->socketLimit;
541}
542
543int
544tr_fdSocketCreate( int domain, int type )
545{
546    int s = -1;
547
548    tr_lockLock( gFd->lock );
549
550    if( gFd->socketCount < getSocketMax( gFd ) )
551        if( ( s = socket( domain, type, 0 ) ) < 0 )
552        {
553#ifdef SYS_DARWIN
554            if( sockerrno != EAFNOSUPPORT )
555#endif
556            tr_err( _( "Couldn't create socket: %s" ),
557                   tr_strerror( sockerrno ) );
558            s = -sockerrno;
559        }
560
561    if( s > -1 )
562        ++gFd->socketCount;
563
564    assert( gFd->socketCount >= 0 );
565
566    tr_lockUnlock( gFd->lock );
567    return s;
568}
569
570int
571tr_fdSocketAccept( int           b,
572                   tr_address  * addr,
573                   tr_port     * port )
574{
575    int                s = -1;
576    unsigned int       len;
577    struct sockaddr_storage sock;
578
579    assert( addr );
580    assert( port );
581
582    tr_lockLock( gFd->lock );
583    if( gFd->socketCount < getSocketMax( gFd ) )
584    {
585        len = sizeof( struct sockaddr_storage );
586        s = accept( b, (struct sockaddr *) &sock, &len );
587    }
588    if( s > -1 )
589    {
590        /* "The ss_family field of the sockaddr_storage structure will always
591         * align with the family field of any protocol-specific structure." */ 
592        if( sock.ss_family == AF_INET ) 
593        { 
594            struct sockaddr_in * sock4 = (struct sockaddr_in *)&sock; 
595            addr->type = TR_AF_INET; 
596            addr->addr.addr4.s_addr = sock4->sin_addr.s_addr; 
597            *port = sock4->sin_port; 
598        } 
599        else 
600        { 
601            struct sockaddr_in6 * sock6 = (struct sockaddr_in6 *)&sock; 
602            addr->type = TR_AF_INET6; 
603            addr->addr.addr6 = sock6->sin6_addr;
604            *port = sock6->sin6_port; 
605        } 
606        ++gFd->socketCount;
607    }
608    tr_lockUnlock( gFd->lock );
609
610    return s;
611}
612
613static void
614socketClose( int fd )
615{
616    EVUTIL_CLOSESOCKET( fd );
617}
618
619void
620tr_fdSocketClose( int s )
621{
622    tr_lockLock( gFd->lock );
623
624    if( s >= 0 )
625    {
626        socketClose( s );
627        --gFd->socketCount;
628    }
629
630    assert( gFd->socketCount >= 0 );
631
632    tr_lockUnlock( gFd->lock );
633}
634
635/***
636****
637****  Startup / Shutdown
638****
639***/
640
641void
642tr_fdInit( size_t openFileLimit, size_t socketLimit )
643{
644    int i;
645
646    assert( gFd == NULL );
647    gFd = tr_new0( struct tr_fd_s, 1 );
648    gFd->openFiles = tr_new0( struct tr_openfile, openFileLimit );
649    gFd->openFileLimit = openFileLimit;
650    gFd->lock = tr_lockNew( );
651
652#ifdef HAVE_GETRLIMIT
653    {
654        struct rlimit rlim;
655        getrlimit( RLIMIT_NOFILE, &rlim );
656        rlim.rlim_cur = MIN( rlim.rlim_max,
657                            (rlim_t)( socketLimit + NOFILE_BUFFER ) );
658        setrlimit( RLIMIT_NOFILE, &rlim );
659        gFd->socketLimit = rlim.rlim_cur - NOFILE_BUFFER;
660        tr_dbg( "setrlimit( RLIMIT_NOFILE, %d )", (int)rlim.rlim_cur );
661    }
662#else
663    gFd->socketLimit = socketLimit;
664#endif
665    tr_dbg( "%zu usable file descriptors", socketLimit );
666
667    for( i = 0; i < gFd->openFileLimit; ++i )
668        gFd->openFiles[i].fd = -1;
669}
670
671void
672tr_fdClose( void )
673{
674    int i = 0;
675
676    for( i = 0; i < gFd->openFileLimit; ++i )
677        if( fileIsOpen( &gFd->openFiles[i] ) )
678            TrCloseFile( i );
679
680    tr_lockFree( gFd->lock );
681
682    tr_free( gFd->openFiles );
683    tr_free( gFd );
684    gFd = NULL;
685}
686
687void
688tr_fdSetPeerLimit( uint16_t n )
689{
690    assert( gFd != NULL && "tr_fdInit() must be called first!" );
691    gFd->socketLimit = n;
692}
693
694uint16_t
695tr_fdGetPeerLimit( void )
696{
697    return gFd ? gFd->socketLimit : -1;
698}
699
Note: See TracBrowser for help on using the repository browser.