summaryrefslogtreecommitdiff
path: root/db/mongomutex.h
blob: 08b091cae9cf3ec6c9a40450d9ae42d503c6c2d2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
// @file mongomutex.h

/*
 *    Copyright (C) 2010 10gen Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/* Mutex heirarchy (1 = "leaf")
     name                   level
     Logstream::mutex       1
     ClientCursor::ccmutex  2
     dblock                 3

     End func name with _inlock to indicate "caller must lock before calling".
*/

#pragma once

#include "../util/concurrency/rwlock.h"
#include "../util/mmap.h"
#include "../util/time_support.h"
#include "d_globals.h"

namespace mongo {

    class Client;
    Client* curopWaitingForLock( int type );
    void curopGotLock(Client*);

    /* mongomutex time stats */
    class MutexInfo {
        unsigned long long enter, timeLocked; // microseconds
        int locked;
        unsigned long long start; // last as we touch this least often
    public:
        MutexInfo() : timeLocked(0) , locked(0) {
            start = curTimeMicros64();
        }
        void entered() {
            if ( locked == 0 )
                enter = curTimeMicros64();
            locked++;
            assert( locked >= 1 );
        }
        void leaving() {
            locked--;
            assert( locked >= 0 );
            if ( locked == 0 )
                timeLocked += curTimeMicros64() - enter;
        }
        int isLocked() const { return locked; }
        void getTimingInfo(unsigned long long &s, unsigned long long &tl) const {
            s = start;
            tl = timeLocked;
        }
        unsigned long long getTimeLocked() const { return timeLocked; }
    };

    /** the 'big lock'. a read/write lock.
        there is one of these, d.dbMutex.

        generally if you need to declare a mutex use the right primitive class, not this.

        use readlock and writelock classes for scoped locks on this rather than direct
        manipulation.
       */
    class MongoMutex {
    public:
        MongoMutex(const char * name);

        /** @return
         *    > 0  write lock
         *    = 0  no lock
         *    < 0  read lock
         */
        int getState() const { return _state.get(); }

        bool atLeastReadLocked() const { return _state.get() != 0; }
        void assertAtLeastReadLocked() const { assert(atLeastReadLocked()); }
        bool isWriteLocked/*by our thread*/() const { return getState() > 0; }
        void assertWriteLocked() const {
            assert( getState() > 0 );
            DEV assert( !_releasedEarly.get() );
        }

        // write lock.  use the writelock scoped lock class, not this directly.
        void lock() {
            if ( _writeLockedAlready() )
                return;

            _state.set(1);

            curopWaitingForLock( 1 ); // stats
            _m.lock();
            MongoFile::markAllWritable(); // for _DEBUG validation -- a no op for release build
            _acquiredWriteLock();
        }

        // try write lock
        bool lock_try( int millis ) {
            if ( _writeLockedAlready() ) // adjusts _state
                return true;

            curopWaitingForLock( 1 );
            bool got = _m.lock_try( millis );

            if ( got ) {
                _state.set(1);
                MongoFile::markAllWritable(); // for _DEBUG validation -- a no op for release build
                _acquiredWriteLock();
            }

            return got;
        }

        // un write lock
        void unlock() {
            int s = _state.get();
            if( s > 1 ) {
                _state.set(s-1); // recursive lock case
                return;
            }
            if( s != 1 ) {
                if( _releasedEarly.get() ) {
                    _releasedEarly.set(false);
                    return;
                }
                massert( 12599, "internal error: attempt to unlock when wasn't in a write lock", false);
            }
            _releasingWriteLock();
            MongoFile::unmarkAllWritable(); // _DEBUG validation
            _state.set(0);
            _m.unlock();
        }

        /* unlock (write lock), and when unlock() is called later,
           be smart then and don't unlock it again.
           */
        void releaseEarly() {
            assert( getState() == 1 ); // must not be recursive
            assert( !_releasedEarly.get() );
            _releasedEarly.set(true);
            unlock();
        }

        // read lock. don't call directly, use readlock.
        void lock_shared() {
            int s = _state.get();
            if( s ) {
                if( s > 0 ) {
                    // already in write lock - just be recursive and stay write locked
                    _state.set(s+1);
                }
                else {
                    // already in read lock - recurse
                    _state.set(s-1);
                }
            }
            else {
                _state.set(-1);
                Client *c = curopWaitingForLock( -1 );
                _m.lock_shared();
                curopGotLock(c);
            }
        }

        // try read lock
        bool lock_shared_try( int millis ) {
            int s = _state.get();
            if ( s ) {
                // we already have a lock, so no need to try
                lock_shared();
                return true;
            }

            /* [dm] should there be
                             Client *c = curopWaitingForLock( 1 );
               here?  i think so.  seems to be missing.
               */
            bool got = _m.lock_shared_try( millis );
            if ( got )
                _state.set(-1);
            return got;
        }

        void unlock_shared() {
            int s = _state.get();
            if( s > 0 ) {
                wassert( s > 1 ); /* we must have done a lock write first to have s > 1 */
                _state.set(s-1);
                return;
            }
            if( s < -1 ) {
                _state.set(s+1);
                return;
            }
            wassert( s == -1 );
            _state.set(0);
            _m.unlock_shared();
        }

        MutexInfo& info() { return _minfo; }

    private:
        void lockedExclusively();
        void unlockingExclusively();
        void _acquiredWriteLock();
        void _releasingWriteLock();

        /* @return true if was already write locked.  increments recursive lock count. */
        bool _writeLockedAlready();

        RWLock _m;

        /* > 0 write lock with recurse count
           < 0 read lock
        */
        ThreadLocalValue<int> _state;

        MutexInfo _minfo;

    public:
        // indicates we need to call dur::REMAPPRIVATEVIEW on the next write lock
        bool _remapPrivateViewRequested;

    private:
        /* See the releaseEarly() method.
           we use a separate TLS value for releasedEarly - that is ok as
           our normal/common code path, we never even touch it */
        ThreadLocalValue<bool> _releasedEarly;

        /* this is for fsyncAndLock command.  otherwise write lock's greediness will
           make us block on any attempted write lock the the fsync's lock.
           */
        //volatile bool _blockWrites;
    };

    namespace dur {
        void REMAPPRIVATEVIEW();
        void releasingWriteLock(); // because it's hard to include dur.h here
    }

    inline void MongoMutex::_releasingWriteLock() {
        dur::releasingWriteLock();
        unlockingExclusively();
    }

    inline void MongoMutex::_acquiredWriteLock() {
        lockedExclusively();
        if( _remapPrivateViewRequested ) {
            dur::REMAPPRIVATEVIEW();
            dassert( !_remapPrivateViewRequested );
        }
    }

    string sayClientState();

    /* @return true if was already write locked.  increments recursive lock count. */
    inline bool MongoMutex::_writeLockedAlready() {
        int s = _state.get();
        if( s > 0 ) {
            _state.set(s+1);
            return true;
        }
        massert( 10293 , string("internal error: locks are not upgradeable: ") + sayClientState() , s == 0 );
        return false;
    }

    struct writelock {
        writelock() { d.dbMutex.lock(); }
        writelock(const string& ns) { d.dbMutex.lock(); }
        ~writelock() {
            DESTRUCTOR_GUARD(
                d.dbMutex.unlock();
            );
        }
    };

    struct readlock {
        readlock(const string& ns) {
            d.dbMutex.lock_shared();
        }
        readlock() { d.dbMutex.lock_shared(); }
        ~readlock() {
            DESTRUCTOR_GUARD(
                d.dbMutex.unlock_shared();
            );
        }
    };
    struct readlocktry {
        readlocktry( const string&ns , int tryms ) {
            _got = d.dbMutex.lock_shared_try( tryms );
        }
        ~readlocktry() {
            if ( _got ) {
                d.dbMutex.unlock_shared();
            }
        }
        bool got() const { return _got; }
    private:
        bool _got;
    };

    struct writelocktry {
        writelocktry( const string&ns , int tryms ) {
            _got = d.dbMutex.lock_try( tryms );
        }
        ~writelocktry() {
            if ( _got ) {
                d.dbMutex.unlock();
            }
        }
        bool got() const { return _got; }
    private:
        bool _got;
    };

    struct readlocktryassert : public readlocktry {
        readlocktryassert(const string& ns, int tryms) :
            readlocktry(ns,tryms) {
            uassert(13142, "timeout getting readlock", got());
        }
    };

    /** assure we have at least a read lock - they key with this being
        if you have a write lock, that's ok too.
    */
    struct atleastreadlock {
        atleastreadlock( const string& ns = "" ) {
            _prev = d.dbMutex.getState();
            if ( _prev == 0 )
                d.dbMutex.lock_shared();
        }
        ~atleastreadlock() {
            if ( _prev == 0 )
                d.dbMutex.unlock_shared();
        }
    private:
        int _prev;
    };

    /* parameterized choice of read or write locking
       use readlock and writelock instead of this when statically known which you want
    */
    class mongolock {
        bool _writelock;
    public:
        mongolock(bool write) : _writelock(write) {
            if( _writelock ) {
                d.dbMutex.lock();
            }
            else
                d.dbMutex.lock_shared();
        }
        ~mongolock() {
            DESTRUCTOR_GUARD(
            if( _writelock ) {
                d.dbMutex.unlock();
            }
            else {
                d.dbMutex.unlock_shared();
            }
            );
        }
        /* this unlocks, does NOT upgrade. that works for our current usage */
        //void releaseAndWriteLock();
    };

    /* deprecated - use writelock and readlock instead */
    struct dblock : public writelock {
        dblock() : writelock("") { }
    };

    // eliminate this - we should just type "d.dbMutex.assertWriteLocked();" instead
    inline void assertInWriteLock() { d.dbMutex.assertWriteLocked(); }

}