summaryrefslogtreecommitdiff
path: root/src/mongo/db/storage/mmap_v1/mmap_windows.cpp
blob: 88abedd9c77d903e39061e9e53b22f71fa566e29 (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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
// mmap_win.cpp

/*    Copyright 2009 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/>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the GNU Affero General Public License in all respects
 *    for all of the code used other than as permitted herein. If you modify
 *    file(s) with this exception, you may extend this exception to your
 *    version of the file(s), but you are not obligated to do so. If you do not
 *    wish to do so, delete this exception statement from your version. If you
 *    delete this exception statement from all source files in the program,
 *    then also delete it in the license file.
 */

#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kControl

#include "mongo/platform/basic.h"

#include "mongo/db/storage/mmap_v1/mmap.h"

#include "mongo/db/storage/mmap_v1/durable_mapped_file.h"
#include "mongo/db/storage/mmap_v1/file_allocator.h"
#include "mongo/stdx/mutex.h"
#include "mongo/util/log.h"
#include "mongo/util/processinfo.h"
#include "mongo/util/text.h"
#include "mongo/util/timer.h"

namespace mongo {

using std::endl;
using std::string;
using std::vector;

namespace {
mongo::AtomicUInt64 mmfNextId(0);
}

static size_t fetchMinOSPageSizeBytes() {
    SYSTEM_INFO si;
    GetSystemInfo(&si);
    size_t minOSPageSizeBytes = si.dwPageSize;
    minOSPageSizeBytesTest(minOSPageSizeBytes);
    return minOSPageSizeBytes;
}
const size_t g_minOSPageSizeBytes = fetchMinOSPageSizeBytes();

// MapViewMutex
//
// Protects:
//   1. Ensures all MapViewOfFile/UnMapViewOfFile operations are serialized to reduce chance of
//    "address in use" errors (error code 487)
// -   These errors can still occur if the memory is used for other purposes
//     (stack storage, heap)
//   2. Prevents calls to VirtualProtect while we remapping files.
// Lock Ordering:
//  - If taken, must be after previewViews._m to prevent deadlocks
stdx::mutex mapViewMutex;

MAdvise::MAdvise(void*, unsigned, Advice) {}
MAdvise::~MAdvise() {}

const unsigned long long memoryMappedFileLocationFloor = 256LL * 1024LL * 1024LL * 1024LL;
static unsigned long long _nextMemoryMappedFileLocation = memoryMappedFileLocationFloor;

// nextMemoryMappedFileLocationMutex
//
// Protects:
//  Windows 64-bit specific allocation of virtual memory regions for
//  placing memory mapped files in memory
// Lock Ordering:
//  No restrictions
static SimpleMutex _nextMemoryMappedFileLocationMutex;

unsigned long long AlignNumber(unsigned long long number, unsigned long long granularity) {
    return (number + granularity - 1) & ~(granularity - 1);
}

static void* getNextMemoryMappedFileLocation(unsigned long long mmfSize) {
    if (4 == sizeof(void*)) {
        return 0;
    }
    stdx::lock_guard<SimpleMutex> lk(_nextMemoryMappedFileLocationMutex);

    static unsigned long long granularity = 0;

    if (0 == granularity) {
        SYSTEM_INFO systemInfo;
        GetSystemInfo(&systemInfo);
        granularity = static_cast<unsigned long long>(systemInfo.dwAllocationGranularity);
    }

    unsigned long long thisMemoryMappedFileLocation = _nextMemoryMappedFileLocation;

    int current_retry = 1;

    while (true) {
        MEMORY_BASIC_INFORMATION memInfo;

        if (VirtualQuery(reinterpret_cast<LPCVOID>(thisMemoryMappedFileLocation),
                         &memInfo,
                         sizeof(memInfo)) == 0) {
            DWORD gle = GetLastError();

            // If we exceed the limits of Virtual Memory
            // - 8TB before Windows 8.1/2012 R2, 128 TB after
            // restart scanning from our memory mapped floor once more
            // This is a linear scan of regions, not of every VM page
            if (gle == ERROR_INVALID_PARAMETER && current_retry == 1) {
                thisMemoryMappedFileLocation = memoryMappedFileLocationFloor;
                ++current_retry;
                continue;
            }

            log() << "VirtualQuery of " << thisMemoryMappedFileLocation << " failed with error "
                  << errnoWithDescription(gle);
            fassertFailed(17484);
        }

        // Free memory regions that we can use for memory map files
        // 1. Marked MEM_FREE, not MEM_RESERVE
        // 2. Marked as PAGE_NOACCESS, not anything else
        if (memInfo.Protect == PAGE_NOACCESS && memInfo.State == MEM_FREE &&
            memInfo.RegionSize > mmfSize)
            break;

        thisMemoryMappedFileLocation =
            reinterpret_cast<unsigned long long>(memInfo.BaseAddress) + memInfo.RegionSize;
    }

    _nextMemoryMappedFileLocation =
        thisMemoryMappedFileLocation + AlignNumber(mmfSize, granularity);

    return reinterpret_cast<void*>(static_cast<uintptr_t>(thisMemoryMappedFileLocation));
}

MemoryMappedFile::MemoryMappedFile()
    : _uniqueId(mmfNextId.fetchAndAdd(1)), fd(0), maphandle(0), len(0) {
    created();
}

void MemoryMappedFile::close() {
    LockMongoFilesShared::assertExclusivelyLocked();

    // Prevent flush and close from concurrently running
    stdx::lock_guard<stdx::mutex> lk(_flushMutex);

    {
        stdx::lock_guard<stdx::mutex> lk(mapViewMutex);

        for (vector<void*>::iterator i = views.begin(); i != views.end(); i++) {
            UnmapViewOfFile(*i);
        }
    }

    views.clear();
    if (maphandle)
        CloseHandle(maphandle);
    maphandle = 0;
    if (fd)
        CloseHandle(fd);
    fd = 0;
    destroyed();  // cleans up from the master list of mmaps
}

unsigned long long mapped = 0;

void* MemoryMappedFile::createReadOnlyMap() {
    verify(maphandle);

    stdx::lock_guard<stdx::mutex> lk(mapViewMutex);

    void* readOnlyMapAddress = NULL;
    int current_retry = 0;

    while (true) {
        LPVOID thisAddress = getNextMemoryMappedFileLocation(len);

        readOnlyMapAddress = MapViewOfFileEx(maphandle,      // file mapping handle
                                             FILE_MAP_READ,  // access
                                             0,
                                             0,             // file offset, high and low
                                             0,             // bytes to map, 0 == all
                                             thisAddress);  // address to place file

        if (0 == readOnlyMapAddress) {
            DWORD dosError = GetLastError();

            ++current_retry;

            // If we failed to allocate a memory mapped file, try again in case we picked
            // an address that Windows is also trying to use for some other VM allocations
            if (dosError == ERROR_INVALID_ADDRESS && current_retry < 5) {
                continue;
            }

            log() << "MapViewOfFileEx for " << filename() << " at address " << thisAddress
                  << " failed with error " << errnoWithDescription(dosError) << " (file size is "
                  << len << ")"
                  << " in MemoryMappedFile::createReadOnlyMap" << endl;

            fassertFailed(16165);
        }

        break;
    }

    views.push_back(readOnlyMapAddress);
    return readOnlyMapAddress;
}

void* MemoryMappedFile::map(const char* filenameIn, unsigned long long& length, int options) {
    verify(fd == 0 && len == 0);  // can't open more than once
    setFilename(filenameIn);
    FileAllocator::get()->allocateAsap(filenameIn, length);
    /* big hack here: Babble uses db names with colons.  doesn't seem to work on windows.  temporary perhaps. */
    char filename[256];
    strncpy(filename, filenameIn, 255);
    filename[255] = 0;
    {
        size_t len = strlen(filename);
        for (size_t i = len - 1; i >= 0; i--) {
            if (filename[i] == '/' || filename[i] == '\\')
                break;

            if (filename[i] == ':')
                filename[i] = '_';
        }
    }

    updateLength(filename, length);

    {
        DWORD createOptions = FILE_ATTRIBUTE_NORMAL;
        if (options & SEQUENTIAL)
            createOptions |= FILE_FLAG_SEQUENTIAL_SCAN;
        DWORD rw = GENERIC_READ | GENERIC_WRITE;
        fd = CreateFileW(toWideString(filename).c_str(),
                         rw,                                  // desired access
                         FILE_SHARE_WRITE | FILE_SHARE_READ,  // share mode
                         NULL,                                // security
                         OPEN_ALWAYS,                         // create disposition
                         createOptions,                       // flags
                         NULL);                               // hTempl
        if (fd == INVALID_HANDLE_VALUE) {
            DWORD dosError = GetLastError();
            log() << "CreateFileW for " << filename << " failed with "
                  << errnoWithDescription(dosError) << " (file size is " << length << ")"
                  << " in MemoryMappedFile::map" << endl;
            return 0;
        }
    }

    mapped += length;

    {
        DWORD flProtect = PAGE_READWRITE;  //(options & READONLY)?PAGE_READONLY:PAGE_READWRITE;
        maphandle = CreateFileMappingW(fd,
                                       NULL,
                                       flProtect,
                                       length >> 32 /*maxsizehigh*/,
                                       (unsigned)length /*maxsizelow*/,
                                       NULL /*lpName*/);
        if (maphandle == NULL) {
            DWORD dosError = GetLastError();
            log() << "CreateFileMappingW for " << filename << " failed with "
                  << errnoWithDescription(dosError) << " (file size is " << length << ")"
                  << " in MemoryMappedFile::map" << endl;
            close();
            fassertFailed(16225);
        }
    }

    void* view = 0;
    {
        stdx::lock_guard<stdx::mutex> lk(mapViewMutex);
        DWORD access = (options & READONLY) ? FILE_MAP_READ : FILE_MAP_ALL_ACCESS;

        int current_retry = 0;
        while (true) {
            LPVOID thisAddress = getNextMemoryMappedFileLocation(length);

            view = MapViewOfFileEx(maphandle,  // file mapping handle
                                   access,     // access
                                   0,
                                   0,             // file offset, high and low
                                   0,             // bytes to map, 0 == all
                                   thisAddress);  // address to place file

            if (view == 0) {
                DWORD dosError = GetLastError();

                ++current_retry;

                // If we failed to allocate a memory mapped file, try again in case we picked
                // an address that Windows is also trying to use for some other VM allocations
                if (dosError == ERROR_INVALID_ADDRESS && current_retry < 5) {
                    continue;
                }

#ifndef _WIN64
                // Warn user that if they are running a 32-bit app on 64-bit Windows
                if (dosError == ERROR_NOT_ENOUGH_MEMORY) {
                    BOOL wow64Process;
                    BOOL retWow64 = IsWow64Process(GetCurrentProcess(), &wow64Process);
                    if (retWow64 && wow64Process) {
                        log() << "This is a 32-bit MongoDB binary running on a 64-bit"
                                 " operating system that has run out of virtual memory for"
                                 " databases. Switch to a 64-bit build of MongoDB to open"
                                 " the databases.";
                    }
                }
#endif

                log() << "MapViewOfFileEx for " << filename << " at address " << thisAddress
                      << " failed with " << errnoWithDescription(dosError) << " (file size is "
                      << length << ")"
                      << " in MemoryMappedFile::map" << endl;

                close();
                fassertFailed(16166);
            }

            break;
        }
    }

    views.push_back(view);
    len = length;
    return view;
}

extern stdx::mutex mapViewMutex;

void* MemoryMappedFile::createPrivateMap() {
    verify(maphandle);

    stdx::lock_guard<stdx::mutex> lk(mapViewMutex);

    LPVOID thisAddress = getNextMemoryMappedFileLocation(len);

    void* privateMapAddress = NULL;
    int current_retry = 0;

    while (true) {
        privateMapAddress = MapViewOfFileEx(maphandle,      // file mapping handle
                                            FILE_MAP_READ,  // access
                                            0,
                                            0,             // file offset, high and low
                                            0,             // bytes to map, 0 == all
                                            thisAddress);  // address to place file

        if (privateMapAddress == 0) {
            DWORD dosError = GetLastError();

            ++current_retry;

            // If we failed to allocate a memory mapped file, try again in case we picked
            // an address that Windows is also trying to use for some other VM allocations
            if (dosError == ERROR_INVALID_ADDRESS && current_retry < 5) {
                continue;
            }

            log() << "MapViewOfFileEx for " << filename() << " failed with error "
                  << errnoWithDescription(dosError) << " (file size is " << len << ")"
                  << " in MemoryMappedFile::createPrivateMap" << endl;

            fassertFailed(16167);
        }

        break;
    }

    views.push_back(privateMapAddress);
    return privateMapAddress;
}

void* MemoryMappedFile::remapPrivateView(void* oldPrivateAddr) {
    LockMongoFilesExclusive lockMongoFiles;

    privateViews.clearWritableBits(oldPrivateAddr, len);

    stdx::lock_guard<stdx::mutex> lk(mapViewMutex);

    if (!UnmapViewOfFile(oldPrivateAddr)) {
        DWORD dosError = GetLastError();
        log() << "UnMapViewOfFile for " << filename() << " failed with error "
              << errnoWithDescription(dosError) << " in MemoryMappedFile::remapPrivateView" << endl;
        fassertFailed(16168);
    }

    void* newPrivateView =
        MapViewOfFileEx(maphandle,      // file mapping handle
                        FILE_MAP_READ,  // access
                        0,
                        0,                // file offset, high and low
                        0,                // bytes to map, 0 == all
                        oldPrivateAddr);  // we want the same address we had before
    if (0 == newPrivateView) {
        DWORD dosError = GetLastError();
        log() << "MapViewOfFileEx for " << filename() << " failed with error "
              << errnoWithDescription(dosError) << " (file size is " << len << ")"
              << " in MemoryMappedFile::remapPrivateView" << endl;
    }
    fassert(16148, newPrivateView == oldPrivateAddr);
    return newPrivateView;
}

class WindowsFlushable : public MemoryMappedFile::Flushable {
public:
    WindowsFlushable(MemoryMappedFile* theFile,
                     void* view,
                     HANDLE fd,
                     const uint64_t id,
                     const std::string& filename,
                     stdx::mutex& flushMutex)
        : _theFile(theFile),
          _view(view),
          _fd(fd),
          _id(id),
          _filename(filename),
          _flushMutex(flushMutex) {}

    void flush() {
        if (!_view || !_fd)
            return;

        {
            LockMongoFilesShared mmfilesLock;

            std::set<MongoFile*> mmfs = MongoFile::getAllFiles();
            std::set<MongoFile*>::const_iterator it = mmfs.find(_theFile);
            if (it == mmfs.end() || (*it)->getUniqueId() != _id) {
                // this was deleted while we were unlocked
                return;
            }

            // Hold the flush mutex to ensure the file is not closed during flush
            _flushMutex.lock();
        }

        stdx::lock_guard<stdx::mutex> lk(_flushMutex, stdx::adopt_lock);

        int loopCount = 0;
        bool success = false;
        bool timeout = false;
        int dosError = ERROR_SUCCESS;
        const int maximumTimeInSeconds = 60 * 15;
        Timer t;
        while (!success && !timeout) {
            ++loopCount;
            success = FALSE != FlushViewOfFile(_view, 0);
            if (!success) {
                dosError = GetLastError();
                if (dosError != ERROR_LOCK_VIOLATION) {
                    break;
                }
                timeout = t.seconds() > maximumTimeInSeconds;
            }
        }
        if (success && loopCount > 1) {
            log() << "FlushViewOfFile for " << _filename << " succeeded after " << loopCount
                  << " attempts taking " << t.millis() << "ms" << endl;
        } else if (!success) {
            log() << "FlushViewOfFile for " << _filename << " failed with error " << dosError
                  << " after " << loopCount << " attempts taking " << t.millis() << "ms" << endl;
            // Abort here to avoid data corruption
            fassert(16387, false);
        }

        success = FALSE != FlushFileBuffers(_fd);
        if (!success) {
            int err = GetLastError();
            log() << "FlushFileBuffers failed: " << errnoWithDescription(err)
                  << " file: " << _filename << endl;
            dataSyncFailedHandler();
        }
    }

    MemoryMappedFile* _theFile;  // this may be deleted while we are running
    void* _view;
    HANDLE _fd;
    const uint64_t _id;
    string _filename;
    stdx::mutex& _flushMutex;
};

void MemoryMappedFile::flush(bool sync) {
    uassert(13056, "Async flushing not supported on windows", sync);
    if (!views.empty()) {
        WindowsFlushable f(this, viewForFlushing(), fd, _uniqueId, filename(), _flushMutex);
        f.flush();
    }
}

MemoryMappedFile::Flushable* MemoryMappedFile::prepareFlush() {
    return new WindowsFlushable(this, viewForFlushing(), fd, _uniqueId, filename(), _flushMutex);
}
}