mem_arena.cpp 13 KB

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