File indexing completed on 2024-05-12 03:54:54

0001 /*
0002     This file is part of the KDE project.
0003 
0004     SPDX-FileCopyrightText: 2010 Michael Pyne <mpyne@kde.org>
0005 
0006     SPDX-License-Identifier: LGPL-2.0-only
0007 */
0008 
0009 #ifndef KSHAREDDATACACHE_P_H
0010 #define KSHAREDDATACACHE_P_H
0011 
0012 #include "kcoreaddons_debug.h"
0013 
0014 #include <cerrno>
0015 #include <fcntl.h>
0016 #include <unistd.h> // for _POSIX_ADVISORY_INFO
0017 
0018 // posix_fallocate is used to ensure that the file used for the cache is
0019 // actually fully committed to disk before attempting to use the file.
0020 #if defined(_POSIX_ADVISORY_INFO) && ((_POSIX_ADVISORY_INFO == 0) || (_POSIX_ADVISORY_INFO >= 200112L))
0021 #define KSDC_POSIX_FALLOCATE_SUPPORTED 1
0022 #endif
0023 #ifdef Q_OS_OSX
0024 #include "posix_fallocate_mac.h"
0025 #define KSDC_POSIX_FALLOCATE_SUPPORTED 1
0026 #endif
0027 
0028 static bool ensureFileAllocated(int fd, size_t fileSize)
0029 {
0030 #ifdef KSDC_POSIX_FALLOCATE_SUPPORTED
0031     int result;
0032     while ((result = ::posix_fallocate(fd, 0, fileSize)) == EINTR) {
0033         ;
0034     }
0035 
0036     if (result != 0) {
0037         if (result == ENOSPC) {
0038             qCCritical(KCOREADDONS_DEBUG) << "No space left on device. Check filesystem free space at your XDG_CACHE_HOME!";
0039         }
0040         qCCritical(KCOREADDONS_DEBUG) << "The operating system is unable to promise" << fileSize
0041                                       << "bytes for mapped cache, "
0042                                          "abandoning the cache for crash-safety.";
0043         return false;
0044     }
0045 
0046     return true;
0047 #else
0048 
0049 #ifdef __GNUC__
0050 #warning                                                                                                                                                       \
0051     "This system does not seem to support posix_fallocate, which is needed to ensure KSharedDataCache's underlying files are fully committed to disk to avoid crashes with low disk space."
0052 #endif
0053     qCWarning(KCOREADDONS_DEBUG) << "This system misses support for posix_fallocate()"
0054                                     " -- ensure this partition has room for at least"
0055                                  << fileSize << "bytes.";
0056 
0057     // TODO: It's possible to emulate the functionality, but doing so
0058     // overwrites the data in the file so we don't do this. If you were to add
0059     // this emulation, you must ensure it only happens on initial creation of a
0060     // new file and not just mapping an existing cache.
0061 
0062     return true;
0063 #endif // KSDC_POSIX_FALLOCATE_SUPPORTED
0064 }
0065 
0066 #endif /* KSHAREDDATACACHE_P_H */