malloc.c 31 KB

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