malloc.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  1. /* StarPU --- Runtime system for heterogeneous multicore architectures.
  2. *
  3. * Copyright (C) 2011-2014,2016,2017 Inria
  4. * Copyright (C) 2018 Federal University of Rio Grande do Sul (UFRGS)
  5. * Copyright (C) 2010-2017, 2019 CNRS
  6. * Copyright (C) 2009-2019 Université de Bordeaux
  7. *
  8. * StarPU is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU Lesser General Public License as published by
  10. * the Free Software Foundation; either version 2.1 of the License, or (at
  11. * your option) any later version.
  12. *
  13. * StarPU is distributed in the hope that it will be useful, but
  14. * WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  16. *
  17. * See the GNU Lesser General Public License in COPYING.LGPL for more details.
  18. */
  19. #include <errno.h>
  20. #include <core/workers.h>
  21. #include <core/disk.h>
  22. #include <common/config.h>
  23. #include <common/fxt.h>
  24. #include <starpu.h>
  25. #include <drivers/opencl/driver_opencl.h>
  26. #include <datawizard/memory_manager.h>
  27. #include <datawizard/memory_nodes.h>
  28. #include <datawizard/malloc.h>
  29. #include <core/simgrid.h>
  30. #include <core/task.h>
  31. #ifdef STARPU_SIMGRID
  32. #include <sys/mman.h>
  33. #include <fcntl.h>
  34. #include <smpi/smpi.h>
  35. #endif
  36. #ifdef STARPU_HAVE_HWLOC
  37. #include <hwloc.h>
  38. #ifndef HWLOC_API_VERSION
  39. #define HWLOC_OBJ_PU HWLOC_OBJ_PROC
  40. #endif
  41. #if HWLOC_API_VERSION < 0x00010b00
  42. #define HWLOC_OBJ_NUMANODE HWLOC_OBJ_NODE
  43. #endif
  44. #endif
  45. #ifndef O_BINARY
  46. #define O_BINARY 0
  47. #endif
  48. #ifndef MAP_POPULATE
  49. #define MAP_POPULATE 0
  50. #endif
  51. static size_t _malloc_align = sizeof(void*);
  52. static int disable_pinning;
  53. static int malloc_on_node_default_flags[STARPU_MAXNODES];
  54. /* This file is used for implementing "folded" allocation */
  55. #ifdef STARPU_SIMGRID
  56. static int bogusfile = -1;
  57. static unsigned long _starpu_malloc_simulation_fold;
  58. #endif
  59. static starpu_malloc_hook malloc_hook;
  60. static starpu_free_hook free_hook;
  61. void starpu_malloc_set_hooks(starpu_malloc_hook _malloc_hook, starpu_free_hook _free_hook)
  62. {
  63. malloc_hook = _malloc_hook;
  64. free_hook = _free_hook;
  65. }
  66. void starpu_malloc_set_align(size_t align)
  67. {
  68. STARPU_ASSERT_MSG(!(align & (align - 1)), "Alignment given to starpu_malloc_set_align (%lu) must be a power of two", (unsigned long) align);
  69. if (_malloc_align < align)
  70. _malloc_align = align;
  71. }
  72. #if (defined(STARPU_USE_CUDA) && !defined(STARPU_HAVE_CUDA_MEMCPY_PEER))// || defined(STARPU_USE_OPENCL)
  73. struct malloc_pinned_codelet_struct
  74. {
  75. void **ptr;
  76. size_t dim;
  77. };
  78. #endif
  79. /* Would be difficult to do it this way, we need to remember the cl_mem to be able to free it later... */
  80. //#ifdef STARPU_USE_OPENCL
  81. //static void malloc_pinned_opencl_codelet(void *buffers[] STARPU_ATTRIBUTE_UNUSED, void *arg)
  82. //{
  83. // struct malloc_pinned_codelet_struct *s = arg;
  84. // // _STARPU_MALLOC(*(s->ptr), s->dim);
  85. // starpu_opencl_allocate_memory(devid, (void **)(s->ptr), s->dim, CL_MEM_READ_WRITE|CL_MEM_ALLOC_HOST_PTR);
  86. //}
  87. //#endif
  88. #if defined(STARPU_USE_CUDA) && !defined(STARPU_HAVE_CUDA_MEMCPY_PEER) && !defined(STARPU_SIMGRID)
  89. static void malloc_pinned_cuda_codelet(void *buffers[] STARPU_ATTRIBUTE_UNUSED, void *arg)
  90. {
  91. struct malloc_pinned_codelet_struct *s = arg;
  92. cudaError_t cures;
  93. cures = cudaHostAlloc((void **)(s->ptr), s->dim, cudaHostAllocPortable);
  94. if (STARPU_UNLIKELY(cures))
  95. STARPU_CUDA_REPORT_ERROR(cures);
  96. }
  97. #endif
  98. #if (defined(STARPU_USE_CUDA) && !defined(STARPU_HAVE_CUDA_MEMCPY_PEER)) && !defined(STARPU_SIMGRID)// || defined(STARPU_USE_OPENCL)
  99. static struct starpu_perfmodel malloc_pinned_model =
  100. {
  101. .type = STARPU_HISTORY_BASED,
  102. .symbol = "malloc_pinned"
  103. };
  104. static struct starpu_codelet malloc_pinned_cl =
  105. {
  106. .cuda_funcs = {malloc_pinned_cuda_codelet},
  107. //#ifdef STARPU_USE_OPENCL
  108. // .opencl_funcs = {malloc_pinned_opencl_codelet},
  109. //#endif
  110. .nbuffers = 0,
  111. .model = &malloc_pinned_model
  112. };
  113. #endif
  114. /* Allocation in CPU RAM */
  115. int starpu_malloc_flags(void **A, size_t dim, int flags)
  116. {
  117. return _starpu_malloc_flags_on_node(STARPU_MAIN_RAM, A, dim, flags);
  118. }
  119. /* Return whether we should pin the allocated data */
  120. static int _starpu_malloc_should_pin(int flags)
  121. {
  122. if (flags & STARPU_MALLOC_PINNED && disable_pinning <= 0)
  123. {
  124. if (_starpu_can_submit_cuda_task())
  125. {
  126. return 1;
  127. }
  128. // if (_starpu_can_submit_opencl_task())
  129. // return 1;
  130. }
  131. return 0;
  132. }
  133. int _starpu_malloc_flags_on_node(unsigned dst_node, void **A, size_t dim, int flags)
  134. {
  135. int ret=0;
  136. STARPU_ASSERT(A);
  137. if (flags & STARPU_MALLOC_COUNT)
  138. {
  139. if (!(flags & STARPU_MALLOC_NORECLAIM))
  140. while (starpu_memory_allocate(dst_node, dim, flags) != 0)
  141. {
  142. size_t freed;
  143. size_t reclaim = 2 * dim;
  144. _STARPU_DEBUG("There is not enough memory left, we are going to reclaim %ld\n", (long)reclaim);
  145. _STARPU_TRACE_START_MEMRECLAIM(dst_node,0);
  146. freed = _starpu_memory_reclaim_generic(dst_node, 0, reclaim);
  147. _STARPU_TRACE_END_MEMRECLAIM(dst_node,0);
  148. if (freed < dim && !(flags & STARPU_MEMORY_WAIT))
  149. {
  150. // We could not reclaim enough memory
  151. *A = NULL;
  152. return -ENOMEM;
  153. }
  154. }
  155. else if (flags & STARPU_MEMORY_WAIT)
  156. starpu_memory_allocate(dst_node, dim, flags);
  157. else
  158. starpu_memory_allocate(dst_node, dim, flags | STARPU_MEMORY_OVERFLOW);
  159. }
  160. if (malloc_hook)
  161. {
  162. ret = malloc_hook(dst_node, A, dim, flags);
  163. goto end;
  164. }
  165. if (_starpu_malloc_should_pin(flags) && STARPU_RUNNING_ON_VALGRIND == 0)
  166. {
  167. if (_starpu_can_submit_cuda_task())
  168. {
  169. #ifdef STARPU_SIMGRID
  170. /* FIXME: CUDA seems to be taking 650µs every 1MiB.
  171. * Ideally we would simulate this batching in 1MiB requests
  172. * instead of computing an average value.
  173. */
  174. if (_starpu_simgrid_cuda_malloc_cost())
  175. starpu_sleep((float) dim * 0.000650 / 1048576.);
  176. #else /* STARPU_SIMGRID */
  177. #ifdef STARPU_USE_CUDA
  178. #ifdef STARPU_HAVE_CUDA_MEMCPY_PEER
  179. cudaError_t cures;
  180. cures = cudaHostAlloc(A, dim, cudaHostAllocPortable);
  181. if (STARPU_UNLIKELY(cures))
  182. {
  183. STARPU_CUDA_REPORT_ERROR(cures);
  184. ret = -ENOMEM;
  185. }
  186. goto end;
  187. #else
  188. int push_res;
  189. /* Old versions of CUDA are not thread-safe, we have to
  190. * run cudaHostAlloc from CUDA workers */
  191. STARPU_ASSERT_MSG(_starpu_worker_may_perform_blocking_calls(), "without CUDA peer allocation support, pinned allocation must not be done from task or callback");
  192. struct malloc_pinned_codelet_struct s =
  193. {
  194. .ptr = A,
  195. .dim = dim
  196. };
  197. malloc_pinned_cl.where = STARPU_CUDA;
  198. struct starpu_task *task = starpu_task_create();
  199. task->name = "cuda_malloc_pinned";
  200. task->callback_func = NULL;
  201. task->cl = &malloc_pinned_cl;
  202. task->cl_arg = &s;
  203. task->type = STARPU_TASK_TYPE_INTERNAL;
  204. task->synchronous = 1;
  205. _starpu_exclude_task_from_dag(task);
  206. push_res = _starpu_task_submit_internally(task);
  207. STARPU_ASSERT(push_res != -ENODEV);
  208. goto end;
  209. #endif /* STARPU_HAVE_CUDA_MEMCPY_PEER */
  210. #endif /* STARPU_USE_CUDA */
  211. // }
  212. // else if (_starpu_can_submit_opencl_task())
  213. // {
  214. //#ifdef STARPU_USE_OPENCL
  215. // int push_res;
  216. //
  217. // STARPU_ASSERT_MSG(_starpu_worker_may_perform_blocking_calls(), "pinned OpenCL allocation must not be done from task or callback");
  218. //
  219. // struct malloc_pinned_codelet_struct s =
  220. // {
  221. // .ptr = A,
  222. // .dim = dim
  223. // };
  224. //
  225. // malloc_pinned_cl.where = STARPU_OPENCL;
  226. // struct starpu_task *task = starpu_task_create();
  227. // task->name = "opencl_malloc_pinned";
  228. // task->callback_func = NULL;
  229. // task->cl = &malloc_pinned_cl;
  230. // task->cl_arg = &s;
  231. // task->synchronous = 1;
  232. // task->type = STARPU_TASK_TYPE_INTERNAL;
  233. //
  234. // _starpu_exclude_task_from_dag(task);
  235. //
  236. // push_res = _starpu_task_submit_internally(task);
  237. // STARPU_ASSERT(push_res != -ENODEV);
  238. // goto end;
  239. //#endif /* STARPU_USE_OPENCL */
  240. #endif /* STARPU_SIMGRID */
  241. }
  242. }
  243. #ifdef STARPU_SIMGRID
  244. if (flags & STARPU_MALLOC_SIMULATION_FOLDED)
  245. {
  246. #if SIMGRID_VERSION >= 31500 && SIMGRID_VERSION != 31559
  247. if (_starpu_simgrid_running_smpi())
  248. *A = SMPI_SHARED_MALLOC(dim);
  249. else
  250. #endif
  251. {
  252. /* Use "folded" allocation: the same file is mapped several
  253. * times contiguously, to get a memory area one can read/write,
  254. * without consuming memory */
  255. /* First reserve memory area */
  256. void *buf = mmap (NULL, dim, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
  257. unsigned i;
  258. if (buf == MAP_FAILED)
  259. {
  260. _STARPU_DISP("Warning: could not allocate %luMiB of memory, you need to run \"sysctl vm.overcommit_memory=1\" as root to allow so big allocations\n", (unsigned long) (dim >> 20));
  261. ret = -ENOMEM;
  262. *A = NULL;
  263. }
  264. else
  265. {
  266. if (bogusfile == -1)
  267. {
  268. char *path = starpu_getenv("TMPDIR");
  269. if (!path)
  270. path = starpu_getenv("TEMP");
  271. if (!path)
  272. path = starpu_getenv("TMP");
  273. if (!path)
  274. path = "/tmp";
  275. /* Create bogus file if not done already */
  276. char *name = _starpu_mktemp(path, O_RDWR | O_BINARY, &bogusfile);
  277. char *dumb;
  278. if (!name)
  279. {
  280. ret = errno;
  281. munmap(buf, dim);
  282. *A = NULL;
  283. goto end;
  284. }
  285. unlink(name);
  286. free(name);
  287. _STARPU_CALLOC(dumb, 1,_starpu_malloc_simulation_fold);
  288. write(bogusfile, dumb, _starpu_malloc_simulation_fold);
  289. free(dumb);
  290. }
  291. /* Map the bogus file in place of the anonymous memory */
  292. for (i = 0; i < dim / _starpu_malloc_simulation_fold; i++)
  293. {
  294. void *pos = (void*) ((unsigned long) buf + i * _starpu_malloc_simulation_fold);
  295. void *res = mmap(pos, _starpu_malloc_simulation_fold, PROT_READ|PROT_WRITE, MAP_FIXED|MAP_SHARED|MAP_POPULATE, bogusfile, 0);
  296. STARPU_ASSERT_MSG(res == pos, "Could not map folded virtual memory (%s). Do you perhaps need to increase the STARPU_MALLOC_SIMULATION_FOLD environment variable or the sysctl vm.max_map_count?", strerror(errno));
  297. }
  298. if (dim % _starpu_malloc_simulation_fold)
  299. {
  300. void *pos = (void*) ((unsigned long) buf + i * _starpu_malloc_simulation_fold);
  301. void *res = mmap(pos, dim % _starpu_malloc_simulation_fold, PROT_READ|PROT_WRITE, MAP_FIXED|MAP_SHARED|MAP_POPULATE, bogusfile, 0);
  302. STARPU_ASSERT_MSG(res == pos, "Could not map folded virtual memory (%s). Do you perhaps need to increase the STARPU_MALLOC_SIMULATION_FOLD environment variable or the sysctl vm.max_map_count?", strerror(errno));
  303. }
  304. *A = buf;
  305. }
  306. }
  307. }
  308. #endif
  309. #ifdef STARPU_HAVE_HWLOC
  310. if (starpu_memory_nodes_get_numa_count() > 1)
  311. {
  312. struct _starpu_machine_config *config = _starpu_get_machine_config();
  313. hwloc_topology_t hwtopology = config->topology.hwtopology;
  314. hwloc_obj_t numa_node_obj = hwloc_get_obj_by_type(hwtopology, HWLOC_OBJ_NUMANODE, starpu_memory_nodes_numa_id_to_hwloclogid(dst_node));
  315. hwloc_bitmap_t nodeset = numa_node_obj->nodeset;
  316. #if HWLOC_API_VERSION >= 0x00020000
  317. *A = hwloc_alloc_membind(hwtopology, dim, nodeset, HWLOC_MEMBIND_BIND, HWLOC_MEMBIND_BYNODESET | HWLOC_MEMBIND_NOCPUBIND);
  318. #else
  319. *A = hwloc_alloc_membind_nodeset(hwtopology, dim, nodeset, HWLOC_MEMBIND_BIND, HWLOC_MEMBIND_NOCPUBIND);
  320. #endif
  321. //fprintf(stderr, "Allocation %lu bytes on NUMA node %d [%p]\n", (unsigned long) dim, starpu_memnode_get_numaphysid(dst_node), *A);
  322. if (!*A)
  323. ret = -ENOMEM;
  324. }
  325. #endif /* STARPU_HAVE_HWLOC */
  326. else
  327. #ifdef STARPU_HAVE_POSIX_MEMALIGN
  328. if (_malloc_align != sizeof(void*))
  329. {
  330. if (posix_memalign(A, _malloc_align, dim))
  331. {
  332. ret = -ENOMEM;
  333. *A = NULL;
  334. }
  335. }
  336. else
  337. #elif defined(STARPU_HAVE_MEMALIGN)
  338. if (_malloc_align != sizeof(void*))
  339. {
  340. *A = memalign(_malloc_align, dim);
  341. if (!*A)
  342. ret = -ENOMEM;
  343. }
  344. else
  345. #endif /* STARPU_HAVE_POSIX_MEMALIGN */
  346. {
  347. *A = malloc(dim);
  348. if (!*A)
  349. ret = -ENOMEM;
  350. }
  351. end:
  352. if (ret == 0)
  353. {
  354. STARPU_ASSERT_MSG(*A, "Failed to allocated memory of size %lu b\n", (unsigned long)dim);
  355. }
  356. else if (flags & STARPU_MALLOC_COUNT)
  357. {
  358. starpu_memory_deallocate(dst_node, dim);
  359. }
  360. return ret;
  361. }
  362. int starpu_malloc(void **A, size_t dim)
  363. {
  364. return starpu_malloc_flags(A, dim, STARPU_MALLOC_PINNED);
  365. }
  366. #if defined(STARPU_USE_CUDA) && !defined(STARPU_HAVE_CUDA_MEMCPY_PEER) && !defined(STARPU_SIMGRID)
  367. static void free_pinned_cuda_codelet(void *buffers[] STARPU_ATTRIBUTE_UNUSED, void *arg)
  368. {
  369. cudaError_t cures;
  370. cures = cudaFreeHost(arg);
  371. if (STARPU_UNLIKELY(cures))
  372. STARPU_CUDA_REPORT_ERROR(cures);
  373. }
  374. #endif
  375. //#ifdef STARPU_USE_OPENCL
  376. //static void free_pinned_opencl_codelet(void *buffers[] STARPU_ATTRIBUTE_UNUSED, void *arg)
  377. //{
  378. // // free(arg);
  379. // int err = clReleaseMemObject(arg);
  380. // if (err != CL_SUCCESS) STARPU_OPENCL_REPORT_ERROR(err);
  381. //}
  382. //#endif
  383. #if defined(STARPU_USE_CUDA) && !defined(STARPU_HAVE_CUDA_MEMCPY_PEER) && !defined(STARPU_SIMGRID) // || defined(STARPU_USE_OPENCL)
  384. static struct starpu_perfmodel free_pinned_model =
  385. {
  386. .type = STARPU_HISTORY_BASED,
  387. .symbol = "free_pinned"
  388. };
  389. static struct starpu_codelet free_pinned_cl =
  390. {
  391. .cuda_funcs = {free_pinned_cuda_codelet},
  392. //#ifdef STARPU_USE_OPENCL
  393. // .opencl_funcs = {free_pinned_opencl_codelet},
  394. //#endif
  395. .nbuffers = 0,
  396. .model = &free_pinned_model
  397. };
  398. #endif
  399. int starpu_free_flags(void *A, size_t dim, int flags)
  400. {
  401. return _starpu_free_flags_on_node(STARPU_MAIN_RAM, A, dim, flags);
  402. }
  403. int _starpu_free_flags_on_node(unsigned dst_node, void *A, size_t dim, int flags)
  404. {
  405. if (free_hook)
  406. {
  407. free_hook(dst_node, A, dim, flags);
  408. goto out;
  409. }
  410. if (_starpu_malloc_should_pin(flags) && STARPU_RUNNING_ON_VALGRIND == 0)
  411. {
  412. if (_starpu_can_submit_cuda_task())
  413. {
  414. #ifdef STARPU_SIMGRID
  415. /* TODO: simulate CUDA barrier */
  416. #else /* !STARPU_SIMGRID */
  417. #ifdef STARPU_USE_CUDA
  418. #ifndef STARPU_HAVE_CUDA_MEMCPY_PEER
  419. if (!starpu_is_initialized())
  420. {
  421. #endif
  422. /* This is especially useful when starpu_free is called even
  423. * though starpu_shutdown has already
  424. * been called, so we will not be able to submit a task. */
  425. cudaError_t err = cudaFreeHost(A);
  426. if (STARPU_UNLIKELY(err))
  427. STARPU_CUDA_REPORT_ERROR(err);
  428. goto out;
  429. #ifndef STARPU_HAVE_CUDA_MEMCPY_PEER
  430. }
  431. else
  432. {
  433. int push_res;
  434. STARPU_ASSERT_MSG(_starpu_worker_may_perform_blocking_calls(), "without CUDA peer allocation support, pinned deallocation must not be done from task or callback");
  435. free_pinned_cl.where = STARPU_CUDA;
  436. struct starpu_task *task = starpu_task_create();
  437. task->name = "cuda_free_pinned";
  438. task->callback_func = NULL;
  439. task->cl = &free_pinned_cl;
  440. task->cl_arg = A;
  441. task->synchronous = 1;
  442. task->type = STARPU_TASK_TYPE_INTERNAL;
  443. _starpu_exclude_task_from_dag(task);
  444. push_res = _starpu_task_submit_internally(task);
  445. STARPU_ASSERT(push_res != -ENODEV);
  446. goto out;
  447. }
  448. #endif /* STARPU_HAVE_CUDA_MEMCPY_PEER */
  449. #endif /* STARPU_USE_CUDA */
  450. #endif /* STARPU_SIMGRID */
  451. }
  452. // else if (_starpu_can_submit_opencl_task())
  453. // {
  454. //#ifdef STARPU_USE_OPENCL
  455. // int push_res;
  456. //
  457. // STARPU_ASSERT_MSG(_starpu_worker_may_perform_blocking_calls(), "pinned OpenCL deallocation must not be done from task or callback");
  458. //
  459. // free_pinned_cl.where = STARPU_OPENCL;
  460. // struct starpu_task *task = starpu_task_create();
  461. // task->name = "opencl_free_pinned";
  462. // task->callback_func = NULL;
  463. // task->cl = &free_pinned_cl;
  464. // task->cl_arg = A;
  465. // task->synchronous = 1;
  466. // task->type = STARPU_TASK_TYPE_INTERNAL;
  467. //
  468. // _starpu_exclude_task_from_dag(task);
  469. //
  470. // push_res = starpu_task_submit(task);
  471. // STARPU_ASSERT(push_res != -ENODEV);
  472. // goto out;
  473. // }
  474. //#endif
  475. }
  476. #ifdef STARPU_SIMGRID
  477. if (flags & STARPU_MALLOC_SIMULATION_FOLDED)
  478. {
  479. #if SIMGRID_VERSION >= 31500 && SIMGRID_VERSION != 31559
  480. if (_starpu_simgrid_running_smpi())
  481. SMPI_SHARED_FREE(A);
  482. else
  483. #endif
  484. munmap(A, dim);
  485. }
  486. #endif
  487. #ifdef STARPU_HAVE_HWLOC
  488. else if (starpu_memory_nodes_get_numa_count() > 1)
  489. {
  490. struct _starpu_machine_config *config = _starpu_get_machine_config();
  491. hwloc_topology_t hwtopology = config->topology.hwtopology;
  492. hwloc_free(hwtopology, A, dim);
  493. }
  494. #endif /* STARPU_HAVE_HWLOC */
  495. else
  496. free(A);
  497. out:
  498. if (flags & STARPU_MALLOC_COUNT)
  499. {
  500. starpu_memory_deallocate(dst_node, dim);
  501. }
  502. return 0;
  503. }
  504. int starpu_free(void *A)
  505. {
  506. return starpu_free_flags(A, 0, STARPU_MALLOC_PINNED);
  507. }
  508. static uintptr_t _starpu_malloc_on_node(unsigned dst_node, size_t size, int flags)
  509. {
  510. uintptr_t addr = 0;
  511. /* Handle count first */
  512. if (flags & STARPU_MALLOC_COUNT)
  513. {
  514. if (starpu_memory_allocate(dst_node, size, flags) != 0)
  515. return 0;
  516. /* And prevent double-count in starpu_malloc_flags */
  517. flags &= ~STARPU_MALLOC_COUNT;
  518. }
  519. struct _starpu_node_ops *node_ops = _starpu_memory_node_get_node_ops(dst_node);
  520. if (node_ops && node_ops->malloc_on_node)
  521. addr = node_ops->malloc_on_node(dst_node, size, flags & ~STARPU_MALLOC_COUNT);
  522. else
  523. STARPU_ABORT_MSG("No malloc_on_node function defined for node %s\n", _starpu_node_get_prefix(starpu_node_get_kind(dst_node)));
  524. if (addr == 0)
  525. {
  526. // Allocation failed, gives the memory back to the memory manager
  527. _STARPU_TRACE_MEMORY_FULL(size);
  528. if (flags & STARPU_MALLOC_COUNT)
  529. starpu_memory_deallocate(dst_node, size);
  530. }
  531. return addr;
  532. }
  533. void _starpu_free_on_node_flags(unsigned dst_node, uintptr_t addr, size_t size, int flags)
  534. {
  535. int count = flags & STARPU_MALLOC_COUNT;
  536. flags &= ~STARPU_MALLOC_COUNT;
  537. struct _starpu_node_ops *node_ops = _starpu_memory_node_get_node_ops(dst_node);
  538. if (node_ops && node_ops->free_on_node)
  539. node_ops->free_on_node(dst_node, addr, size, flags);
  540. else
  541. STARPU_ABORT_MSG("No free_on_node function defined for node %s\n", _starpu_node_get_prefix(starpu_node_get_kind(dst_node)));
  542. if (count)
  543. starpu_memory_deallocate(dst_node, size);
  544. }
  545. int
  546. starpu_memory_pin(void *addr STARPU_ATTRIBUTE_UNUSED, size_t size STARPU_ATTRIBUTE_UNUSED)
  547. {
  548. if (STARPU_MALLOC_PINNED && disable_pinning <= 0 && STARPU_RUNNING_ON_VALGRIND == 0)
  549. {
  550. #if defined(STARPU_USE_CUDA) && defined(STARPU_HAVE_CUDA_MEMCPY_PEER)
  551. if (cudaHostRegister(addr, size, cudaHostRegisterPortable) != cudaSuccess)
  552. return -1;
  553. #endif
  554. }
  555. return 0;
  556. }
  557. int
  558. starpu_memory_unpin(void *addr STARPU_ATTRIBUTE_UNUSED, size_t size STARPU_ATTRIBUTE_UNUSED)
  559. {
  560. if (STARPU_MALLOC_PINNED && disable_pinning <= 0 && STARPU_RUNNING_ON_VALGRIND == 0)
  561. {
  562. #if defined(STARPU_USE_CUDA) && defined(STARPU_HAVE_CUDA_MEMCPY_PEER)
  563. if (cudaHostUnregister(addr) != cudaSuccess)
  564. return -1;
  565. #endif
  566. }
  567. return 0;
  568. }
  569. /*
  570. * On CUDA which has very expensive malloc, for small sizes, allocate big
  571. * chunks divided in blocks, and we actually allocate segments of consecutive
  572. * blocks.
  573. *
  574. * We try to keep the list of chunks with increasing occupancy, so we can
  575. * quickly find free segments to allocate.
  576. */
  577. /* Size of each chunk, 32MiB granularity brings 128 chunks to be allocated in
  578. * order to fill a 4GiB GPU. */
  579. #define CHUNK_SIZE (32*1024*1024)
  580. /* Maximum segment size we will allocate in chunks */
  581. #define CHUNK_ALLOC_MAX (CHUNK_SIZE / 8)
  582. /* Granularity of allocation, i.e. block size, StarPU will never allocate less
  583. * than this.
  584. * 16KiB (i.e. 64x64 float) granularity eats 2MiB RAM for managing a 4GiB GPU.
  585. */
  586. #define CHUNK_ALLOC_MIN (16*1024)
  587. /* Don't really deallocate chunks unless we have more than this many chunks
  588. * which are completely free. */
  589. #define CHUNKS_NFREE 4
  590. /* Number of blocks */
  591. #define CHUNK_NBLOCKS (CHUNK_SIZE/CHUNK_ALLOC_MIN)
  592. /* Linked list for available segments */
  593. struct block
  594. {
  595. int length; /* Number of consecutive free blocks */
  596. int next; /* next free segment */
  597. };
  598. /* One chunk */
  599. LIST_TYPE(_starpu_chunk,
  600. uintptr_t base;
  601. /* Available number of blocks, for debugging */
  602. int available;
  603. /* Overestimation of the maximum size of available segments in this chunk */
  604. int available_max;
  605. /* Bitmap describing availability of the block */
  606. /* Block 0 is always empty, and is just the head of the free segments list */
  607. struct block bitmap[CHUNK_NBLOCKS+1];
  608. )
  609. /* One list of chunks per node */
  610. static struct _starpu_chunk_list chunks[STARPU_MAXNODES];
  611. /* Number of completely free chunks */
  612. static int nfreechunks[STARPU_MAXNODES];
  613. /* This protects chunks and nfreechunks */
  614. static starpu_pthread_mutex_t chunk_mutex[STARPU_MAXNODES];
  615. void
  616. _starpu_malloc_init(unsigned dst_node)
  617. {
  618. _starpu_chunk_list_init(&chunks[dst_node]);
  619. nfreechunks[dst_node] = 0;
  620. STARPU_PTHREAD_MUTEX_INIT(&chunk_mutex[dst_node], NULL);
  621. disable_pinning = starpu_get_env_number("STARPU_DISABLE_PINNING");
  622. malloc_on_node_default_flags[dst_node] = STARPU_MALLOC_PINNED | STARPU_MALLOC_COUNT;
  623. #ifdef STARPU_SIMGRID
  624. /* Reasonably "costless" */
  625. _starpu_malloc_simulation_fold = starpu_get_env_number_default("STARPU_MALLOC_SIMULATION_FOLD", 1) << 20;
  626. #endif
  627. }
  628. void
  629. _starpu_malloc_shutdown(unsigned dst_node)
  630. {
  631. struct _starpu_chunk *chunk, *next_chunk;
  632. STARPU_PTHREAD_MUTEX_LOCK(&chunk_mutex[dst_node]);
  633. for (chunk = _starpu_chunk_list_begin(&chunks[dst_node]);
  634. chunk != _starpu_chunk_list_end(&chunks[dst_node]);
  635. chunk = next_chunk)
  636. {
  637. next_chunk = _starpu_chunk_list_next(chunk);
  638. _starpu_free_on_node_flags(dst_node, chunk->base, CHUNK_SIZE, malloc_on_node_default_flags[dst_node]);
  639. _starpu_chunk_list_erase(&chunks[dst_node], chunk);
  640. free(chunk);
  641. }
  642. STARPU_PTHREAD_MUTEX_UNLOCK(&chunk_mutex[dst_node]);
  643. STARPU_PTHREAD_MUTEX_DESTROY(&chunk_mutex[dst_node]);
  644. }
  645. /* Create a new chunk */
  646. static struct _starpu_chunk *_starpu_new_chunk(unsigned dst_node, int flags)
  647. {
  648. struct _starpu_chunk *chunk;
  649. uintptr_t base = _starpu_malloc_on_node(dst_node, CHUNK_SIZE, flags);
  650. if (!base)
  651. return NULL;
  652. /* Create a new chunk */
  653. chunk = _starpu_chunk_new();
  654. chunk->base = base;
  655. /* First block is just a fake block pointing to the free segments list */
  656. chunk->bitmap[0].length = 0;
  657. chunk->bitmap[0].next = 1;
  658. /* At first we have only one big segment for the whole chunk */
  659. chunk->bitmap[1].length = CHUNK_NBLOCKS;
  660. chunk->bitmap[1].next = -1;
  661. chunk->available_max = CHUNK_NBLOCKS;
  662. chunk->available = CHUNK_NBLOCKS;
  663. return chunk;
  664. }
  665. /* Return whether we should use our suballocator */
  666. static int _starpu_malloc_should_suballoc(unsigned dst_node, size_t size, int flags)
  667. {
  668. return size <= CHUNK_ALLOC_MAX &&
  669. (starpu_node_get_kind(dst_node) == STARPU_CUDA_RAM
  670. || (starpu_node_get_kind(dst_node) == STARPU_CPU_RAM
  671. && _starpu_malloc_should_pin(flags))
  672. );
  673. }
  674. uintptr_t
  675. starpu_malloc_on_node_flags(unsigned dst_node, size_t size, int flags)
  676. {
  677. /* Big allocation, allocate normally */
  678. if (!_starpu_malloc_should_suballoc(dst_node, size, flags))
  679. return _starpu_malloc_on_node(dst_node, size, flags);
  680. /* Round up allocation to block size */
  681. int nblocks = (size + CHUNK_ALLOC_MIN - 1) / CHUNK_ALLOC_MIN;
  682. struct _starpu_chunk *chunk;
  683. int prevblock, block;
  684. int available_max;
  685. struct block *bitmap;
  686. STARPU_PTHREAD_MUTEX_LOCK(&chunk_mutex[dst_node]);
  687. /* Try to find a big enough segment among the chunks */
  688. for (chunk = _starpu_chunk_list_begin(&chunks[dst_node]);
  689. chunk != _starpu_chunk_list_end(&chunks[dst_node]);
  690. chunk = _starpu_chunk_list_next(chunk))
  691. {
  692. if (chunk->available_max < nblocks)
  693. continue;
  694. bitmap = chunk->bitmap;
  695. available_max = 0;
  696. for (prevblock = block = 0;
  697. block != -1;
  698. prevblock = block, block = bitmap[prevblock].next)
  699. {
  700. STARPU_ASSERT(block >= 0 && block <= CHUNK_NBLOCKS);
  701. int length = bitmap[block].length;
  702. if (length >= nblocks)
  703. {
  704. if (length >= 2*nblocks)
  705. {
  706. /* This one this has quite some room,
  707. * put it front, to make finding it
  708. * easier next time. */
  709. _starpu_chunk_list_erase(&chunks[dst_node], chunk);
  710. _starpu_chunk_list_push_front(&chunks[dst_node], chunk);
  711. }
  712. if (chunk->available == CHUNK_NBLOCKS)
  713. /* This one was empty, it's not empty any more */
  714. nfreechunks[dst_node]--;
  715. goto found;
  716. }
  717. if (length > available_max)
  718. available_max = length;
  719. }
  720. /* Didn't find a big enough segment in this chunk, its
  721. * available_max is out of date */
  722. chunk->available_max = available_max;
  723. }
  724. /* Didn't find a big enough segment, create another chunk. */
  725. chunk = _starpu_new_chunk(dst_node, flags);
  726. if (!chunk)
  727. {
  728. /* Really no memory any more, fail */
  729. STARPU_PTHREAD_MUTEX_UNLOCK(&chunk_mutex[dst_node]);
  730. errno = ENOMEM;
  731. return 0;
  732. }
  733. /* And make it easy to find. */
  734. _starpu_chunk_list_push_front(&chunks[dst_node], chunk);
  735. bitmap = chunk->bitmap;
  736. prevblock = 0;
  737. block = 1;
  738. found:
  739. chunk->available -= nblocks;
  740. STARPU_ASSERT(bitmap[block].length >= nblocks);
  741. STARPU_ASSERT(block <= CHUNK_NBLOCKS);
  742. if (bitmap[block].length == nblocks)
  743. {
  744. /* Fits exactly, drop this segment from the skip list */
  745. bitmap[prevblock].next = bitmap[block].next;
  746. }
  747. else
  748. {
  749. /* Still some room */
  750. STARPU_ASSERT(block + nblocks <= CHUNK_NBLOCKS);
  751. bitmap[prevblock].next = block + nblocks;
  752. bitmap[block + nblocks].length = bitmap[block].length - nblocks;
  753. bitmap[block + nblocks].next = bitmap[block].next;
  754. }
  755. STARPU_PTHREAD_MUTEX_UNLOCK(&chunk_mutex[dst_node]);
  756. return chunk->base + (block-1) * CHUNK_ALLOC_MIN;
  757. }
  758. void
  759. starpu_free_on_node_flags(unsigned dst_node, uintptr_t addr, size_t size, int flags)
  760. {
  761. /* Big allocation, deallocate normally */
  762. if (!_starpu_malloc_should_suballoc(dst_node, size, flags))
  763. {
  764. _starpu_free_on_node_flags(dst_node, addr, size, flags);
  765. return;
  766. }
  767. struct _starpu_chunk *chunk;
  768. /* Round up allocation to block size */
  769. int nblocks = (size + CHUNK_ALLOC_MIN - 1) / CHUNK_ALLOC_MIN;
  770. STARPU_PTHREAD_MUTEX_LOCK(&chunk_mutex[dst_node]);
  771. for (chunk = _starpu_chunk_list_begin(&chunks[dst_node]);
  772. chunk != _starpu_chunk_list_end(&chunks[dst_node]);
  773. chunk = _starpu_chunk_list_next(chunk))
  774. if (addr >= chunk->base && addr < chunk->base + CHUNK_SIZE)
  775. break;
  776. STARPU_ASSERT(chunk != _starpu_chunk_list_end(&chunks[dst_node]));
  777. struct block *bitmap = chunk->bitmap;
  778. int block = ((addr - chunk->base) / CHUNK_ALLOC_MIN) + 1, prevblock, nextblock;
  779. /* Look for free segment just before this one */
  780. for (prevblock = 0;
  781. prevblock != -1;
  782. prevblock = nextblock)
  783. {
  784. STARPU_ASSERT(prevblock >= 0 && prevblock <= CHUNK_NBLOCKS);
  785. nextblock = bitmap[prevblock].next;
  786. STARPU_ASSERT_MSG(nextblock != block, "It seems data 0x%lx (size %u) on node %u is being freed a second time\n", (unsigned long) addr, (unsigned) size, dst_node);
  787. if (nextblock > block || nextblock == -1)
  788. break;
  789. }
  790. STARPU_ASSERT(prevblock != -1);
  791. chunk->available += nblocks;
  792. /* Insert in free segments list */
  793. bitmap[block].next = nextblock;
  794. bitmap[prevblock].next = block;
  795. bitmap[block].length = nblocks;
  796. STARPU_ASSERT(nextblock >= -1 && nextblock <= CHUNK_NBLOCKS);
  797. if (nextblock == block + nblocks)
  798. {
  799. /* This freed segment is just before a free segment, merge them */
  800. bitmap[block].next = bitmap[nextblock].next;
  801. bitmap[block].length += bitmap[nextblock].length;
  802. if (bitmap[block].length > chunk->available_max)
  803. chunk->available_max = bitmap[block].length;
  804. }
  805. if (prevblock > 0 && prevblock + bitmap[prevblock].length == block)
  806. {
  807. /* This free segment is just after a free segment, merge them */
  808. bitmap[prevblock].next = bitmap[block].next;
  809. bitmap[prevblock].length += bitmap[block].length;
  810. if (bitmap[prevblock].length > chunk->available_max)
  811. chunk->available_max = bitmap[prevblock].length;
  812. block = prevblock;
  813. }
  814. if (chunk->available == CHUNK_NBLOCKS)
  815. {
  816. /* This chunk is now empty, but avoid chunk free/alloc
  817. * ping-pong by keeping some of these. */
  818. if (nfreechunks[dst_node] >= CHUNKS_NFREE)
  819. {
  820. /* We already have free chunks, release this one */
  821. _starpu_free_on_node_flags(dst_node, chunk->base, CHUNK_SIZE, flags);
  822. _starpu_chunk_list_erase(&chunks[dst_node], chunk);
  823. free(chunk);
  824. }
  825. else
  826. nfreechunks[dst_node]++;
  827. }
  828. else
  829. {
  830. /* Freed some room, put this first in chunks list */
  831. _starpu_chunk_list_erase(&chunks[dst_node], chunk);
  832. _starpu_chunk_list_push_front(&chunks[dst_node], chunk);
  833. }
  834. STARPU_PTHREAD_MUTEX_UNLOCK(&chunk_mutex[dst_node]);
  835. }
  836. void starpu_malloc_on_node_set_default_flags(unsigned node, int flags)
  837. {
  838. STARPU_ASSERT_MSG(node < STARPU_MAXNODES, "bogus node value %u given to starpu_malloc_on_node_set_default_flags\n", node);
  839. malloc_on_node_default_flags[node] = flags;
  840. }
  841. uintptr_t
  842. starpu_malloc_on_node(unsigned dst_node, size_t size)
  843. {
  844. return starpu_malloc_on_node_flags(dst_node, size, malloc_on_node_default_flags[dst_node]);
  845. }
  846. void
  847. starpu_free_on_node(unsigned dst_node, uintptr_t addr, size_t size)
  848. {
  849. starpu_free_on_node_flags(dst_node, addr, size, malloc_on_node_default_flags[dst_node]);
  850. }