mem_arena.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. // Copyright (C) 2003 Dolphin Project.
  2. // This program is free software: you can redistribute it and/or modify
  3. // it under the terms of the GNU General Public License as published by
  4. // the Free Software Foundation, version 2.0 or later versions.
  5. // This program is distributed in the hope that it will be useful,
  6. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  7. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  8. // GNU General Public License 2.0 for more details.
  9. // A copy of the GPL 2.0 should have been included with the program.
  10. // If not, see http://www.gnu.org/licenses/
  11. // Official SVN repository and contact information can be found at
  12. // http://code.google.com/p/dolphin-emu/
  13. #include <string>
  14. #include "common/memory_util.h"
  15. #include "common/mem_arena.h"
  16. #include "common/string_util.h"
  17. #ifndef _WIN32
  18. #include <sys/stat.h>
  19. #include <fcntl.h>
  20. #include <unistd.h>
  21. #include <cerrno>
  22. #include <cstring>
  23. #ifdef ANDROID
  24. #include <sys/ioctl.h>
  25. #include <linux/ashmem.h>
  26. #endif
  27. #endif
  28. #ifdef IOS
  29. void* globalbase = NULL;
  30. #endif
  31. #ifdef ANDROID
  32. // Hopefully this ABI will never change...
  33. #define ASHMEM_DEVICE "/dev/ashmem"
  34. /*
  35. * ashmem_create_region - creates a new ashmem region and returns the file
  36. * descriptor, or <0 on error
  37. *
  38. * `name' is an optional label to give the region (visible in /proc/pid/maps)
  39. * `size' is the size of the region, in page-aligned bytes
  40. */
  41. int ashmem_create_region(const char *name, size_t size)
  42. {
  43. int fd, ret;
  44. fd = open(ASHMEM_DEVICE, O_RDWR);
  45. if (fd < 0)
  46. return fd;
  47. if (name) {
  48. char buf[ASHMEM_NAME_LEN];
  49. strncpy(buf, name, sizeof(buf));
  50. ret = ioctl(fd, ASHMEM_SET_NAME, buf);
  51. if (ret < 0)
  52. goto error;
  53. }
  54. ret = ioctl(fd, ASHMEM_SET_SIZE, size);
  55. if (ret < 0)
  56. goto error;
  57. return fd;
  58. error:
  59. ERROR_LOG(MEMMAP, "NASTY ASHMEM ERROR: ret = %08x", ret);
  60. close(fd);
  61. return ret;
  62. }
  63. int ashmem_set_prot_region(int fd, int prot)
  64. {
  65. return ioctl(fd, ASHMEM_SET_PROT_MASK, prot);
  66. }
  67. int ashmem_pin_region(int fd, size_t offset, size_t len)
  68. {
  69. struct ashmem_pin pin = { offset, len };
  70. return ioctl(fd, ASHMEM_PIN, &pin);
  71. }
  72. int ashmem_unpin_region(int fd, size_t offset, size_t len)
  73. {
  74. struct ashmem_pin pin = { offset, len };
  75. return ioctl(fd, ASHMEM_UNPIN, &pin);
  76. }
  77. #endif // Android
  78. #if defined(_WIN32) && !defined(_XBOX)
  79. SYSTEM_INFO sysInfo;
  80. #endif
  81. // Windows mappings need to be on 64K boundaries, due to Alpha legacy.
  82. #ifdef _WIN32
  83. size_t roundup(size_t x) {
  84. #ifndef _XBOX
  85. int gran = sysInfo.dwAllocationGranularity ? sysInfo.dwAllocationGranularity : 0x10000;
  86. #else
  87. int gran = 0x10000; // 64k in 360
  88. #endif
  89. return (x + gran - 1) & ~(gran - 1);
  90. }
  91. #else
  92. size_t roundup(size_t x) {
  93. return x;
  94. }
  95. #endif
  96. void MemArena::GrabLowMemSpace(size_t size)
  97. {
  98. #ifdef _WIN32
  99. #ifndef _XBOX
  100. hMemoryMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, (DWORD)(size), NULL);
  101. GetSystemInfo(&sysInfo);
  102. #endif
  103. #elif defined(ANDROID)
  104. // Use ashmem so we don't have to allocate a file on disk!
  105. fd = ashmem_create_region("PPSSPP_RAM", size);
  106. // Note that it appears that ashmem is pinned by default, so no need to pin.
  107. if (fd < 0)
  108. {
  109. ERROR_LOG(MEMMAP, "Failed to grab ashmem space of size: %08x errno: %d", (int)size, (int)(errno));
  110. return;
  111. }
  112. #else
  113. // Try to find a non-existing filename for our shared memory.
  114. // In most cases the first one will be available, but it's nicer to search
  115. // a bit more.
  116. for (int i = 0; i < 10000; i++)
  117. {
  118. std::string file_name = StringFromFormat("/citramem.%d", i);
  119. fd = shm_open(file_name.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600);
  120. if (fd != -1)
  121. {
  122. shm_unlink(file_name.c_str());
  123. break;
  124. }
  125. else if (errno != EEXIST)
  126. {
  127. ERROR_LOG(MEMMAP, "shm_open failed: %s", strerror(errno));
  128. return;
  129. }
  130. }
  131. if (ftruncate(fd, size) < 0)
  132. ERROR_LOG(MEMMAP, "Failed to allocate low memory space");
  133. #endif
  134. }
  135. void MemArena::ReleaseSpace()
  136. {
  137. #ifdef _WIN32
  138. CloseHandle(hMemoryMapping);
  139. hMemoryMapping = 0;
  140. #elif defined(__SYMBIAN32__)
  141. memmap->Close();
  142. delete memmap;
  143. #else
  144. close(fd);
  145. #endif
  146. }
  147. void *MemArena::CreateView(s64 offset, size_t size, void *base)
  148. {
  149. #ifdef _WIN32
  150. #ifdef _XBOX
  151. size = roundup(size);
  152. // use 64kb pages
  153. void * ptr = VirtualAlloc(NULL, size, MEM_COMMIT | MEM_LARGE_PAGES, PAGE_READWRITE);
  154. return ptr;
  155. #else
  156. size = roundup(size);
  157. void *ptr = MapViewOfFileEx(hMemoryMapping, FILE_MAP_ALL_ACCESS, 0, (DWORD)((u64)offset), size, base);
  158. return ptr;
  159. #endif
  160. #else
  161. void *retval = mmap(base, size, PROT_READ | PROT_WRITE, MAP_SHARED |
  162. // Do not sync memory to underlying file. Linux has this by default.
  163. #ifdef BLACKBERRY
  164. MAP_NOSYNCFILE |
  165. #elif defined(__FreeBSD__)
  166. MAP_NOSYNC |
  167. #endif
  168. ((base == nullptr) ? 0 : MAP_FIXED), fd, offset);
  169. if (retval == MAP_FAILED)
  170. {
  171. NOTICE_LOG(MEMMAP, "mmap failed");
  172. return nullptr;
  173. }
  174. return retval;
  175. #endif
  176. }
  177. void MemArena::ReleaseView(void* view, size_t size)
  178. {
  179. #ifdef _WIN32
  180. #ifndef _XBOX
  181. UnmapViewOfFile(view);
  182. #endif
  183. #elif defined(__SYMBIAN32__)
  184. memmap->Decommit(((int)view - (int)memmap->Base()) & 0x3FFFFFFF, size);
  185. #else
  186. munmap(view, size);
  187. #endif
  188. }
  189. #ifndef __SYMBIAN32__
  190. u8* MemArena::Find4GBBase()
  191. {
  192. #ifdef _M_X64
  193. #ifdef _WIN32
  194. // 64 bit
  195. u8* base = (u8*)VirtualAlloc(0, 0xE1000000, MEM_RESERVE, PAGE_READWRITE);
  196. VirtualFree(base, 0, MEM_RELEASE);
  197. return base;
  198. #else
  199. // Very precarious - mmap cannot return an error when trying to map already used pages.
  200. // This makes the Windows approach above unusable on Linux, so we will simply pray...
  201. return reinterpret_cast<u8*>(0x2300000000ULL);
  202. #endif
  203. #else // 32 bit
  204. #ifdef _WIN32
  205. u8* base = (u8*)VirtualAlloc(0, 0x10000000, MEM_RESERVE, PAGE_READWRITE);
  206. if (base) {
  207. VirtualFree(base, 0, MEM_RELEASE);
  208. }
  209. return base;
  210. #else
  211. #ifdef IOS
  212. void* base = NULL;
  213. if (globalbase == NULL){
  214. base = mmap(0, 0x08000000, PROT_READ | PROT_WRITE,
  215. MAP_ANON | MAP_SHARED, -1, 0);
  216. if (base == MAP_FAILED) {
  217. PanicAlert("Failed to map 128 MB of memory space: %s", strerror(errno));
  218. return 0;
  219. }
  220. munmap(base, 0x08000000);
  221. globalbase = base;
  222. }
  223. else{ base = globalbase; }
  224. #else
  225. void* base = mmap(0, 0x10000000, PROT_READ | PROT_WRITE,
  226. MAP_ANON | MAP_SHARED, -1, 0);
  227. if (base == MAP_FAILED) {
  228. PanicAlert("Failed to map 256 MB of memory space: %s", strerror(errno));
  229. return 0;
  230. }
  231. munmap(base, 0x10000000);
  232. #endif
  233. return static_cast<u8*>(base);
  234. #endif
  235. #endif
  236. }
  237. #endif
  238. // yeah, this could also be done in like two bitwise ops...
  239. #define SKIP(a_flags, b_flags)
  240. // if (!(a_flags & MV_WII_ONLY) && (b_flags & MV_WII_ONLY))
  241. // continue;
  242. // if (!(a_flags & MV_FAKE_VMEM) && (b_flags & MV_FAKE_VMEM))
  243. // continue;
  244. static bool Memory_TryBase(u8 *base, const MemoryView *views, int num_views, u32 flags, MemArena *arena) {
  245. // OK, we know where to find free space. Now grab it!
  246. // We just mimic the popular BAT setup.
  247. size_t position = 0;
  248. size_t last_position = 0;
  249. #if defined(_XBOX)
  250. void *ptr;
  251. #endif
  252. // Zero all the pointers to be sure.
  253. for (int i = 0; i < num_views; i++)
  254. {
  255. if (views[i].out_ptr_low)
  256. *views[i].out_ptr_low = 0;
  257. if (views[i].out_ptr)
  258. *views[i].out_ptr = 0;
  259. }
  260. int i;
  261. for (i = 0; i < num_views; i++)
  262. {
  263. const MemoryView &view = views[i];
  264. if (view.size == 0)
  265. continue;
  266. SKIP(flags, view.flags);
  267. if (view.flags & MV_MIRROR_PREVIOUS) {
  268. position = last_position;
  269. }
  270. else {
  271. #ifdef __SYMBIAN32__
  272. *(view.out_ptr_low) = (u8*)((int)arena->memmap->Base() + view.virtual_address);
  273. arena->memmap->Commit(view.virtual_address & 0x3FFFFFFF, view.size);
  274. }
  275. *(view.out_ptr) = (u8*)((int)arena->memmap->Base() + view.virtual_address & 0x3FFFFFFF);
  276. #elif defined(_XBOX)
  277. *(view.out_ptr_low) = (u8*)(base + view.virtual_address);
  278. //arena->memmap->Commit(view.virtual_address & 0x3FFFFFFF, view.size);
  279. ptr = VirtualAlloc(base + (view.virtual_address & 0x3FFFFFFF), view.size, MEM_COMMIT, PAGE_READWRITE);
  280. }
  281. *(view.out_ptr) = (u8*)base + (view.virtual_address & 0x3FFFFFFF);
  282. #else
  283. *(view.out_ptr_low) = (u8*)arena->CreateView(position, view.size);
  284. if (!*view.out_ptr_low)
  285. goto bail;
  286. }
  287. #ifdef _M_X64
  288. *view.out_ptr = (u8*)arena->CreateView(
  289. position, view.size, base + view.virtual_address);
  290. #else
  291. if (view.flags & MV_MIRROR_PREVIOUS) { // TODO: should check if the two & 0x3FFFFFFF are identical.
  292. // No need to create multiple identical views.
  293. *view.out_ptr = *views[i - 1].out_ptr;
  294. }
  295. else {
  296. *view.out_ptr = (u8*)arena->CreateView(
  297. position, view.size, base + (view.virtual_address & 0x3FFFFFFF));
  298. if (!*view.out_ptr)
  299. goto bail;
  300. }
  301. #endif
  302. #endif
  303. last_position = position;
  304. position += roundup(view.size);
  305. }
  306. return true;
  307. bail:
  308. // Argh! ERROR! Free what we grabbed so far so we can try again.
  309. for (int j = 0; j <= i; j++)
  310. {
  311. if (views[i].size == 0)
  312. continue;
  313. SKIP(flags, views[i].flags);
  314. if (views[j].out_ptr_low && *views[j].out_ptr_low)
  315. {
  316. arena->ReleaseView(*views[j].out_ptr_low, views[j].size);
  317. *views[j].out_ptr_low = NULL;
  318. }
  319. if (*views[j].out_ptr)
  320. {
  321. #ifdef _M_X64
  322. arena->ReleaseView(*views[j].out_ptr, views[j].size);
  323. #else
  324. if (!(views[j].flags & MV_MIRROR_PREVIOUS))
  325. {
  326. arena->ReleaseView(*views[j].out_ptr, views[j].size);
  327. }
  328. #endif
  329. *views[j].out_ptr = NULL;
  330. }
  331. }
  332. return false;
  333. }
  334. u8 *MemoryMap_Setup(const MemoryView *views, int num_views, u32 flags, MemArena *arena)
  335. {
  336. size_t total_mem = 0;
  337. int base_attempts = 0;
  338. for (int i = 0; i < num_views; i++)
  339. {
  340. if (views[i].size == 0)
  341. continue;
  342. SKIP(flags, views[i].flags);
  343. if ((views[i].flags & MV_MIRROR_PREVIOUS) == 0)
  344. total_mem += roundup(views[i].size);
  345. }
  346. // Grab some pagefile backed memory out of the void ...
  347. #ifndef __SYMBIAN32__
  348. arena->GrabLowMemSpace(total_mem);
  349. #endif
  350. // Now, create views in high memory where there's plenty of space.
  351. #ifdef _M_X64
  352. u8 *base = MemArena::Find4GBBase();
  353. // This really shouldn't fail - in 64-bit, there will always be enough
  354. // address space.
  355. if (!Memory_TryBase(base, views, num_views, flags, arena))
  356. {
  357. PanicAlert("MemoryMap_Setup: Failed finding a memory base.");
  358. return 0;
  359. }
  360. #elif defined(_XBOX)
  361. // Reserve 256MB
  362. u8 *base = (u8*)VirtualAlloc(0, 0x10000000, MEM_RESERVE | MEM_LARGE_PAGES, PAGE_READWRITE);
  363. if (!Memory_TryBase(base, views, num_views, flags, arena))
  364. {
  365. PanicAlert("MemoryMap_Setup: Failed finding a memory base.");
  366. exit(0);
  367. return 0;
  368. }
  369. #elif defined(_WIN32)
  370. // Try a whole range of possible bases. Return once we got a valid one.
  371. u32 max_base_addr = 0x7FFF0000 - 0x10000000;
  372. u8 *base = NULL;
  373. for (u32 base_addr = 0x01000000; base_addr < max_base_addr; base_addr += 0x400000)
  374. {
  375. base_attempts++;
  376. base = (u8 *)base_addr;
  377. if (Memory_TryBase(base, views, num_views, flags, arena))
  378. {
  379. INFO_LOG(MEMMAP, "Found valid memory base at %p after %i tries.", base, base_attempts);
  380. base_attempts = 0;
  381. break;
  382. }
  383. }
  384. #elif defined(__SYMBIAN32__)
  385. arena->memmap = new RChunk();
  386. arena->memmap->CreateDisconnectedLocal(0, 0, 0x10000000);
  387. if (!Memory_TryBase(arena->memmap->Base(), views, num_views, flags, arena))
  388. {
  389. PanicAlert("MemoryMap_Setup: Failed finding a memory base.");
  390. return 0;
  391. }
  392. u8* base = arena->memmap->Base();
  393. #else
  394. // Linux32 is fine with the x64 method, although limited to 32-bit with no automirrors.
  395. u8 *base = MemArena::Find4GBBase();
  396. if (!Memory_TryBase(base, views, num_views, flags, arena))
  397. {
  398. ERROR_LOG(MEMMAP, "MemoryMap_Setup: Failed finding a memory base.");
  399. PanicAlert("MemoryMap_Setup: Failed finding a memory base.");
  400. return 0;
  401. }
  402. #endif
  403. if (base_attempts)
  404. PanicAlert("No possible memory base pointer found!");
  405. return base;
  406. }
  407. void MemoryMap_Shutdown(const MemoryView *views, int num_views, u32 flags, MemArena *arena)
  408. {
  409. for (int i = 0; i < num_views; i++)
  410. {
  411. if (views[i].size == 0)
  412. continue;
  413. SKIP(flags, views[i].flags);
  414. if (views[i].out_ptr_low && *views[i].out_ptr_low)
  415. arena->ReleaseView(*views[i].out_ptr_low, views[i].size);
  416. if (*views[i].out_ptr && (views[i].out_ptr_low && *views[i].out_ptr != *views[i].out_ptr_low))
  417. arena->ReleaseView(*views[i].out_ptr, views[i].size);
  418. *views[i].out_ptr = NULL;
  419. if (views[i].out_ptr_low)
  420. *views[i].out_ptr_low = NULL;
  421. }
  422. }