offload_engine.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. /*
  2. Copyright (c) 2014 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 <algorithm>
  30. #include <vector>
  31. #include "offload_host.h"
  32. #include "offload_table.h"
  33. const char* Engine::m_func_names[Engine::c_funcs_total] =
  34. {
  35. "server_compute",
  36. #ifdef MYO_SUPPORT
  37. "server_myoinit",
  38. "server_myofini",
  39. #endif // MYO_SUPPORT
  40. "server_init",
  41. "server_var_table_size",
  42. "server_var_table_copy"
  43. };
  44. // Symbolic representation of system signals. Fix for CQ233593
  45. const char* Engine::c_signal_names[Engine::c_signal_max] =
  46. {
  47. "Unknown SIGNAL",
  48. "SIGHUP", /* 1, Hangup (POSIX). */
  49. "SIGINT", /* 2, Interrupt (ANSI). */
  50. "SIGQUIT", /* 3, Quit (POSIX). */
  51. "SIGILL", /* 4, Illegal instruction (ANSI). */
  52. "SIGTRAP", /* 5, Trace trap (POSIX). */
  53. "SIGABRT", /* 6, Abort (ANSI). */
  54. "SIGBUS", /* 7, BUS error (4.2 BSD). */
  55. "SIGFPE", /* 8, Floating-point exception (ANSI). */
  56. "SIGKILL", /* 9, Kill, unblockable (POSIX). */
  57. "SIGUSR1", /* 10, User-defined signal 1 (POSIX). */
  58. "SIGSEGV", /* 11, Segmentation violation (ANSI). */
  59. "SIGUSR2", /* 12, User-defined signal 2 (POSIX). */
  60. "SIGPIPE", /* 13, Broken pipe (POSIX). */
  61. "SIGALRM", /* 14, Alarm clock (POSIX). */
  62. "SIGTERM", /* 15, Termination (ANSI). */
  63. "SIGSTKFLT", /* 16, Stack fault. */
  64. "SIGCHLD", /* 17, Child status has changed (POSIX). */
  65. "SIGCONT", /* 18, Continue (POSIX). */
  66. "SIGSTOP", /* 19, Stop, unblockable (POSIX). */
  67. "SIGTSTP", /* 20, Keyboard stop (POSIX). */
  68. "SIGTTIN", /* 21, Background read from tty (POSIX). */
  69. "SIGTTOU", /* 22, Background write to tty (POSIX). */
  70. "SIGURG", /* 23, Urgent condition on socket (4.2 BSD). */
  71. "SIGXCPU", /* 24, CPU limit exceeded (4.2 BSD). */
  72. "SIGXFSZ", /* 25, File size limit exceeded (4.2 BSD). */
  73. "SIGVTALRM", /* 26, Virtual alarm clock (4.2 BSD). */
  74. "SIGPROF", /* 27, Profiling alarm clock (4.2 BSD). */
  75. "SIGWINCH", /* 28, Window size change (4.3 BSD, Sun). */
  76. "SIGIO", /* 29, I/O now possible (4.2 BSD). */
  77. "SIGPWR", /* 30, Power failure restart (System V). */
  78. "SIGSYS" /* 31, Bad system call. */
  79. };
  80. void Engine::init(void)
  81. {
  82. if (!m_ready) {
  83. mutex_locker_t locker(m_lock);
  84. if (!m_ready) {
  85. // start process if not done yet
  86. if (m_process == 0) {
  87. init_process();
  88. }
  89. // load penging images
  90. load_libraries();
  91. // and (re)build pointer table
  92. init_ptr_data();
  93. // it is ready now
  94. m_ready = true;
  95. }
  96. }
  97. }
  98. void Engine::init_process(void)
  99. {
  100. COIENGINE engine;
  101. COIRESULT res;
  102. const char **environ;
  103. // create environment for the target process
  104. environ = (const char**) mic_env_vars.create_environ_for_card(m_index);
  105. if (environ != 0) {
  106. for (const char **p = environ; *p != 0; p++) {
  107. OFFLOAD_DEBUG_TRACE(3, "Env Var for card %d: %s\n", m_index, *p);
  108. }
  109. }
  110. // Create execution context in the specified device
  111. OFFLOAD_DEBUG_TRACE(2, "Getting device %d (engine %d) handle\n", m_index,
  112. m_physical_index);
  113. res = COI::EngineGetHandle(COI_ISA_KNC, m_physical_index, &engine);
  114. check_result(res, c_get_engine_handle, m_index, res);
  115. // Target executable should be available by the time when we
  116. // attempt to initialize the device
  117. if (__target_exe == 0) {
  118. LIBOFFLOAD_ERROR(c_no_target_exe);
  119. exit(1);
  120. }
  121. OFFLOAD_DEBUG_TRACE(2,
  122. "Loading target executable \"%s\" from %p, size %lld\n",
  123. __target_exe->name, __target_exe->data, __target_exe->size);
  124. res = COI::ProcessCreateFromMemory(
  125. engine, // in_Engine
  126. __target_exe->name, // in_pBinaryName
  127. __target_exe->data, // in_pBinaryBuffer
  128. __target_exe->size, // in_BinaryBufferLength,
  129. 0, // in_Argc
  130. 0, // in_ppArgv
  131. environ == 0, // in_DupEnv
  132. environ, // in_ppAdditionalEnv
  133. mic_proxy_io, // in_ProxyActive
  134. mic_proxy_fs_root, // in_ProxyfsRoot
  135. mic_buffer_size, // in_BufferSpace
  136. mic_library_path, // in_LibrarySearchPath
  137. __target_exe->origin, // in_FileOfOrigin
  138. __target_exe->offset, // in_FileOfOriginOffset
  139. &m_process // out_pProcess
  140. );
  141. check_result(res, c_process_create, m_index, res);
  142. // get function handles
  143. res = COI::ProcessGetFunctionHandles(m_process, c_funcs_total,
  144. m_func_names, m_funcs);
  145. check_result(res, c_process_get_func_handles, m_index, res);
  146. // initialize device side
  147. pid_t pid = init_device();
  148. // For IDB
  149. if (__dbg_is_attached) {
  150. // TODO: we have in-memory executable now.
  151. // Check with IDB team what should we provide them now?
  152. if (strlen(__target_exe->name) < MAX_TARGET_NAME) {
  153. strcpy(__dbg_target_exe_name, __target_exe->name);
  154. }
  155. __dbg_target_so_pid = pid;
  156. __dbg_target_id = m_physical_index;
  157. __dbg_target_so_loaded();
  158. }
  159. }
  160. void Engine::fini_process(bool verbose)
  161. {
  162. if (m_process != 0) {
  163. uint32_t sig;
  164. int8_t ret;
  165. // destroy target process
  166. OFFLOAD_DEBUG_TRACE(2, "Destroying process on the device %d\n",
  167. m_index);
  168. COIRESULT res = COI::ProcessDestroy(m_process, -1, 0, &ret, &sig);
  169. m_process = 0;
  170. if (res == COI_SUCCESS) {
  171. OFFLOAD_DEBUG_TRACE(3, "Device process: signal %d, exit code %d\n",
  172. sig, ret);
  173. if (verbose) {
  174. if (sig != 0) {
  175. LIBOFFLOAD_ERROR(
  176. c_mic_process_exit_sig, m_index, sig,
  177. c_signal_names[sig >= c_signal_max ? 0 : sig]);
  178. }
  179. else {
  180. LIBOFFLOAD_ERROR(c_mic_process_exit_ret, m_index, ret);
  181. }
  182. }
  183. // for idb
  184. if (__dbg_is_attached) {
  185. __dbg_target_so_unloaded();
  186. }
  187. }
  188. else {
  189. if (verbose) {
  190. LIBOFFLOAD_ERROR(c_mic_process_exit, m_index);
  191. }
  192. }
  193. }
  194. }
  195. void Engine::load_libraries()
  196. {
  197. // load libraries collected so far
  198. for (TargetImageList::iterator it = m_images.begin();
  199. it != m_images.end(); it++) {
  200. OFFLOAD_DEBUG_TRACE(2, "Loading library \"%s\" from %p, size %llu\n",
  201. it->name, it->data, it->size);
  202. // load library to the device
  203. COILIBRARY lib;
  204. COIRESULT res;
  205. res = COI::ProcessLoadLibraryFromMemory(m_process,
  206. it->data,
  207. it->size,
  208. it->name,
  209. mic_library_path,
  210. it->origin,
  211. it->offset,
  212. COI_LOADLIBRARY_V1_FLAGS,
  213. &lib);
  214. if (res != COI_SUCCESS && res != COI_ALREADY_EXISTS) {
  215. check_result(res, c_load_library, m_index, res);
  216. }
  217. }
  218. m_images.clear();
  219. }
  220. static bool target_entry_cmp(
  221. const VarList::BufEntry &l,
  222. const VarList::BufEntry &r
  223. )
  224. {
  225. const char *l_name = reinterpret_cast<const char*>(l.name);
  226. const char *r_name = reinterpret_cast<const char*>(r.name);
  227. return strcmp(l_name, r_name) < 0;
  228. }
  229. static bool host_entry_cmp(
  230. const VarTable::Entry *l,
  231. const VarTable::Entry *r
  232. )
  233. {
  234. return strcmp(l->name, r->name) < 0;
  235. }
  236. void Engine::init_ptr_data(void)
  237. {
  238. COIRESULT res;
  239. COIEVENT event;
  240. // Prepare table of host entries
  241. std::vector<const VarTable::Entry*> host_table(__offload_vars.begin(),
  242. __offload_vars.end());
  243. // no need to do anything further is host table is empty
  244. if (host_table.size() <= 0) {
  245. return;
  246. }
  247. // Get var table entries from the target.
  248. // First we need to get size for the buffer to copy data
  249. struct {
  250. int64_t nelems;
  251. int64_t length;
  252. } params;
  253. res = COI::PipelineRunFunction(get_pipeline(),
  254. m_funcs[c_func_var_table_size],
  255. 0, 0, 0,
  256. 0, 0,
  257. 0, 0,
  258. &params, sizeof(params),
  259. &event);
  260. check_result(res, c_pipeline_run_func, m_index, res);
  261. res = COI::EventWait(1, &event, -1, 1, 0, 0);
  262. check_result(res, c_event_wait, res);
  263. if (params.length == 0) {
  264. return;
  265. }
  266. // create buffer for target entries and copy data to host
  267. COIBUFFER buffer;
  268. res = COI::BufferCreate(params.length, COI_BUFFER_NORMAL, 0, 0, 1,
  269. &m_process, &buffer);
  270. check_result(res, c_buf_create, m_index, res);
  271. COI_ACCESS_FLAGS flags = COI_SINK_WRITE;
  272. res = COI::PipelineRunFunction(get_pipeline(),
  273. m_funcs[c_func_var_table_copy],
  274. 1, &buffer, &flags,
  275. 0, 0,
  276. &params.nelems, sizeof(params.nelems),
  277. 0, 0,
  278. &event);
  279. check_result(res, c_pipeline_run_func, m_index, res);
  280. res = COI::EventWait(1, &event, -1, 1, 0, 0);
  281. check_result(res, c_event_wait, res);
  282. // patch names in target data
  283. VarList::BufEntry *target_table;
  284. COIMAPINSTANCE map_inst;
  285. res = COI::BufferMap(buffer, 0, params.length, COI_MAP_READ_ONLY, 0, 0,
  286. 0, &map_inst,
  287. reinterpret_cast<void**>(&target_table));
  288. check_result(res, c_buf_map, res);
  289. VarList::table_patch_names(target_table, params.nelems);
  290. // and sort entries
  291. std::sort(target_table, target_table + params.nelems, target_entry_cmp);
  292. std::sort(host_table.begin(), host_table.end(), host_entry_cmp);
  293. // merge host and target entries and enter matching vars map
  294. std::vector<const VarTable::Entry*>::const_iterator hi =
  295. host_table.begin();
  296. std::vector<const VarTable::Entry*>::const_iterator he =
  297. host_table.end();
  298. const VarList::BufEntry *ti = target_table;
  299. const VarList::BufEntry *te = target_table + params.nelems;
  300. while (hi != he && ti != te) {
  301. int res = strcmp((*hi)->name, reinterpret_cast<const char*>(ti->name));
  302. if (res == 0) {
  303. // add matching entry to var map
  304. std::pair<PtrSet::iterator, bool> res =
  305. m_ptr_set.insert(PtrData((*hi)->addr, (*hi)->size));
  306. // store address for new entries
  307. if (res.second) {
  308. PtrData *ptr = const_cast<PtrData*>(res.first.operator->());
  309. ptr->mic_addr = ti->addr;
  310. ptr->is_static = true;
  311. }
  312. hi++;
  313. ti++;
  314. }
  315. else if (res < 0) {
  316. hi++;
  317. }
  318. else {
  319. ti++;
  320. }
  321. }
  322. // cleanup
  323. res = COI::BufferUnmap(map_inst, 0, 0, 0);
  324. check_result(res, c_buf_unmap, res);
  325. res = COI::BufferDestroy(buffer);
  326. check_result(res, c_buf_destroy, res);
  327. }
  328. COIRESULT Engine::compute(
  329. const std::list<COIBUFFER> &buffers,
  330. const void* data,
  331. uint16_t data_size,
  332. void* ret,
  333. uint16_t ret_size,
  334. uint32_t num_deps,
  335. const COIEVENT* deps,
  336. COIEVENT* event
  337. ) /* const */
  338. {
  339. COIBUFFER *bufs;
  340. COI_ACCESS_FLAGS *flags;
  341. COIRESULT res;
  342. // convert buffers list to array
  343. int num_bufs = buffers.size();
  344. if (num_bufs > 0) {
  345. bufs = (COIBUFFER*) alloca(num_bufs * sizeof(COIBUFFER));
  346. flags = (COI_ACCESS_FLAGS*) alloca(num_bufs *
  347. sizeof(COI_ACCESS_FLAGS));
  348. int i = 0;
  349. for (std::list<COIBUFFER>::const_iterator it = buffers.begin();
  350. it != buffers.end(); it++) {
  351. bufs[i] = *it;
  352. // TODO: this should be fixed
  353. flags[i++] = COI_SINK_WRITE;
  354. }
  355. }
  356. else {
  357. bufs = 0;
  358. flags = 0;
  359. }
  360. // start computation
  361. res = COI::PipelineRunFunction(get_pipeline(),
  362. m_funcs[c_func_compute],
  363. num_bufs, bufs, flags,
  364. num_deps, deps,
  365. data, data_size,
  366. ret, ret_size,
  367. event);
  368. return res;
  369. }
  370. pid_t Engine::init_device(void)
  371. {
  372. struct init_data {
  373. int device_index;
  374. int devices_total;
  375. int console_level;
  376. int offload_report_level;
  377. } data;
  378. COIRESULT res;
  379. COIEVENT event;
  380. pid_t pid;
  381. OFFLOAD_DEBUG_TRACE_1(2, 0, c_offload_init,
  382. "Initializing device with logical index %d "
  383. "and physical index %d\n",
  384. m_index, m_physical_index);
  385. // setup misc data
  386. data.device_index = m_index;
  387. data.devices_total = mic_engines_total;
  388. data.console_level = console_enabled;
  389. data.offload_report_level = offload_report_level;
  390. res = COI::PipelineRunFunction(get_pipeline(),
  391. m_funcs[c_func_init],
  392. 0, 0, 0, 0, 0,
  393. &data, sizeof(data),
  394. &pid, sizeof(pid),
  395. &event);
  396. check_result(res, c_pipeline_run_func, m_index, res);
  397. res = COI::EventWait(1, &event, -1, 1, 0, 0);
  398. check_result(res, c_event_wait, res);
  399. OFFLOAD_DEBUG_TRACE(2, "Device process pid is %d\n", pid);
  400. return pid;
  401. }
  402. // data associated with each thread
  403. struct Thread {
  404. Thread(long* addr_coipipe_counter) {
  405. m_addr_coipipe_counter = addr_coipipe_counter;
  406. memset(m_pipelines, 0, sizeof(m_pipelines));
  407. }
  408. ~Thread() {
  409. #ifndef TARGET_WINNT
  410. __sync_sub_and_fetch(m_addr_coipipe_counter, 1);
  411. #else // TARGET_WINNT
  412. _InterlockedDecrement(m_addr_coipipe_counter);
  413. #endif // TARGET_WINNT
  414. for (int i = 0; i < mic_engines_total; i++) {
  415. if (m_pipelines[i] != 0) {
  416. COI::PipelineDestroy(m_pipelines[i]);
  417. }
  418. }
  419. }
  420. COIPIPELINE get_pipeline(int index) const {
  421. return m_pipelines[index];
  422. }
  423. void set_pipeline(int index, COIPIPELINE pipeline) {
  424. m_pipelines[index] = pipeline;
  425. }
  426. AutoSet& get_auto_vars() {
  427. return m_auto_vars;
  428. }
  429. private:
  430. long* m_addr_coipipe_counter;
  431. AutoSet m_auto_vars;
  432. COIPIPELINE m_pipelines[MIC_ENGINES_MAX];
  433. };
  434. COIPIPELINE Engine::get_pipeline(void)
  435. {
  436. Thread* thread = (Thread*) thread_getspecific(mic_thread_key);
  437. if (thread == 0) {
  438. thread = new Thread(&m_proc_number);
  439. thread_setspecific(mic_thread_key, thread);
  440. }
  441. COIPIPELINE pipeline = thread->get_pipeline(m_index);
  442. if (pipeline == 0) {
  443. COIRESULT res;
  444. int proc_num;
  445. #ifndef TARGET_WINNT
  446. proc_num = __sync_fetch_and_add(&m_proc_number, 1);
  447. #else // TARGET_WINNT
  448. proc_num = _InterlockedIncrement(&m_proc_number);
  449. #endif // TARGET_WINNT
  450. if (proc_num > COI_PIPELINE_MAX_PIPELINES) {
  451. LIBOFFLOAD_ERROR(c_coipipe_max_number, COI_PIPELINE_MAX_PIPELINES);
  452. LIBOFFLOAD_ABORT;
  453. }
  454. // create pipeline for this thread
  455. res = COI::PipelineCreate(m_process, 0, mic_stack_size, &pipeline);
  456. check_result(res, c_pipeline_create, m_index, res);
  457. thread->set_pipeline(m_index, pipeline);
  458. }
  459. return pipeline;
  460. }
  461. AutoSet& Engine::get_auto_vars(void)
  462. {
  463. Thread* thread = (Thread*) thread_getspecific(mic_thread_key);
  464. if (thread == 0) {
  465. thread = new Thread(&m_proc_number);
  466. thread_setspecific(mic_thread_key, thread);
  467. }
  468. return thread->get_auto_vars();
  469. }
  470. void Engine::destroy_thread_data(void *data)
  471. {
  472. delete static_cast<Thread*>(data);
  473. }