]> git.sesse.net Git - stockfish/blob - src/misc.cpp
Use fallback implementation for C++ aligned_alloc
[stockfish] / src / misc.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2020 The Stockfish developers (see AUTHORS file)
4
5   Stockfish is free software: you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation, either version 3 of the License, or
8   (at your option) any later version.
9
10   Stockfish is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #ifdef _WIN32
20 #if _WIN32_WINNT < 0x0601
21 #undef  _WIN32_WINNT
22 #define _WIN32_WINNT 0x0601 // Force to include needed API prototypes
23 #endif
24
25 #ifndef NOMINMAX
26 #define NOMINMAX
27 #endif
28
29 #include <windows.h>
30 // The needed Windows API for processor groups could be missed from old Windows
31 // versions, so instead of calling them directly (forcing the linker to resolve
32 // the calls at compile time), try to load them at runtime. To do this we need
33 // first to define the corresponding function pointers.
34 extern "C" {
35 typedef bool(*fun1_t)(LOGICAL_PROCESSOR_RELATIONSHIP,
36                       PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX, PDWORD);
37 typedef bool(*fun2_t)(USHORT, PGROUP_AFFINITY);
38 typedef bool(*fun3_t)(HANDLE, CONST GROUP_AFFINITY*, PGROUP_AFFINITY);
39 }
40 #endif
41
42 #include <fstream>
43 #include <iomanip>
44 #include <iostream>
45 #include <sstream>
46 #include <vector>
47 #include <cstdlib>
48
49 #if defined(__linux__) && !defined(__ANDROID__)
50 #include <stdlib.h>
51 #include <sys/mman.h>
52 #endif
53
54 #include "misc.h"
55 #include "thread.h"
56
57 using namespace std;
58
59 namespace {
60
61 /// Version number. If Version is left empty, then compile date in the format
62 /// DD-MM-YY and show in engine_info.
63 const string Version = "";
64
65 /// Our fancy logging facility. The trick here is to replace cin.rdbuf() and
66 /// cout.rdbuf() with two Tie objects that tie cin and cout to a file stream. We
67 /// can toggle the logging of std::cout and std:cin at runtime whilst preserving
68 /// usual I/O functionality, all without changing a single line of code!
69 /// Idea from http://groups.google.com/group/comp.lang.c++/msg/1d941c0f26ea0d81
70
71 struct Tie: public streambuf { // MSVC requires split streambuf for cin and cout
72
73   Tie(streambuf* b, streambuf* l) : buf(b), logBuf(l) {}
74
75   int sync() override { return logBuf->pubsync(), buf->pubsync(); }
76   int overflow(int c) override { return log(buf->sputc((char)c), "<< "); }
77   int underflow() override { return buf->sgetc(); }
78   int uflow() override { return log(buf->sbumpc(), ">> "); }
79
80   streambuf *buf, *logBuf;
81
82   int log(int c, const char* prefix) {
83
84     static int last = '\n'; // Single log file
85
86     if (last == '\n')
87         logBuf->sputn(prefix, 3);
88
89     return last = logBuf->sputc((char)c);
90   }
91 };
92
93 class Logger {
94
95   Logger() : in(cin.rdbuf(), file.rdbuf()), out(cout.rdbuf(), file.rdbuf()) {}
96  ~Logger() { start(""); }
97
98   ofstream file;
99   Tie in, out;
100
101 public:
102   static void start(const std::string& fname) {
103
104     static Logger l;
105
106     if (!fname.empty() && !l.file.is_open())
107     {
108         l.file.open(fname, ifstream::out);
109
110         if (!l.file.is_open())
111         {
112             cerr << "Unable to open debug log file " << fname << endl;
113             exit(EXIT_FAILURE);
114         }
115
116         cin.rdbuf(&l.in);
117         cout.rdbuf(&l.out);
118     }
119     else if (fname.empty() && l.file.is_open())
120     {
121         cout.rdbuf(l.out.buf);
122         cin.rdbuf(l.in.buf);
123         l.file.close();
124     }
125   }
126 };
127
128 } // namespace
129
130 /// engine_info() returns the full name of the current Stockfish version. This
131 /// will be either "Stockfish <Tag> DD-MM-YY" (where DD-MM-YY is the date when
132 /// the program was compiled) or "Stockfish <Version>", depending on whether
133 /// Version is empty.
134
135 const string engine_info(bool to_uci) {
136
137   const string months("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec");
138   string month, day, year;
139   stringstream ss, date(__DATE__); // From compiler, format is "Sep 21 2008"
140
141   ss << "Stockfish " << Version << setfill('0');
142
143   if (Version.empty())
144   {
145       date >> month >> day >> year;
146       ss << setw(2) << day << setw(2) << (1 + months.find(month) / 4) << year.substr(2);
147   }
148
149   ss << (to_uci  ? "\nid author ": " by ")
150      << "the Stockfish developers (see AUTHORS file)";
151
152   return ss.str();
153 }
154
155
156 /// compiler_info() returns a string trying to describe the compiler we use
157
158 const std::string compiler_info() {
159
160   #define stringify2(x) #x
161   #define stringify(x) stringify2(x)
162   #define make_version_string(major, minor, patch) stringify(major) "." stringify(minor) "." stringify(patch)
163
164 /// Predefined macros hell:
165 ///
166 /// __GNUC__           Compiler is gcc, Clang or Intel on Linux
167 /// __INTEL_COMPILER   Compiler is Intel
168 /// _MSC_VER           Compiler is MSVC or Intel on Windows
169 /// _WIN32             Building on Windows (any)
170 /// _WIN64             Building on Windows 64 bit
171
172   std::string compiler = "\nCompiled by ";
173
174   #ifdef __clang__
175      compiler += "clang++ ";
176      compiler += make_version_string(__clang_major__, __clang_minor__, __clang_patchlevel__);
177   #elif __INTEL_COMPILER
178      compiler += "Intel compiler ";
179      compiler += "(version ";
180      compiler += stringify(__INTEL_COMPILER) " update " stringify(__INTEL_COMPILER_UPDATE);
181      compiler += ")";
182   #elif _MSC_VER
183      compiler += "MSVC ";
184      compiler += "(version ";
185      compiler += stringify(_MSC_FULL_VER) "." stringify(_MSC_BUILD);
186      compiler += ")";
187   #elif __GNUC__
188      compiler += "g++ (GNUC) ";
189      compiler += make_version_string(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
190   #else
191      compiler += "Unknown compiler ";
192      compiler += "(unknown version)";
193   #endif
194
195   #if defined(__APPLE__)
196      compiler += " on Apple";
197   #elif defined(__CYGWIN__)
198      compiler += " on Cygwin";
199   #elif defined(__MINGW64__)
200      compiler += " on MinGW64";
201   #elif defined(__MINGW32__)
202      compiler += " on MinGW32";
203   #elif defined(__ANDROID__)
204      compiler += " on Android";
205   #elif defined(__linux__)
206      compiler += " on Linux";
207   #elif defined(_WIN64)
208      compiler += " on Microsoft Windows 64-bit";
209   #elif defined(_WIN32)
210      compiler += " on Microsoft Windows 32-bit";
211   #else
212      compiler += " on unknown system";
213   #endif
214
215   compiler += "\nCompilation settings include: ";
216   compiler += (Is64Bit ? " 64bit" : " 32bit");
217   #if defined(USE_AVX512)
218     compiler += " AVX512";
219   #endif
220   #if defined(USE_AVX2)
221     compiler += " AVX2";
222   #endif
223   #if defined(USE_SSE42)
224     compiler += " SSE42";
225   #endif
226   #if defined(USE_SSE41)
227     compiler += " SSE41";
228   #endif
229   #if defined(USE_SSSE3)
230     compiler += " SSSE3";
231   #endif
232   #if defined(USE_SSE3)
233     compiler += " SSE3";
234   #endif
235     compiler += (HasPext ? " BMI2" : "");
236     compiler += (HasPopCnt ? " POPCNT" : "");
237   #if !defined(NDEBUG)
238     compiler += " DEBUG";
239   #endif
240
241   compiler += "\n__VERSION__ macro expands to: ";
242   #ifdef __VERSION__
243      compiler += __VERSION__;
244   #else
245      compiler += "(undefined macro)";
246   #endif
247   compiler += "\n";
248
249   return compiler;
250 }
251
252
253 /// Debug functions used mainly to collect run-time statistics
254 static std::atomic<int64_t> hits[2], means[2];
255
256 void dbg_hit_on(bool b) { ++hits[0]; if (b) ++hits[1]; }
257 void dbg_hit_on(bool c, bool b) { if (c) dbg_hit_on(b); }
258 void dbg_mean_of(int v) { ++means[0]; means[1] += v; }
259
260 void dbg_print() {
261
262   if (hits[0])
263       cerr << "Total " << hits[0] << " Hits " << hits[1]
264            << " hit rate (%) " << 100 * hits[1] / hits[0] << endl;
265
266   if (means[0])
267       cerr << "Total " << means[0] << " Mean "
268            << (double)means[1] / means[0] << endl;
269 }
270
271
272 /// Used to serialize access to std::cout to avoid multiple threads writing at
273 /// the same time.
274
275 std::ostream& operator<<(std::ostream& os, SyncCout sc) {
276
277   static std::mutex m;
278
279   if (sc == IO_LOCK)
280       m.lock();
281
282   if (sc == IO_UNLOCK)
283       m.unlock();
284
285   return os;
286 }
287
288
289 /// Trampoline helper to avoid moving Logger to misc.h
290 void start_logger(const std::string& fname) { Logger::start(fname); }
291
292
293 /// prefetch() preloads the given address in L1/L2 cache. This is a non-blocking
294 /// function that doesn't stall the CPU waiting for data to be loaded from memory,
295 /// which can be quite slow.
296 #ifdef NO_PREFETCH
297
298 void prefetch(void*) {}
299
300 #else
301
302 void prefetch(void* addr) {
303
304 #  if defined(__INTEL_COMPILER)
305    // This hack prevents prefetches from being optimized away by
306    // Intel compiler. Both MSVC and gcc seem not be affected by this.
307    __asm__ ("");
308 #  endif
309
310 #  if defined(__INTEL_COMPILER) || defined(_MSC_VER)
311   _mm_prefetch((char*)addr, _MM_HINT_T0);
312 #  else
313   __builtin_prefetch(addr);
314 #  endif
315 }
316
317 #endif
318
319 /// Wrappers for systems where the c++17 implementation doesn't guarantee the availability of aligned_alloc.
320 /// Memory allocated with std_aligned_alloc must be freed with std_aligned_free.
321 ///
322
323 void* std_aligned_alloc(size_t alignment, size_t size) {
324 #if (defined(__APPLE__) && defined(_LIBCPP_HAS_C11_FEATURES)) || defined(__ANDROID__) || defined(__OpenBSD__) || (defined(__GLIBCXX__) && !defined(_GLIBCXX_HAVE_ALIGNED_ALLOC) )
325   return aligned_alloc(alignment, size);
326 #elif (defined(_WIN32) || (defined(__APPLE__) && !defined(_LIBCPP_HAS_C11_FEATURES)))
327   return _mm_malloc(size, alignment);
328 #else
329   return std::aligned_alloc(alignment, size);
330 #endif
331 }
332
333 void std_aligned_free(void* ptr) {
334 #if (defined(__APPLE__) && defined(_LIBCPP_HAS_C11_FEATURES)) || defined(__ANDROID__) || defined(__OpenBSD__) || (defined(__GLIBCXX__) && !defined(_GLIBCXX_HAVE_ALIGNED_ALLOC) )
335   free(ptr);
336 #elif (defined(_WIN32) || (defined(__APPLE__) && !defined(_LIBCPP_HAS_C11_FEATURES)))
337   _mm_free(ptr);
338 #else
339   free(ptr);
340 #endif
341 }
342
343 /// aligned_ttmem_alloc() will return suitably aligned memory, and if possible use large pages.
344 /// The returned pointer is the aligned one, while the mem argument is the one that needs
345 /// to be passed to free. With c++17 some of this functionality could be simplified.
346
347 #if defined(__linux__) && !defined(__ANDROID__)
348
349 void* aligned_ttmem_alloc(size_t allocSize, void*& mem) {
350
351   constexpr size_t alignment = 2 * 1024 * 1024; // assumed 2MB page sizes
352   size_t size = ((allocSize + alignment - 1) / alignment) * alignment; // multiple of alignment
353   if (posix_memalign(&mem, alignment, size))
354      mem = nullptr;
355   madvise(mem, allocSize, MADV_HUGEPAGE);
356   return mem;
357 }
358
359 #elif defined(_WIN64)
360
361 static void* aligned_ttmem_alloc_large_pages(size_t allocSize) {
362
363   HANDLE hProcessToken { };
364   LUID luid { };
365   void* mem = nullptr;
366
367   const size_t largePageSize = GetLargePageMinimum();
368   if (!largePageSize)
369       return nullptr;
370
371   // We need SeLockMemoryPrivilege, so try to enable it for the process
372   if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hProcessToken))
373       return nullptr;
374
375   if (LookupPrivilegeValue(NULL, SE_LOCK_MEMORY_NAME, &luid))
376   {
377       TOKEN_PRIVILEGES tp { };
378       TOKEN_PRIVILEGES prevTp { };
379       DWORD prevTpLen = 0;
380
381       tp.PrivilegeCount = 1;
382       tp.Privileges[0].Luid = luid;
383       tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
384
385       // Try to enable SeLockMemoryPrivilege. Note that even if AdjustTokenPrivileges() succeeds,
386       // we still need to query GetLastError() to ensure that the privileges were actually obtained.
387       if (AdjustTokenPrivileges(
388               hProcessToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &prevTp, &prevTpLen) &&
389           GetLastError() == ERROR_SUCCESS)
390       {
391           // Round up size to full pages and allocate
392           allocSize = (allocSize + largePageSize - 1) & ~size_t(largePageSize - 1);
393           mem = VirtualAlloc(
394               NULL, allocSize, MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES, PAGE_READWRITE);
395
396           // Privilege no longer needed, restore previous state
397           AdjustTokenPrivileges(hProcessToken, FALSE, &prevTp, 0, NULL, NULL);
398       }
399   }
400
401   CloseHandle(hProcessToken);
402
403   return mem;
404 }
405
406 void* aligned_ttmem_alloc(size_t allocSize, void*& mem) {
407
408   static bool firstCall = true;
409
410   // Try to allocate large pages
411   mem = aligned_ttmem_alloc_large_pages(allocSize);
412
413   // Suppress info strings on the first call. The first call occurs before 'uci'
414   // is received and in that case this output confuses some GUIs.
415   if (!firstCall)
416   {
417       if (mem)
418           sync_cout << "info string Hash table allocation: Windows large pages used." << sync_endl;
419       else
420           sync_cout << "info string Hash table allocation: Windows large pages not used." << sync_endl;
421   }
422   firstCall = false;
423
424   // Fall back to regular, page aligned, allocation if necessary
425   if (!mem)
426       mem = VirtualAlloc(NULL, allocSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
427
428   return mem;
429 }
430
431 #else
432
433 void* aligned_ttmem_alloc(size_t allocSize, void*& mem) {
434
435   constexpr size_t alignment = 64; // assumed cache line size
436   size_t size = allocSize + alignment - 1; // allocate some extra space
437   mem = malloc(size);
438   void* ret = reinterpret_cast<void*>((uintptr_t(mem) + alignment - 1) & ~uintptr_t(alignment - 1));
439   return ret;
440 }
441
442 #endif
443
444
445 /// aligned_ttmem_free() will free the previously allocated ttmem
446
447 #if defined(_WIN64)
448
449 void aligned_ttmem_free(void* mem) {
450
451   if (mem && !VirtualFree(mem, 0, MEM_RELEASE))
452   {
453       DWORD err = GetLastError();
454       std::cerr << "Failed to free transposition table. Error code: 0x" <<
455           std::hex << err << std::dec << std::endl;
456       exit(EXIT_FAILURE);
457   }
458 }
459
460 #else
461
462 void aligned_ttmem_free(void *mem) {
463   free(mem);
464 }
465
466 #endif
467
468
469 namespace WinProcGroup {
470
471 #ifndef _WIN32
472
473 void bindThisThread(size_t) {}
474
475 #else
476
477 /// best_group() retrieves logical processor information using Windows specific
478 /// API and returns the best group id for the thread with index idx. Original
479 /// code from Texel by Peter Ă–sterlund.
480
481 int best_group(size_t idx) {
482
483   int threads = 0;
484   int nodes = 0;
485   int cores = 0;
486   DWORD returnLength = 0;
487   DWORD byteOffset = 0;
488
489   // Early exit if the needed API is not available at runtime
490   HMODULE k32 = GetModuleHandle("Kernel32.dll");
491   auto fun1 = (fun1_t)(void(*)())GetProcAddress(k32, "GetLogicalProcessorInformationEx");
492   if (!fun1)
493       return -1;
494
495   // First call to get returnLength. We expect it to fail due to null buffer
496   if (fun1(RelationAll, nullptr, &returnLength))
497       return -1;
498
499   // Once we know returnLength, allocate the buffer
500   SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX *buffer, *ptr;
501   ptr = buffer = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)malloc(returnLength);
502
503   // Second call, now we expect to succeed
504   if (!fun1(RelationAll, buffer, &returnLength))
505   {
506       free(buffer);
507       return -1;
508   }
509
510   while (byteOffset < returnLength)
511   {
512       if (ptr->Relationship == RelationNumaNode)
513           nodes++;
514
515       else if (ptr->Relationship == RelationProcessorCore)
516       {
517           cores++;
518           threads += (ptr->Processor.Flags == LTP_PC_SMT) ? 2 : 1;
519       }
520
521       assert(ptr->Size);
522       byteOffset += ptr->Size;
523       ptr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)(((char*)ptr) + ptr->Size);
524   }
525
526   free(buffer);
527
528   std::vector<int> groups;
529
530   // Run as many threads as possible on the same node until core limit is
531   // reached, then move on filling the next node.
532   for (int n = 0; n < nodes; n++)
533       for (int i = 0; i < cores / nodes; i++)
534           groups.push_back(n);
535
536   // In case a core has more than one logical processor (we assume 2) and we
537   // have still threads to allocate, then spread them evenly across available
538   // nodes.
539   for (int t = 0; t < threads - cores; t++)
540       groups.push_back(t % nodes);
541
542   // If we still have more threads than the total number of logical processors
543   // then return -1 and let the OS to decide what to do.
544   return idx < groups.size() ? groups[idx] : -1;
545 }
546
547
548 /// bindThisThread() set the group affinity of the current thread
549
550 void bindThisThread(size_t idx) {
551
552   // Use only local variables to be thread-safe
553   int group = best_group(idx);
554
555   if (group == -1)
556       return;
557
558   // Early exit if the needed API are not available at runtime
559   HMODULE k32 = GetModuleHandle("Kernel32.dll");
560   auto fun2 = (fun2_t)(void(*)())GetProcAddress(k32, "GetNumaNodeProcessorMaskEx");
561   auto fun3 = (fun3_t)(void(*)())GetProcAddress(k32, "SetThreadGroupAffinity");
562
563   if (!fun2 || !fun3)
564       return;
565
566   GROUP_AFFINITY affinity;
567   if (fun2(group, &affinity))
568       fun3(GetCurrentThread(), &affinity, nullptr);
569 }
570
571 #endif
572
573 } // namespace WinProcGroup