offload_engine.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  1. /*
  2. Copyright (c) 2014-2016 Intel Corporation. All Rights Reserved.
  3. Redistribution and use in source and binary forms, with or without
  4. modification, are permitted provided that the following conditions
  5. are met:
  6. * Redistributions of source code must retain the above copyright
  7. notice, this list of conditions and the following disclaimer.
  8. * Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in the
  10. documentation and/or other materials provided with the distribution.
  11. * Neither the name of Intel Corporation nor the names of its
  12. contributors may be used to endorse or promote products derived
  13. from this software without specific prior written permission.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  15. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  16. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  17. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  18. HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  19. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  20. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  21. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  22. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "offload_engine.h"
  27. #include <signal.h>
  28. #include <errno.h>
  29. #include <sys/stat.h>
  30. #include <sys/types.h>
  31. #include <algorithm>
  32. #include <vector>
  33. #include "offload_host.h"
  34. #include "offload_table.h"
  35. #include "offload_iterator.h"
  36. #if defined(HOST_WINNT)
  37. #define PATH_SEPARATOR ";"
  38. #else
  39. #define PATH_SEPARATOR ":"
  40. #endif
  41. // Static members of Stream class must be described somewhere.
  42. // This members describe the list of all streams defined in programm
  43. // via call to _Offload_stream_create.
  44. uint64_t Stream::m_streams_count = 0;
  45. StreamMap Stream::all_streams;
  46. mutex_t Stream::m_stream_lock;
  47. char* mic_library_path = 0;
  48. const char* Engine::m_func_names[Engine::c_funcs_total] =
  49. {
  50. "server_compute",
  51. #ifdef MYO_SUPPORT
  52. "server_myoinit",
  53. "server_myofini",
  54. #endif // MYO_SUPPORT
  55. "server_init",
  56. "server_var_table_size",
  57. "server_var_table_copy",
  58. "server_set_stream_affinity"
  59. };
  60. // Symbolic representation of system signals. Fix for CQ233593
  61. const char* Engine::c_signal_names[Engine::c_signal_max] =
  62. {
  63. "Unknown SIGNAL",
  64. "SIGHUP", /* 1, Hangup (POSIX). */
  65. "SIGINT", /* 2, Interrupt (ANSI). */
  66. "SIGQUIT", /* 3, Quit (POSIX). */
  67. "SIGILL", /* 4, Illegal instruction (ANSI). */
  68. "SIGTRAP", /* 5, Trace trap (POSIX). */
  69. "SIGABRT", /* 6, Abort (ANSI). */
  70. "SIGBUS", /* 7, BUS error (4.2 BSD). */
  71. "SIGFPE", /* 8, Floating-point exception (ANSI). */
  72. "SIGKILL", /* 9, Kill, unblockable (POSIX). */
  73. "SIGUSR1", /* 10, User-defined signal 1 (POSIX). */
  74. "SIGSEGV", /* 11, Segmentation violation (ANSI). */
  75. "SIGUSR2", /* 12, User-defined signal 2 (POSIX). */
  76. "SIGPIPE", /* 13, Broken pipe (POSIX). */
  77. "SIGALRM", /* 14, Alarm clock (POSIX). */
  78. "SIGTERM", /* 15, Termination (ANSI). */
  79. "SIGSTKFLT", /* 16, Stack fault. */
  80. "SIGCHLD", /* 17, Child status has changed (POSIX). */
  81. "SIGCONT", /* 18, Continue (POSIX). */
  82. "SIGSTOP", /* 19, Stop, unblockable (POSIX). */
  83. "SIGTSTP", /* 20, Keyboard stop (POSIX). */
  84. "SIGTTIN", /* 21, Background read from tty (POSIX). */
  85. "SIGTTOU", /* 22, Background write to tty (POSIX). */
  86. "SIGURG", /* 23, Urgent condition on socket (4.2 BSD). */
  87. "SIGXCPU", /* 24, CPU limit exceeded (4.2 BSD). */
  88. "SIGXFSZ", /* 25, File size limit exceeded (4.2 BSD). */
  89. "SIGVTALRM", /* 26, Virtual alarm clock (4.2 BSD). */
  90. "SIGPROF", /* 27, Profiling alarm clock (4.2 BSD). */
  91. "SIGWINCH", /* 28, Window size change (4.3 BSD, Sun). */
  92. "SIGIO", /* 29, I/O now possible (4.2 BSD). */
  93. "SIGPWR", /* 30, Power failure restart (System V). */
  94. "SIGSYS" /* 31, Bad system call. */
  95. };
  96. void Engine::init(void)
  97. {
  98. if (!m_ready) {
  99. mutex_locker_t locker(m_lock);
  100. if (!m_ready) {
  101. // start process if not done yet
  102. if (m_process == 0) {
  103. init_process();
  104. }
  105. // load penging images
  106. load_libraries();
  107. // and (re)build pointer table
  108. init_ptr_data();
  109. // it is ready now
  110. m_ready = true;
  111. // Inform the debugger
  112. if (__dbg_is_attached) {
  113. __dbg_target_so_loaded();
  114. }
  115. }
  116. }
  117. }
  118. void Engine::print_stream_cpu_list(const char * str)
  119. {
  120. int count = 0;
  121. char buffer[1024];
  122. CpuEl* cpu_el = m_cpu_head;
  123. OFFLOAD_DEBUG_TRACE(3,
  124. "%s : cpu list as Index(Count) for the streams is :\n", str);
  125. buffer[0] = 0;
  126. for (int i = 0; i < m_num_threads; i++) {
  127. cpu_el = m_cpus + i;
  128. if (m_assigned_cpus == 0 || (*m_assigned_cpus)[i]) {
  129. count++;
  130. sprintf(buffer + strlen(buffer), "%d(%d) ", CPU_INDEX(cpu_el), cpu_el->count);
  131. if (count % 20 == 0) {
  132. OFFLOAD_DEBUG_TRACE(3, "%s\n", buffer);
  133. buffer[0] = 0;
  134. }
  135. }
  136. }
  137. if (count % 20 != 0) {
  138. OFFLOAD_DEBUG_TRACE(3, "%s\n", buffer);
  139. }
  140. }
  141. void Engine::init_process(void)
  142. {
  143. COIENGINE engine;
  144. COIRESULT res;
  145. const char **environ;
  146. char buf[4096]; // For exe path name
  147. char* mic_device_main = 0;
  148. // create environment for the target process
  149. environ = (const char**) mic_env_vars.create_environ_for_card(m_index);
  150. if (environ != 0) {
  151. for (const char **p = environ; *p != 0; p++) {
  152. OFFLOAD_DEBUG_TRACE(3, "Env Var for card %d: %s\n", m_index, *p);
  153. }
  154. }
  155. // Create execution context in the specified device
  156. OFFLOAD_DEBUG_TRACE(2, "Getting device %d (engine %d) handle\n", m_index,
  157. m_physical_index);
  158. res = COI::EngineGetHandle(COI_ISA_MIC, m_physical_index, &engine);
  159. check_result(res, c_get_engine_handle, m_index, res);
  160. // Get engine info on threads and cores.
  161. // The values of core number and thread number will be used later at stream
  162. // creation by call to _Offload_stream_create(device,number_of_cpus).
  163. COI_ENGINE_INFO engine_info;
  164. res = COI::EngineGetInfo(engine, sizeof(COI_ENGINE_INFO), &engine_info);
  165. check_result(res, c_get_engine_info, m_index, res);
  166. if (mic_library_path == 0 ) {
  167. if (engine_info.ISA == COI_DEVICE_KNC) {
  168. mic_library_path = knc_library_path;
  169. }
  170. else if (engine_info.ISA == COI_DEVICE_KNL) {
  171. mic_library_path = knl_library_path;
  172. }
  173. else {
  174. LIBOFFLOAD_ERROR(c_unknown_mic_device_type);
  175. }
  176. }
  177. // m_cpus is the list of all available threads.
  178. // At the begining all threads made available through OFFLOAD_DEVICES
  179. // or all threads existed at the engine if OFFLOAD_DEVICES isn't set.
  180. // m_cpu_head points to the head of the m_cpus list.
  181. // m_cpus is ordered by number of streams using the thread.
  182. // m_cpu_head points to the least used thread.
  183. // After creating and destroying a stream the m_cpus list must be fixed
  184. // to be ordered.
  185. m_cpus = (CpuEl*)malloc(engine_info.NumThreads * sizeof(CpuEl));
  186. if (m_cpus == NULL)
  187. LIBOFFLOAD_ERROR(c_malloc);
  188. memset(m_cpus, 0, engine_info.NumThreads * sizeof(CpuEl));
  189. CpuEl* prev_cpu = NULL;
  190. for (int i = 0; i < engine_info.NumThreads; i++) {
  191. if (m_assigned_cpus == 0 || (*m_assigned_cpus)[i]) {
  192. if (prev_cpu) {
  193. prev_cpu->next = m_cpus + i;
  194. }
  195. else {
  196. m_cpu_head = m_cpus + i;
  197. }
  198. m_cpus[i].prev = prev_cpu;
  199. m_cpus[i].count = 0;
  200. prev_cpu = m_cpus + i;
  201. }
  202. }
  203. // The following values will be used at pipeline creation for streams
  204. m_num_cores = engine_info.NumCores;
  205. m_num_threads = engine_info.NumThreads;
  206. print_stream_cpu_list("init_process");
  207. // Check if OFFLOAD_DMA_CHANNEL_COUNT is set to 2
  208. // Only the value 2 is supported in 16.0
  209. if (mic_dma_channel_count == 2) {
  210. if (COI::ProcessConfigureDMA) {
  211. // Set DMA channels using COI API
  212. COI::ProcessConfigureDMA(2, COI::DMA_MODE_READ_WRITE);
  213. }
  214. else {
  215. // Set environment variable COI_DMA_CHANNEL_COUNT
  216. // use putenv instead of setenv as Windows has no setenv.
  217. // Note: putenv requires its argument can't be freed or modified.
  218. // So no free after call to putenv or elsewhere.
  219. char * env_var = strdup("COI_DMA_CHANNEL_COUNT=2");
  220. if (env_var == NULL)
  221. LIBOFFLOAD_ERROR(c_malloc);
  222. putenv(env_var);
  223. }
  224. }
  225. // Target executable is not available then use compiler provided offload_main
  226. if (__target_exe == 0) {
  227. // find target executable to be used if main application is not an
  228. // offload build application.
  229. const char *base_name = "offload_main";
  230. if (mic_library_path != 0) {
  231. char *buf = strdup(mic_library_path);
  232. if (buf == NULL)
  233. LIBOFFLOAD_ERROR(c_malloc);
  234. char *try_name = (char*) alloca(strlen(mic_library_path) +
  235. strlen(base_name) + 2);
  236. char *dir, *ptr;
  237. for (dir = strtok_r(buf, PATH_SEPARATOR, &ptr); dir != 0;
  238. dir = strtok_r(0, PATH_SEPARATOR, &ptr)) {
  239. // compose a full path
  240. sprintf(try_name, "%s/%s", dir, base_name);
  241. // check if such file exists
  242. struct stat st;
  243. if (stat(try_name, &st) == 0 && S_ISREG(st.st_mode)) {
  244. mic_device_main = strdup(try_name);
  245. if (mic_device_main == NULL)
  246. LIBOFFLOAD_ERROR(c_malloc);
  247. break;
  248. }
  249. }
  250. free(buf);
  251. }
  252. if (mic_device_main == 0) {
  253. LIBOFFLOAD_ERROR(c_report_no_target_exe, "offload_main");
  254. exit(1);
  255. }
  256. OFFLOAD_DEBUG_TRACE(2,
  257. "Loading target executable %s\n",mic_device_main);
  258. res = COI::ProcessCreateFromFile(
  259. engine, // in_Engine
  260. mic_device_main, // in_pBinaryName
  261. 0, // in_Argc
  262. 0, // in_ppArgv
  263. environ == 0, // in_DupEnv
  264. environ, // in_ppAdditionalEnv
  265. mic_proxy_io, // in_ProxyActive
  266. mic_proxy_fs_root, // in_ProxyfsRoot
  267. mic_buffer_size, // in_BufferSpace
  268. mic_library_path, // in_LibrarySearchPath
  269. &m_process // out_pProcess
  270. );
  271. }
  272. else {
  273. // Target executable should be available by the time when we
  274. // attempt to initialize the device
  275. // Need the full path of the FAT exe for VTUNE
  276. {
  277. #ifndef TARGET_WINNT
  278. ssize_t len = readlink("/proc/self/exe", buf,1000);
  279. #else
  280. int len = GetModuleFileName(NULL, buf,1000);
  281. #endif // TARGET_WINNT
  282. if (len == -1) {
  283. LIBOFFLOAD_ERROR(c_report_no_host_exe);
  284. exit(1);
  285. }
  286. else if (len > 999) {
  287. LIBOFFLOAD_ERROR(c_report_path_buff_overflow);
  288. exit(1);
  289. }
  290. buf[len] = '\0';
  291. }
  292. OFFLOAD_DEBUG_TRACE(2,
  293. "Loading target executable \"%s\" from %p, size %lld, host file %s\n",
  294. __target_exe->name, __target_exe->data, __target_exe->size,
  295. buf);
  296. res = COI::ProcessCreateFromMemory(
  297. engine, // in_Engine
  298. __target_exe->name, // in_pBinaryName
  299. __target_exe->data, // in_pBinaryBuffer
  300. __target_exe->size, // in_BinaryBufferLength,
  301. 0, // in_Argc
  302. 0, // in_ppArgv
  303. environ == 0, // in_DupEnv
  304. environ, // in_ppAdditionalEnv
  305. mic_proxy_io, // in_ProxyActive
  306. mic_proxy_fs_root, // in_ProxyfsRoot
  307. mic_buffer_size, // in_BufferSpace
  308. mic_library_path, // in_LibrarySearchPath
  309. buf, // in_FileOfOrigin
  310. -1, // in_FileOfOriginOffset use -1 to indicate to
  311. // COI that is is a FAT binary
  312. &m_process // out_pProcess
  313. );
  314. }
  315. check_result(res, c_process_create, m_index, res);
  316. if ((mic_4k_buffer_size != 0) || (mic_2m_buffer_size !=0)) {
  317. // available only in MPSS 4.2 and greater
  318. if (COI::ProcessSetCacheSize != 0 ) {
  319. int flags;
  320. // Need compiler to use MPSS 3.2 or greater to get these
  321. // definition so currently hardcoding it
  322. // COI_CACHE_ACTION_GROW_NOW && COI_CACHE_MODE_ONDEMAND_SYNC;
  323. flags = 0x00020002;
  324. res = COI::ProcessSetCacheSize(
  325. m_process, // in_Process
  326. mic_2m_buffer_size, // in_HugePagePoolSize
  327. flags, // inHugeFlags
  328. mic_4k_buffer_size, // in_SmallPagePoolSize
  329. flags, // inSmallFlags
  330. 0, // in_NumDependencies
  331. 0, // in_pDependencies
  332. 0 // out_PCompletion
  333. );
  334. OFFLOAD_DEBUG_TRACE(2,
  335. "Reserve target buffers 4K pages = %d 2M pages = %d\n",
  336. mic_4k_buffer_size, mic_2m_buffer_size);
  337. check_result(res, c_process_set_cache_size, m_index, res);
  338. }
  339. else {
  340. OFFLOAD_DEBUG_TRACE(2,
  341. "Reserve target buffers not supported in current MPSS\n");
  342. }
  343. }
  344. // get function handles
  345. res = COI::ProcessGetFunctionHandles(m_process, c_funcs_total,
  346. m_func_names, m_funcs);
  347. check_result(res, c_process_get_func_handles, m_index, res);
  348. // initialize device side
  349. pid_t pid = init_device();
  350. // For IDB
  351. if (__dbg_is_attached) {
  352. // TODO: we have in-memory executable now.
  353. // Check with IDB team what should we provide them now?
  354. if (__target_exe == 0) {
  355. strcpy(__dbg_target_exe_name, "offload_main");
  356. }
  357. else {
  358. if (strlen(__target_exe->name) < MAX_TARGET_NAME) {
  359. strcpy(__dbg_target_exe_name, __target_exe->name);
  360. }
  361. }
  362. __dbg_target_so_pid = pid;
  363. __dbg_target_id = m_physical_index;
  364. // The call to __dbg_target_so_loaded() is moved
  365. // to Engine:init so all the libraries are loaded before
  366. // informing debugger so debugger can access them.
  367. // __dbg_target_so_loaded();
  368. }
  369. }
  370. void Engine::fini_process(bool verbose)
  371. {
  372. if (m_process != 0) {
  373. uint32_t sig;
  374. int8_t ret;
  375. // destroy target process
  376. OFFLOAD_DEBUG_TRACE(2, "Destroying process on the device %d\n",
  377. m_index);
  378. COIRESULT res = COI::ProcessDestroy(m_process, -1, 0, &ret, &sig);
  379. m_process = 0;
  380. if (res == COI_SUCCESS) {
  381. OFFLOAD_DEBUG_TRACE(3, "Device process: signal %d, exit code %d\n",
  382. sig, ret);
  383. if (verbose) {
  384. if (sig != 0) {
  385. LIBOFFLOAD_ERROR(
  386. c_mic_process_exit_sig, m_index, sig,
  387. c_signal_names[sig >= c_signal_max ? 0 : sig]);
  388. }
  389. else {
  390. LIBOFFLOAD_ERROR(c_mic_process_exit_ret, m_index, ret);
  391. }
  392. }
  393. // for idb
  394. if (__dbg_is_attached) {
  395. __dbg_target_so_unloaded();
  396. }
  397. }
  398. else {
  399. if (verbose) {
  400. LIBOFFLOAD_ERROR(c_mic_process_exit, m_index);
  401. }
  402. }
  403. }
  404. }
  405. void Engine::load_libraries()
  406. {
  407. // load libraries collected so far
  408. for (TargetImageList::iterator it = m_images.begin();
  409. it != m_images.end(); it++) {
  410. OFFLOAD_DEBUG_TRACE(2,
  411. "Loading library \"%s\" from %p, size %llu, host file %s\n",
  412. it->name, it->data, it->size, it->origin);
  413. // load library to the device
  414. COILIBRARY lib;
  415. COIRESULT res;
  416. res = COI::ProcessLoadLibraryFromMemory(m_process,
  417. it->data,
  418. it->size,
  419. it->name,
  420. mic_library_path,
  421. it->origin,
  422. (it->origin) ? -1 : 0,
  423. COI_LOADLIBRARY_V1_FLAGS,
  424. &lib);
  425. m_dyn_libs.push_front(DynLib(it->name, it->data, lib));
  426. if (res != COI_SUCCESS && res != COI_ALREADY_EXISTS) {
  427. check_result(res, c_load_library, it->origin, m_index, res);
  428. }
  429. }
  430. m_images.clear();
  431. }
  432. void Engine::unload_library(const void *data, const char *name)
  433. {
  434. if (m_process == 0) {
  435. return;
  436. }
  437. for (DynLibList::iterator it = m_dyn_libs.begin();
  438. it != m_dyn_libs.end(); it++) {
  439. if (it->data == data) {
  440. COIRESULT res;
  441. OFFLOAD_DEBUG_TRACE(2,
  442. "Unloading library \"%s\"\n",name);
  443. res = COI::ProcessUnloadLibrary(m_process,it->lib);
  444. m_dyn_libs.erase(it);
  445. if (res != COI_SUCCESS) {
  446. check_result(res, c_unload_library, m_index, res);
  447. }
  448. return;
  449. }
  450. }
  451. }
  452. static bool target_entry_cmp(
  453. const VarList::BufEntry &l,
  454. const VarList::BufEntry &r
  455. )
  456. {
  457. const char *l_name = reinterpret_cast<const char*>(l.name);
  458. const char *r_name = reinterpret_cast<const char*>(r.name);
  459. return strcmp(l_name, r_name) < 0;
  460. }
  461. static bool host_entry_cmp(
  462. const VarTable::Entry *l,
  463. const VarTable::Entry *r
  464. )
  465. {
  466. return strcmp(l->name, r->name) < 0;
  467. }
  468. void Engine::init_ptr_data(void)
  469. {
  470. COIRESULT res;
  471. COIEVENT event;
  472. // Prepare table of host entries
  473. std::vector<const VarTable::Entry*> host_table(
  474. Iterator(__offload_vars.get_head()),
  475. Iterator());
  476. // no need to do anything further is host table is empty
  477. if (host_table.size() <= 0) {
  478. return;
  479. }
  480. // Get var table entries from the target.
  481. // First we need to get size for the buffer to copy data
  482. struct {
  483. int64_t nelems;
  484. int64_t length;
  485. } params;
  486. res = COI::PipelineRunFunction(get_pipeline(),
  487. m_funcs[c_func_var_table_size],
  488. 0, 0, 0,
  489. 0, 0,
  490. 0, 0,
  491. &params, sizeof(params),
  492. &event);
  493. check_result(res, c_pipeline_run_func, m_index, res);
  494. res = COI::EventWait(1, &event, -1, 1, 0, 0);
  495. check_result(res, c_event_wait, res);
  496. if (params.length == 0) {
  497. return;
  498. }
  499. // create buffer for target entries and copy data to host
  500. COIBUFFER buffer;
  501. res = COI::BufferCreate(params.length, COI_BUFFER_NORMAL, 0, 0, 1,
  502. &m_process, &buffer);
  503. check_result(res, c_buf_create, m_index, res);
  504. COI_ACCESS_FLAGS flags = COI_SINK_WRITE;
  505. res = COI::PipelineRunFunction(get_pipeline(),
  506. m_funcs[c_func_var_table_copy],
  507. 1, &buffer, &flags,
  508. 0, 0,
  509. &params.nelems, sizeof(params.nelems),
  510. 0, 0,
  511. &event);
  512. check_result(res, c_pipeline_run_func, m_index, res);
  513. res = COI::EventWait(1, &event, -1, 1, 0, 0);
  514. check_result(res, c_event_wait, res);
  515. // patch names in target data
  516. VarList::BufEntry *target_table;
  517. COIMAPINSTANCE map_inst;
  518. res = COI::BufferMap(buffer, 0, params.length, COI_MAP_READ_ONLY, 0, 0,
  519. 0, &map_inst,
  520. reinterpret_cast<void**>(&target_table));
  521. check_result(res, c_buf_map, res);
  522. VarList::table_patch_names(target_table, params.nelems);
  523. // and sort entries
  524. std::sort(target_table, target_table + params.nelems, target_entry_cmp);
  525. std::sort(host_table.begin(), host_table.end(), host_entry_cmp);
  526. // merge host and target entries and enter matching vars map
  527. std::vector<const VarTable::Entry*>::const_iterator hi =
  528. host_table.begin();
  529. std::vector<const VarTable::Entry*>::const_iterator he =
  530. host_table.end();
  531. const VarList::BufEntry *ti = target_table;
  532. const VarList::BufEntry *te = target_table + params.nelems;
  533. while (hi != he && ti != te) {
  534. int res = strcmp((*hi)->name, reinterpret_cast<const char*>(ti->name));
  535. if (res == 0) {
  536. bool is_new;
  537. // add matching entry to var map
  538. PtrData *ptr = insert_ptr_data((*hi)->addr, (*hi)->size, is_new);
  539. // store address for new entries
  540. if (is_new) {
  541. ptr->mic_addr = ti->addr;
  542. ptr->is_static = true;
  543. ptr->var_alloc_type = (*hi)->var_alloc_type;
  544. }
  545. ptr->alloc_ptr_data_lock.unlock();
  546. hi++;
  547. ti++;
  548. }
  549. else if (res < 0) {
  550. hi++;
  551. }
  552. else {
  553. ti++;
  554. }
  555. }
  556. // cleanup
  557. res = COI::BufferUnmap(map_inst, 0, 0, 0);
  558. check_result(res, c_buf_unmap, res);
  559. res = COI::BufferDestroy(buffer);
  560. check_result(res, c_buf_destroy, res);
  561. }
  562. COIRESULT Engine::compute(
  563. _Offload_stream stream,
  564. const std::list<COIBUFFER> &buffers,
  565. const void* data,
  566. uint16_t data_size,
  567. void* ret,
  568. uint16_t ret_size,
  569. uint32_t num_deps,
  570. const COIEVENT* deps,
  571. COIEVENT* event
  572. ) /* const */
  573. {
  574. COIBUFFER *bufs;
  575. COI_ACCESS_FLAGS *flags;
  576. COIRESULT res;
  577. // convert buffers list to array
  578. int num_bufs = buffers.size();
  579. if (num_bufs > 0) {
  580. bufs = (COIBUFFER*) alloca(num_bufs * sizeof(COIBUFFER));
  581. flags = (COI_ACCESS_FLAGS*) alloca(num_bufs *
  582. sizeof(COI_ACCESS_FLAGS));
  583. int i = 0;
  584. for (std::list<COIBUFFER>::const_iterator it = buffers.begin();
  585. it != buffers.end(); it++) {
  586. bufs[i] = *it;
  587. // TODO: this should be fixed
  588. flags[i++] = COI_SINK_WRITE;
  589. }
  590. }
  591. else {
  592. bufs = 0;
  593. flags = 0;
  594. }
  595. COIPIPELINE pipeline = (stream == no_stream) ?
  596. get_pipeline() :
  597. get_pipeline(stream);
  598. // start computation
  599. res = COI::PipelineRunFunction(pipeline,
  600. m_funcs[c_func_compute],
  601. num_bufs, bufs, flags,
  602. num_deps, deps,
  603. data, data_size,
  604. ret, ret_size,
  605. event);
  606. return res;
  607. }
  608. pid_t Engine::init_device(void)
  609. {
  610. struct init_data {
  611. int device_index;
  612. int devices_total;
  613. int console_level;
  614. int offload_report_level;
  615. } data;
  616. COIRESULT res;
  617. COIEVENT event;
  618. pid_t pid;
  619. OFFLOAD_DEBUG_TRACE_1(2, 0, c_offload_init,
  620. "Initializing device with logical index %d "
  621. "and physical index %d\n",
  622. m_index, m_physical_index);
  623. // setup misc data
  624. data.device_index = m_index;
  625. data.devices_total = mic_engines_total;
  626. data.console_level = console_enabled;
  627. data.offload_report_level = offload_report_level;
  628. res = COI::PipelineRunFunction(get_pipeline(),
  629. m_funcs[c_func_init],
  630. 0, 0, 0, 0, 0,
  631. &data, sizeof(data),
  632. &pid, sizeof(pid),
  633. &event);
  634. check_result(res, c_pipeline_run_func, m_index, res);
  635. res = COI::EventWait(1, &event, -1, 1, 0, 0);
  636. check_result(res, c_event_wait, res);
  637. OFFLOAD_DEBUG_TRACE(2, "Device process pid is %d\n", pid);
  638. return pid;
  639. }
  640. // data associated with each thread
  641. struct Thread {
  642. Thread(long* addr_coipipe_counter) {
  643. m_addr_coipipe_counter = addr_coipipe_counter;
  644. memset(m_pipelines, 0, sizeof(m_pipelines));
  645. }
  646. ~Thread() {
  647. #ifndef TARGET_WINNT
  648. __sync_sub_and_fetch(m_addr_coipipe_counter, 1);
  649. #else // TARGET_WINNT
  650. _InterlockedDecrement(m_addr_coipipe_counter);
  651. #endif // TARGET_WINNT
  652. for (int i = 0; i < mic_engines_total; i++) {
  653. if (m_pipelines[i] != 0) {
  654. COI::PipelineDestroy(m_pipelines[i]);
  655. }
  656. }
  657. }
  658. COIPIPELINE get_pipeline(int index) const {
  659. return m_pipelines[index];
  660. }
  661. void set_pipeline(int index, COIPIPELINE pipeline) {
  662. m_pipelines[index] = pipeline;
  663. }
  664. AutoSet& get_auto_vars() {
  665. return m_auto_vars;
  666. }
  667. private:
  668. long* m_addr_coipipe_counter;
  669. AutoSet m_auto_vars;
  670. COIPIPELINE m_pipelines[MIC_ENGINES_MAX];
  671. };
  672. COIPIPELINE Engine::get_pipeline(void)
  673. {
  674. Thread* thread = (Thread*) thread_getspecific(mic_thread_key);
  675. if (thread == 0) {
  676. thread = new Thread(&m_proc_number);
  677. thread_setspecific(mic_thread_key, thread);
  678. }
  679. COIPIPELINE pipeline = thread->get_pipeline(m_index);
  680. if (pipeline == 0) {
  681. COIRESULT res;
  682. int proc_num;
  683. #ifndef TARGET_WINNT
  684. proc_num = __sync_fetch_and_add(&m_proc_number, 1);
  685. #else // TARGET_WINNT
  686. proc_num = _InterlockedIncrement(&m_proc_number);
  687. #endif // TARGET_WINNT
  688. if (proc_num > COI_PIPELINE_MAX_PIPELINES) {
  689. LIBOFFLOAD_ERROR(c_coipipe_max_number, COI_PIPELINE_MAX_PIPELINES);
  690. LIBOFFLOAD_ABORT;
  691. }
  692. // Create pipeline for this thread
  693. if (m_assigned_cpus == 0) {
  694. // If m_assigned_cpus is NULL, it implies all threads
  695. // Create the pipeline with no CPU mask
  696. res = COI::PipelineCreate(m_process, 0, mic_stack_size, &pipeline);
  697. } else {
  698. // Create COI CPU mask
  699. COI_CPU_MASK in_Mask;
  700. res = COI::PipelineClearCPUMask(in_Mask);
  701. check_result(res, c_clear_cpu_mask, m_index, res);
  702. int threads_per_core = m_num_threads / m_num_cores;
  703. // Available threads are defined by examining of m_assigned_cpus bitset.
  704. // We skip thread 0.
  705. for (int i = 1; i < m_num_threads; i++) {
  706. // For available thread i m_assigned_cpus[i] is equal to 1
  707. if ((*m_assigned_cpus)[i]) {
  708. COI_CPU_MASK_SET(i, in_Mask);
  709. }
  710. }
  711. OFFLOAD_DEBUG_TRACE(2, "COIPipelineCreate Mask for this CPU thread\n"
  712. "%016lx %016lx %016lx %016lx\n%016lx %016lx %016lx %016lx\n"
  713. "%016lx %016lx %016lx %016lx\n%016lx %016lx %016lx %016lx\n",
  714. in_Mask[0], in_Mask[1], in_Mask[2], in_Mask[3],
  715. in_Mask[4], in_Mask[5], in_Mask[6], in_Mask[7],
  716. in_Mask[8], in_Mask[9], in_Mask[10], in_Mask[11],
  717. in_Mask[12], in_Mask[13], in_Mask[14], in_Mask[15]);
  718. // Create the pipeline with allowable CPUs
  719. res = COI::PipelineCreate(m_process, in_Mask, mic_stack_size, &pipeline);
  720. }
  721. check_result(res, c_pipeline_create, m_index, res);
  722. thread->set_pipeline(m_index, pipeline);
  723. }
  724. return pipeline;
  725. }
  726. Stream* Stream::find_stream(uint64_t handle, bool remove)
  727. {
  728. Stream *stream = 0;
  729. m_stream_lock.lock();
  730. {
  731. StreamMap::iterator it = all_streams.find(handle);
  732. if (it != all_streams.end()) {
  733. stream = it->second;
  734. if (remove) {
  735. all_streams.erase(it);
  736. }
  737. }
  738. }
  739. m_stream_lock.unlock();
  740. return stream;
  741. }
  742. void Engine::move_cpu_el_after(CpuEl* cpu_what, CpuEl* cpu_after)
  743. {
  744. if (cpu_what == cpu_after) {
  745. return;
  746. }
  747. CpuEl* cpu_prev = cpu_what->prev;
  748. // remove cpu_what
  749. if (!cpu_prev) {
  750. m_cpu_head = cpu_what->next;
  751. }
  752. else {
  753. cpu_prev->next = cpu_what->next;
  754. }
  755. if (cpu_what->next) {
  756. cpu_what->next->prev = cpu_prev;
  757. }
  758. // insert cpu_what after cpu_after
  759. cpu_what->prev = cpu_after;
  760. cpu_what->next = cpu_after->next;
  761. if (cpu_after->next) {
  762. cpu_after->next->prev = cpu_what;
  763. }
  764. cpu_after->next = cpu_what;
  765. }
  766. COIPIPELINE Engine::get_pipeline(_Offload_stream handle)
  767. {
  768. Stream * stream = Stream::find_stream(handle, false);
  769. if (!stream) {
  770. LIBOFFLOAD_ERROR(c_offload_no_stream, m_index);
  771. LIBOFFLOAD_ABORT;
  772. }
  773. COIPIPELINE pipeline = stream->get_pipeline();
  774. if (pipeline == 0) {
  775. COIRESULT res;
  776. int proc_num;
  777. COI_CPU_MASK in_Mask ;
  778. #ifndef TARGET_WINNT
  779. proc_num = __sync_fetch_and_add(&m_proc_number, 1);
  780. #else // TARGET_WINNT
  781. proc_num = _InterlockedIncrement(&m_proc_number);
  782. #endif // TARGET_WINNT
  783. if (proc_num > COI_PIPELINE_MAX_PIPELINES) {
  784. LIBOFFLOAD_ERROR(c_coipipe_max_number, COI_PIPELINE_MAX_PIPELINES);
  785. LIBOFFLOAD_ABORT;
  786. }
  787. m_stream_lock.lock();
  788. // start process if not done yet
  789. if (m_process == 0) {
  790. init_process();
  791. }
  792. // create CPUmask
  793. res = COI::PipelineClearCPUMask(in_Mask);
  794. check_result(res, c_clear_cpu_mask, m_index, res);
  795. int stream_cpu_num = stream->get_cpu_number();
  796. stream->m_stream_cpus.reset();
  797. int threads_per_core = m_num_threads / m_num_cores;
  798. // Available threads is taken from m_cpus list.
  799. // m_cpu_head points to the head of m_cpus.
  800. // the elements of m_cpus is ordered by the number of usage in streams.
  801. CpuEl *cpu_el = m_cpu_head;
  802. CpuEl *cpu_used_el, *cpu_used_prev, *cpu_prev;
  803. for (int i = 0; i < stream_cpu_num; i++) {
  804. COI_CPU_MASK_SET(CPU_INDEX(cpu_el), in_Mask);
  805. stream->m_stream_cpus.set(CPU_INDEX(cpu_el));
  806. //If the number of availabale threads is less than stream_cpu_num,
  807. // the stream_cpu_num is restricted to this number.
  808. if (!cpu_el->next) {
  809. break;
  810. }
  811. if (i + 1 < stream_cpu_num) {
  812. cpu_el = cpu_el->next;
  813. }
  814. }
  815. // assertion : cpu_el points to the last used thread
  816. cpu_used_el = cpu_el;
  817. while (cpu_used_el) {
  818. cpu_used_el->count++;
  819. cpu_el = cpu_prev = cpu_used_el;
  820. cpu_used_prev = cpu_used_el->prev;
  821. if (!cpu_el->next) {
  822. cpu_used_el = cpu_used_prev;
  823. continue;
  824. }
  825. while (cpu_el) {
  826. if (cpu_used_el->count < cpu_el->count) {
  827. break;
  828. }
  829. // Equal used threads are ordered by thread number to
  830. // assign to a stream as contiguous threads as possible.
  831. else if (cpu_used_el->count == cpu_el->count &&
  832. CPU_INDEX(cpu_used_el) < CPU_INDEX(cpu_el)) {
  833. break;
  834. }
  835. cpu_prev = cpu_el;
  836. cpu_el = cpu_el->next;
  837. }
  838. if (cpu_used_el != cpu_prev) {
  839. move_cpu_el_after(cpu_used_el, cpu_prev);
  840. }
  841. cpu_used_el = cpu_used_prev;
  842. }
  843. print_stream_cpu_list("get_pipeline");
  844. // create pipeline for this thread
  845. OFFLOAD_DEBUG_TRACE(2, "COIPipelineCreate Mask for this Stream\n"
  846. "%016lx %016lx %016lx %016lx\n%016lx %016lx %016lx %016lx\n"
  847. "%016lx %016lx %016lx %016lx\n%016lx %016lx %016lx %016lx\n",
  848. in_Mask[0], in_Mask[1], in_Mask[2], in_Mask[3],
  849. in_Mask[4], in_Mask[5], in_Mask[6], in_Mask[7],
  850. in_Mask[8], in_Mask[9], in_Mask[10], in_Mask[11],
  851. in_Mask[12], in_Mask[13], in_Mask[14], in_Mask[15]);
  852. res = COI::PipelineCreate(m_process, in_Mask,
  853. mic_stack_size, &pipeline);
  854. check_result(res, c_pipeline_create, m_index, res);
  855. // Set stream's affinities
  856. {
  857. struct affinity_spec affinity_spec;
  858. char* affinity_type;
  859. int i;
  860. // "compact" by default
  861. affinity_spec.affinity_type = affinity_compact;
  862. // Check if user has specified type of affinity
  863. if ((affinity_type = getenv("OFFLOAD_STREAM_AFFINITY")) !=
  864. NULL)
  865. {
  866. char affinity_str[16];
  867. int affinity_str_len;
  868. OFFLOAD_DEBUG_TRACE(2,
  869. "User has specified OFFLOAD_STREAM_AFFINITY=%s\n",
  870. affinity_type);
  871. // Set type of affinity requested
  872. affinity_str_len = strlen(affinity_type);
  873. for (i=0; i<affinity_str_len && i<15; i++)
  874. {
  875. affinity_str[i] = tolower(affinity_type[i]);
  876. }
  877. affinity_str[i] = '\0';
  878. if (strcmp(affinity_str, "compact") == 0) {
  879. affinity_spec.affinity_type = affinity_compact;
  880. OFFLOAD_DEBUG_TRACE(2, "Setting affinity=compact\n");
  881. } else if (strcmp(affinity_str, "scatter") == 0) {
  882. affinity_spec.affinity_type = affinity_scatter;
  883. OFFLOAD_DEBUG_TRACE(2, "Setting affinity=scatter\n");
  884. } else {
  885. LIBOFFLOAD_ERROR(c_incorrect_affinity, affinity_str);
  886. affinity_spec.affinity_type = affinity_compact;
  887. OFFLOAD_DEBUG_TRACE(2, "Setting affinity=compact\n");
  888. }
  889. }
  890. // Make flat copy of sink mask because COI's mask is opaque
  891. for (i=0; i<16; i++) {
  892. affinity_spec.sink_mask[i] = in_Mask[i];
  893. }
  894. // Set number of cores and threads
  895. affinity_spec.num_cores = m_num_cores;
  896. affinity_spec.num_threads = m_num_threads;
  897. COIEVENT event;
  898. res = COI::PipelineRunFunction(pipeline,
  899. m_funcs[c_func_set_stream_affinity],
  900. 0, 0, 0,
  901. 0, 0,
  902. &affinity_spec, sizeof(affinity_spec),
  903. 0, 0,
  904. &event);
  905. check_result(res, c_pipeline_run_func, m_index, res);
  906. res = COI::EventWait(1, &event, -1, 1, 0, 0);
  907. check_result(res, c_event_wait, res);
  908. }
  909. m_stream_lock.unlock();
  910. stream->set_pipeline(pipeline);
  911. }
  912. return pipeline;
  913. }
  914. void Engine::stream_destroy(_Offload_stream handle)
  915. {
  916. // get stream
  917. Stream * stream = Stream::find_stream(handle, true);
  918. if (stream) {
  919. // return cpus for future use
  920. for (int i = 0; i < m_num_threads; i++) {
  921. if (stream->m_stream_cpus.test(i)) {
  922. CpuEl *cpu_el = m_cpus + i;
  923. CpuEl *cpu_first_el = cpu_el;
  924. // decrease count of thread "i" and move its CpuEl to the
  925. // proper place into the ordered list
  926. cpu_el->count--;
  927. while (cpu_el->prev) {
  928. if (cpu_first_el->count > cpu_el->prev->count) {
  929. break;
  930. }
  931. else if (cpu_first_el->count == cpu_el->prev->count &&
  932. CPU_INDEX(cpu_first_el) > CPU_INDEX(cpu_el->prev)) {
  933. break;
  934. }
  935. cpu_el = cpu_el->prev;
  936. }
  937. cpu_el = cpu_el->prev;
  938. // If cpu_el for thread "i" must be moved in the list
  939. if (cpu_first_el != cpu_el) {
  940. // Thread "i" is used the least times. It must be set as
  941. // the m_cpu_head.
  942. if (!cpu_el) {
  943. if (!cpu_first_el->prev) {
  944. continue;
  945. }
  946. // remove cpu_el.
  947. cpu_first_el->prev->next = cpu_first_el->next;
  948. if (cpu_first_el->next) {
  949. cpu_first_el->next->prev = cpu_first_el->prev;
  950. }
  951. // make cpu_first_el as new m_cpu_head
  952. cpu_first_el->prev = NULL;
  953. cpu_first_el->next = m_cpu_head;
  954. m_cpu_head->prev = cpu_first_el;
  955. m_cpu_head = cpu_first_el;
  956. }
  957. else {
  958. move_cpu_el_after(cpu_first_el, cpu_el);
  959. }
  960. }
  961. }
  962. }
  963. print_stream_cpu_list("stream_destroy");
  964. delete stream;
  965. }
  966. else {
  967. LIBOFFLOAD_ERROR(c_offload_no_stream, m_index);
  968. LIBOFFLOAD_ABORT;
  969. }
  970. }
  971. uint64_t Engine::get_thread_id(void)
  972. {
  973. Thread* thread = (Thread*) thread_getspecific(mic_thread_key);
  974. if (thread == 0) {
  975. thread = new Thread(&m_proc_number);
  976. thread_setspecific(mic_thread_key, thread);
  977. }
  978. return reinterpret_cast<uint64_t>(thread);
  979. }
  980. AutoSet& Engine::get_auto_vars(void)
  981. {
  982. Thread* thread = (Thread*) thread_getspecific(mic_thread_key);
  983. if (thread == 0) {
  984. thread = new Thread(&m_proc_number);
  985. thread_setspecific(mic_thread_key, thread);
  986. }
  987. return thread->get_auto_vars();
  988. }
  989. void Engine::destroy_thread_data(void *data)
  990. {
  991. delete static_cast<Thread*>(data);
  992. }