shim_ipc_helper.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  1. /* Copyright (C) 2014 Stony Brook University
  2. This file is part of Graphene Library OS.
  3. Graphene Library OS is free software: you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public License
  5. as published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. Graphene Library OS is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  13. /*
  14. * shim_ipc_helper.c
  15. *
  16. * This file contains codes to create a IPC helper thread inside library OS
  17. * and maintain bookkeeping of IPC ports.
  18. */
  19. #include <shim_internal.h>
  20. #include <shim_utils.h>
  21. #include <shim_thread.h>
  22. #include <shim_handle.h>
  23. #include <shim_ipc.h>
  24. #include <shim_checkpoint.h>
  25. #include <shim_profile.h>
  26. #include <pal.h>
  27. #include <pal_error.h>
  28. #include <list.h>
  29. #define PORT_MGR_ALLOC 32
  30. #define PAGE_SIZE allocsize
  31. #define OBJ_TYPE struct shim_ipc_port
  32. #include "memmgr.h"
  33. static MEM_MGR port_mgr;
  34. /* This points to a list of shim_ipc_port objects (by the list field) */
  35. DEFINE_LISTP(shim_ipc_port);
  36. static LISTP_TYPE(shim_ipc_port) pobj_list;
  37. #define PID_HASH_LEN 6
  38. #define PID_HASH_NUM (1 << PID_HASH_LEN)
  39. #define PID_HASH_MASK (PID_HASH_NUM - 1)
  40. #define PID_HASH(pid) ((pid) & PID_HASH_MASK)
  41. /* This points to a list of shim_ipc_port objects (by the hlist field) */
  42. static LISTP_TYPE(shim_ipc_port) ipc_port_pool [PID_HASH_NUM];
  43. /* This variable can be read without the ipc_helper_lock held, but
  44. * should be modified with the ipc_helper_lock held (and in some cases,
  45. * the value should be re-checked after acquiring the lock.
  46. * For reads in a loop without the lock, some caution should be taken to
  47. * use compiler barriers to ensure that a stale value isn't cached.
  48. */
  49. static enum {
  50. HELPER_UNINITIALIZED, HELPER_DELAYED, HELPER_NOTALIVE,
  51. HELPER_ALIVE, HELPER_HANDEDOVER,
  52. } ipc_helper_state;
  53. static struct shim_thread * ipc_helper_thread;
  54. static bool ipc_helper_update;
  55. static AEVENTTYPE ipc_helper_event;
  56. #define IN_HELPER() \
  57. (ipc_helper_thread && ipc_helper_thread == get_cur_thread())
  58. static struct shim_lock ipc_helper_lock;
  59. static struct shim_ipc_port * broadcast_port;
  60. //#define DEBUG_REF
  61. static int init_ipc_port (struct shim_ipc_info * info, PAL_HANDLE hdl, IDTYPE type)
  62. {
  63. if (!info)
  64. return 0;
  65. if (info->pal_handle == IPC_FORCE_RECONNECT) {
  66. info->pal_handle = NULL;
  67. if (!hdl && !qstrempty(&info->uri)) {
  68. debug("try reconnect port %s\n", qstrgetstr(&info->uri));
  69. hdl = DkStreamOpen(qstrgetstr(&info->uri),
  70. 0, 0, 0, 0);
  71. if (!hdl)
  72. return -PAL_ERRNO;
  73. }
  74. info->pal_handle = hdl;
  75. }
  76. if (!info->pal_handle)
  77. info->pal_handle = hdl;
  78. if (info->pal_handle)
  79. add_ipc_port_by_id(info->vmid == cur_process.vmid ? 0 : info->vmid,
  80. info->pal_handle, type, NULL, &info->port);
  81. return 0;
  82. }
  83. static void ipc_broadcast_exit (struct shim_ipc_port * port, IDTYPE vmid,
  84. unsigned exitcode)
  85. {
  86. // Arguments for compatibility
  87. __UNUSED(vmid);
  88. __UNUSED(exitcode);
  89. if (port == broadcast_port) {
  90. MASTER_LOCK();
  91. broadcast_port = NULL;
  92. put_ipc_port(port);
  93. MASTER_UNLOCK();
  94. }
  95. }
  96. int init_ipc_ports (void)
  97. {
  98. int ret = 0;
  99. if (!(port_mgr = create_mem_mgr(init_align_up(PORT_MGR_ALLOC))))
  100. return -ENOMEM;
  101. if ((ret = init_ipc_port(cur_process.self, NULL, IPC_PORT_SERVER)) < 0)
  102. return ret;
  103. if (PAL_CB(parent_process) &&
  104. (ret = init_ipc_port(cur_process.parent, PAL_CB(parent_process),
  105. IPC_PORT_DIRPRT|IPC_PORT_LISTEN)) < 0)
  106. return ret;
  107. if ((ret = init_ipc_port(cur_process.ns[PID_NS], NULL,
  108. IPC_PORT_PIDLDR|IPC_PORT_LISTEN)) < 0)
  109. return ret;
  110. if ((ret = init_ipc_port(cur_process.ns[SYSV_NS], NULL,
  111. IPC_PORT_SYSVLDR|IPC_PORT_LISTEN)) < 0)
  112. return ret;
  113. if (PAL_CB(broadcast_stream))
  114. add_ipc_port_by_id(0, PAL_CB(broadcast_stream), IPC_PORT_LISTEN,
  115. &ipc_broadcast_exit, &broadcast_port);
  116. return 0;
  117. }
  118. static int create_ipc_helper (void);
  119. /* This function should be called as part of init, before locks or atomics are
  120. * required */
  121. int init_ipc_helper (void)
  122. {
  123. bool need_helper = (ipc_helper_state == HELPER_DELAYED);
  124. ipc_helper_state = HELPER_NOTALIVE;
  125. create_lock(&ipc_helper_lock);
  126. create_event(&ipc_helper_event);
  127. if (need_helper) {
  128. /*
  129. * we are enabling multi-threading, must turn on threading
  130. * before grabbing any lock
  131. */
  132. enable_locking();
  133. /* Go ahead and lock the ipc helper lock here, for consistency */
  134. lock(&ipc_helper_lock);
  135. create_ipc_helper();
  136. unlock(&ipc_helper_lock);
  137. }
  138. return 0;
  139. }
  140. static void __get_ipc_port (struct shim_ipc_port * pobj)
  141. {
  142. #ifdef DEBUG_REF
  143. int ref_count = REF_INC(pobj->ref_count);
  144. debug("get ipc_port %p (handle %p, ref_count = %d)\n", pobj,
  145. pobj->pal_handle, ref_count);
  146. #else
  147. REF_INC(pobj->ref_count);
  148. #endif
  149. }
  150. static void __free_ipc_port (struct shim_ipc_port * pobj)
  151. {
  152. if (pobj->pal_handle) {
  153. DkObjectClose(pobj->pal_handle);
  154. pobj->pal_handle = NULL;
  155. }
  156. destroy_lock(&pobj->msgs_lock);
  157. free_mem_obj_to_mgr(port_mgr, pobj);
  158. }
  159. static void __put_ipc_port (struct shim_ipc_port * pobj)
  160. {
  161. int ref_count = REF_DEC(pobj->ref_count);
  162. #ifdef DEBUG_REF
  163. debug("put ipc port %p (handle %p, ref_count = %d)\n", pobj,
  164. pobj->pal_handle, ref_count);
  165. #endif
  166. if (!ref_count)
  167. __free_ipc_port(pobj);
  168. }
  169. /* This should be called with the ipc_helper_lock held */
  170. static inline void restart_ipc_helper (bool need_create)
  171. {
  172. switch (ipc_helper_state) {
  173. case HELPER_UNINITIALIZED:
  174. ipc_helper_state = HELPER_DELAYED;
  175. case HELPER_DELAYED:
  176. return;
  177. case HELPER_NOTALIVE:
  178. if (need_create)
  179. create_ipc_helper();
  180. return;
  181. case HELPER_ALIVE:
  182. if (IN_HELPER()) {
  183. ipc_helper_update = true;
  184. return;
  185. }
  186. debug("set ipc helper restart\n");
  187. set_event(&ipc_helper_event, 1);
  188. return;
  189. case HELPER_HANDEDOVER:
  190. ipc_helper_update = true;
  191. return;
  192. }
  193. }
  194. static bool __add_ipc_port (struct shim_ipc_port * port, IDTYPE vmid,
  195. IDTYPE type, port_fini fini)
  196. {
  197. bool need_restart = false;
  198. assert(vmid != cur_process.vmid);
  199. if (vmid && !port->info.vmid) {
  200. port->info.vmid = vmid;
  201. port->update = true;
  202. }
  203. if (port->info.vmid && LIST_EMPTY(port, hlist)) {
  204. LISTP_TYPE(shim_ipc_port) * head = &ipc_port_pool[PID_HASH(vmid)];
  205. __get_ipc_port(port);
  206. LISTP_ADD(port, head, hlist);
  207. }
  208. if (!(port->info.type & IPC_PORT_IFPOLL) && (type & IPC_PORT_IFPOLL))
  209. need_restart = true;
  210. if ((port->info.type & type) != type) {
  211. port->info.type |= type;
  212. port->update = true;
  213. }
  214. if (fini && (type & ~IPC_PORT_IFPOLL)) {
  215. port_fini * cb = port->fini;
  216. for ( ; cb < port->fini + MAX_IPC_PORT_FINI_CB ; cb++)
  217. if (!*cb || *cb == fini)
  218. break;
  219. assert(cb < port->fini + MAX_IPC_PORT_FINI_CB);
  220. *cb = fini;
  221. }
  222. if (need_restart) {
  223. if (LIST_EMPTY(port, list)) {
  224. __get_ipc_port(port);
  225. LISTP_ADD(port, &pobj_list, list);
  226. port->recent = true;
  227. } else {
  228. if (!port->recent) {
  229. LISTP_DEL_INIT(port, &pobj_list, list);
  230. LISTP_ADD(port, &pobj_list, list);
  231. port->recent = true;
  232. }
  233. }
  234. return true;
  235. } else {
  236. if (LIST_EMPTY(port, list)) {
  237. __get_ipc_port(port);
  238. LISTP_ADD_TAIL(port, &pobj_list, list);
  239. }
  240. return false;
  241. }
  242. }
  243. void add_ipc_port (struct shim_ipc_port * port, IDTYPE vmid, IDTYPE type,
  244. port_fini fini)
  245. {
  246. debug("adding port %p (handle %p) for process %u (type=%04x)\n",
  247. port, port->pal_handle, port->info.vmid, type);
  248. lock(&ipc_helper_lock);
  249. bool need_restart = __add_ipc_port(port, vmid, type, fini);
  250. if (need_restart)
  251. restart_ipc_helper(true);
  252. unlock(&ipc_helper_lock);
  253. }
  254. static struct shim_ipc_port * __get_new_ipc_port (PAL_HANDLE hdl)
  255. {
  256. struct shim_ipc_port * port =
  257. get_mem_obj_from_mgr_enlarge(port_mgr,
  258. size_align_up(PORT_MGR_ALLOC));
  259. if (!port) {
  260. debug("failed to allocate shim_ipc_port\n");
  261. return NULL;
  262. }
  263. memset(port, 0, sizeof(struct shim_ipc_port));
  264. port->pal_handle = hdl;
  265. port->update = true;
  266. INIT_LIST_HEAD(port, hlist);
  267. INIT_LIST_HEAD(port, list);
  268. INIT_LISTP(&port->msgs);
  269. REF_SET(port->ref_count, 1);
  270. create_lock(&port->msgs_lock);
  271. return port;
  272. }
  273. void add_ipc_port_by_id (IDTYPE vmid, PAL_HANDLE hdl, IDTYPE type,
  274. port_fini fini, struct shim_ipc_port ** portptr)
  275. {
  276. debug("adding port (handle %p) for process %u (type %04x)\n",
  277. hdl, vmid, type);
  278. assert(!!hdl && PAL_GET_TYPE(hdl));
  279. lock(&ipc_helper_lock);
  280. LISTP_TYPE(shim_ipc_port) * head = vmid ? &ipc_port_pool[PID_HASH(vmid)] : NULL;
  281. struct shim_ipc_port * tmp, * port = NULL;
  282. if (vmid)
  283. LISTP_FOR_EACH_ENTRY(tmp, head, hlist)
  284. if (tmp->info.vmid == vmid && tmp->pal_handle == hdl) {
  285. port = tmp;
  286. __get_ipc_port(port);
  287. break;
  288. }
  289. if (!port)
  290. LISTP_FOR_EACH_ENTRY(tmp, &pobj_list, list)
  291. if (tmp->pal_handle == hdl) {
  292. port = tmp;
  293. __get_ipc_port(port);
  294. break;
  295. }
  296. if (!port && !(port = __get_new_ipc_port(hdl))) {
  297. *portptr = NULL;
  298. goto out;
  299. }
  300. bool need_restart = __add_ipc_port(port, vmid, type, fini);
  301. assert(!LIST_EMPTY(port, list));
  302. assert(!vmid || !LIST_EMPTY(port, hlist));
  303. if (portptr)
  304. *portptr = port;
  305. else
  306. __put_ipc_port(port);
  307. if (need_restart)
  308. restart_ipc_helper(true);
  309. out:
  310. unlock(&ipc_helper_lock);
  311. }
  312. static bool __del_ipc_port (struct shim_ipc_port * port, IDTYPE type)
  313. {
  314. debug("deleting port %p (handle %p) for process %u\n",
  315. port, port->pal_handle, port->info.vmid);
  316. __get_ipc_port(port); // Prevent the object from being freed during deletion
  317. assert(!LIST_EMPTY(port, list)); // Never delete a port twice
  318. bool need_restart = false;
  319. type = type ? (type & port->info.type) : port->info.type;
  320. if ((type & IPC_PORT_KEEPALIVE) ^
  321. (port->info.type & IPC_PORT_KEEPALIVE))
  322. need_restart = true;
  323. /* if the port still have other usage, we will not remove the port */
  324. if (port->info.type & ~(type|IPC_PORT_IFPOLL|IPC_PORT_KEEPALIVE)) {
  325. debug("masking port %p (handle %p): type %x->%x\n",
  326. port, port->pal_handle, port->info.type, port->info.type & ~type);
  327. port->info.type &= ~type;
  328. goto out;
  329. }
  330. // Prevent further usage of the PAL handle
  331. DkStreamDelete(port->pal_handle, 0);
  332. if (port->info.type & IPC_PORT_IFPOLL)
  333. need_restart = true;
  334. // Officially delete the port
  335. LISTP_DEL_INIT(port, &pobj_list, list);
  336. port->info.type &= IPC_PORT_IFPOLL;
  337. __put_ipc_port(port);
  338. if (!LIST_EMPTY(port, hlist)) {
  339. // Re-fetch head pointer
  340. LISTP_TYPE(shim_ipc_port) * head = &ipc_port_pool[PID_HASH(port->info.vmid)];
  341. LISTP_DEL_INIT(port, head, hlist);
  342. __put_ipc_port(port);
  343. }
  344. // Need to check if there are any pending messages on the port, which means
  345. // some threads might be blocking for responses.
  346. lock(&port->msgs_lock);
  347. struct shim_ipc_msg_obj * msg, * n;
  348. LISTP_FOR_EACH_ENTRY_SAFE(msg, n, &port->msgs, list) {
  349. LISTP_DEL_INIT(msg, &port->msgs, list);
  350. msg->retval = -ECONNRESET;
  351. if (msg->thread) {
  352. debug("wake up thread %d\n", msg->thread->tid);
  353. thread_wakeup(msg->thread);
  354. }
  355. }
  356. unlock(&port->msgs_lock);
  357. out:
  358. port->update = true;
  359. __put_ipc_port(port); // Free the object if ref_count is 0
  360. return need_restart;
  361. }
  362. void del_ipc_port (struct shim_ipc_port * port, IDTYPE type)
  363. {
  364. lock(&ipc_helper_lock);
  365. // If the port is already deleted, don't delete it again.
  366. if (LIST_EMPTY(port, list)) {
  367. unlock(&ipc_helper_lock);
  368. return;
  369. }
  370. bool need_restart = __del_ipc_port(port, type);
  371. if (need_restart)
  372. restart_ipc_helper(false);
  373. unlock(&ipc_helper_lock);
  374. }
  375. void del_ipc_port_by_id (IDTYPE vmid, IDTYPE type)
  376. {
  377. LISTP_TYPE(shim_ipc_port) * head = &ipc_port_pool[PID_HASH(vmid)];
  378. struct shim_ipc_port * port, *n;
  379. bool need_restart = false;
  380. lock(&ipc_helper_lock);
  381. LISTP_FOR_EACH_ENTRY_SAFE(port, n, head, hlist) {
  382. if (LIST_EMPTY(port, list))
  383. continue;
  384. debug("port %p (handle %p) for process %u in list %p\n",
  385. port, port->pal_handle, port->info.vmid, head);
  386. if (port->info.vmid == vmid && __del_ipc_port(port, type))
  387. need_restart = true;
  388. }
  389. if (need_restart)
  390. restart_ipc_helper(false);
  391. unlock(&ipc_helper_lock);
  392. }
  393. void del_ipc_port_fini (struct shim_ipc_port * port, unsigned int exitcode)
  394. {
  395. port_fini fini[MAX_IPC_PORT_FINI_CB];
  396. int nfini = 0;
  397. assert(REF_GET(port->ref_count) > 0);
  398. lock(&ipc_helper_lock);
  399. // If the port is already deleted, don't delete it again.
  400. if (LIST_EMPTY(port, list)) {
  401. unlock(&ipc_helper_lock);
  402. return;
  403. }
  404. IDTYPE vmid = port->info.vmid;
  405. for (int i = 0 ; i < MAX_IPC_PORT_FINI_CB ; i++)
  406. if (port->fini[i]) {
  407. fini[nfini++] = port->fini[i];
  408. port->fini[i] = NULL;
  409. }
  410. bool need_restart = __del_ipc_port(port, 0);
  411. if (need_restart)
  412. restart_ipc_helper(false);
  413. unlock(&ipc_helper_lock);
  414. for (int i = 0 ; i < nfini ; i++)
  415. (fini[i])(port, vmid, exitcode);
  416. }
  417. static struct shim_ipc_port * __lookup_ipc_port (IDTYPE vmid, IDTYPE type)
  418. {
  419. LISTP_TYPE(shim_ipc_port) * head = &ipc_port_pool[PID_HASH(vmid)];
  420. struct shim_ipc_port * tmp;
  421. LISTP_FOR_EACH_ENTRY(tmp, head, hlist)
  422. if (tmp->info.vmid == vmid && (!type || tmp->info.type & type)) {
  423. debug("found port %p (handle %p) for process %u (type %04x)\n",
  424. tmp, tmp->pal_handle, tmp->info.vmid, tmp->info.type);
  425. __get_ipc_port(tmp);
  426. return tmp;
  427. }
  428. return NULL;
  429. }
  430. struct shim_ipc_port * lookup_ipc_port (IDTYPE vmid, IDTYPE type)
  431. {
  432. lock(&ipc_helper_lock);
  433. struct shim_ipc_port * port = __lookup_ipc_port(vmid, type);
  434. if (port) {
  435. assert(!LIST_EMPTY(port, list));
  436. assert(!vmid || !LIST_EMPTY(port, hlist));
  437. }
  438. unlock(&ipc_helper_lock);
  439. return port;
  440. }
  441. void get_ipc_port (struct shim_ipc_port * port)
  442. {
  443. // No need to grab ipc_helper_lock because __get_ipc_port() is atomic.
  444. __get_ipc_port(port);
  445. }
  446. void put_ipc_port (struct shim_ipc_port * port)
  447. {
  448. int ref_count = REF_DEC(port->ref_count);
  449. #ifdef DEBUG_REF
  450. debug("put ipc port %p (handle %p, ref_count = %d)\n", port,
  451. port->pal_handle, ref_count);
  452. #endif
  453. if (!ref_count) {
  454. lock(&ipc_helper_lock); // Need to grab the lock
  455. __free_ipc_port(port);
  456. unlock(&ipc_helper_lock);
  457. }
  458. }
  459. void del_all_ipc_ports (IDTYPE type)
  460. {
  461. struct shim_ipc_port * pobj, * n;
  462. bool need_restart = false;
  463. lock(&ipc_helper_lock);
  464. LISTP_FOR_EACH_ENTRY_SAFE(pobj, n, &pobj_list, list) {
  465. if (__del_ipc_port(pobj, type))
  466. need_restart = true;
  467. }
  468. if (need_restart)
  469. restart_ipc_helper(false);
  470. unlock(&ipc_helper_lock);
  471. }
  472. int broadcast_ipc (struct shim_ipc_msg * msg, struct shim_ipc_port ** exclude,
  473. int exsize, int target_type)
  474. {
  475. struct shim_ipc_port ** exend = exclude + exsize, ** ex;
  476. struct shim_ipc_port * pobj;
  477. if (!target_type && broadcast_port) {
  478. for (ex = exclude ; ex < exend && *ex != broadcast_port ; ex++);
  479. if (ex != exend)
  480. return 0;
  481. debug("send to broadcast stream\n");
  482. int ret = send_ipc_message(msg, broadcast_port);
  483. if (!ret)
  484. return 0;
  485. }
  486. lock(&ipc_helper_lock);
  487. int ntargets = 0;
  488. LISTP_FOR_EACH_ENTRY(pobj, &pobj_list, list) {
  489. debug("found port %p (handle %p) for process %u (type %04x)\n", pobj,
  490. pobj->pal_handle, pobj->info.vmid, pobj->info.type);
  491. if (pobj->info.type & target_type)
  492. ntargets++;
  493. }
  494. struct shim_ipc_port ** targets = __alloca(sizeof(struct shim_ipc_port *)
  495. * ntargets);
  496. int i = 0;
  497. LISTP_FOR_EACH_ENTRY(pobj, &pobj_list, list)
  498. if (pobj->info.type & target_type) {
  499. get_ipc_port(pobj);
  500. targets[i++] = pobj;
  501. }
  502. unlock(&ipc_helper_lock);
  503. for (i = 0 ; i < ntargets ; i++) {
  504. pobj = targets[i];
  505. debug("broadcast to port %p (handle %p) for process %u "
  506. "(type %x, target %x)\n",
  507. pobj, pobj->pal_handle, pobj->info.vmid,
  508. pobj->info.type, target_type);
  509. if (exsize) {
  510. for (ex = exclude ; ex < exend && *ex != pobj ; ex++);
  511. if (ex != exend)
  512. continue;
  513. }
  514. msg->dst = pobj->info.vmid;
  515. /* has to be assigned, so shim_send_ipc_message will not try
  516. to grab ipc_helper_lock */
  517. send_ipc_message(msg, pobj);
  518. put_ipc_port(pobj);
  519. }
  520. return 0;
  521. }
  522. static int ipc_resp_callback (IPC_CALLBACK_ARGS)
  523. {
  524. struct shim_ipc_resp * msgin = (struct shim_ipc_resp *) &msg->msg;
  525. debug("ipc callback from %u: IPC_RESP(%d)\n", msg->src, msgin->retval);
  526. if (!msg->seq)
  527. return msgin->retval;
  528. struct shim_ipc_msg_obj * obj = find_ipc_msg_duplex(port, msg->seq);
  529. if (obj) {
  530. obj->retval = msgin->retval;
  531. if (obj->thread)
  532. thread_wakeup(obj->thread);
  533. return 0;
  534. }
  535. return msgin->retval;
  536. }
  537. static ipc_callback ipc_callbacks [IPC_CODE_NUM] = {
  538. /* RESP */ &ipc_resp_callback,
  539. /* FINDURI */ &ipc_finduri_callback,
  540. /* TELLURI */ &ipc_telluri_callback,
  541. /* CHECKPOINT */ &ipc_checkpoint_callback,
  542. /* parents and children */
  543. /* CLD_EXIT */ &ipc_cld_exit_callback,
  544. /* CLD_JOIN */ &ipc_cld_join_callback,
  545. #ifdef PROFILE
  546. /* CLD_PROFILE */ &ipc_cld_profile_callback,
  547. #endif
  548. /* pid namespace */
  549. IPC_NS_CALLBACKS(pid)
  550. /* PID_KILL */ &ipc_pid_kill_callback,
  551. /* PID_GETSTATUS */ &ipc_pid_getstatus_callback,
  552. /* PID_RETSTATUS */ &ipc_pid_retstatus_callback,
  553. /* PID_GETMETA */ &ipc_pid_getmeta_callback,
  554. /* PID_RETMETA */ &ipc_pid_retmeta_callback,
  555. /* PID_NOP */ &ipc_pid_nop_callback,
  556. /* PID_SENDRPC */ &ipc_pid_sendrpc_callback,
  557. /* sysv namespace */
  558. IPC_NS_CALLBACKS(sysv)
  559. IPC_NS_KEY_CALLBACKS(sysv)
  560. /* SYSV_DELRES */ &ipc_sysv_delres_callback,
  561. /* SYSV_MOVRES */ &ipc_sysv_movres_callback,
  562. /* SYSV_MSGSND */ &ipc_sysv_msgsnd_callback,
  563. /* SYSV_MSGRCV */ &ipc_sysv_msgrcv_callback,
  564. /* SYSV_MSGMOV */ &ipc_sysv_msgmov_callback,
  565. /* SYSV_SEMOP */ &ipc_sysv_semop_callback,
  566. /* SYSV_SEMCTL */ &ipc_sysv_semctl_callback,
  567. /* SYSV_SEMRET */ &ipc_sysv_semret_callback,
  568. /* SYSV_SEMMOV */ &ipc_sysv_semmov_callback,
  569. };
  570. int __response_ipc_message (struct shim_ipc_port * port, IDTYPE dest,
  571. int ret, unsigned long seq)
  572. {
  573. struct shim_ipc_msg * resp = create_ipc_resp_msg_on_stack(ret, dest, seq);
  574. ret = (ret == RESPONSE_CALLBACK) ? 0 : ret;
  575. debug("ipc send to %u: IPC_RESP(%d)\n", resp->dst, ret);
  576. struct shim_ipc_resp * msgin = (struct shim_ipc_resp *) &resp->msg;
  577. msgin->retval = ret;
  578. return send_ipc_message(resp, port);
  579. }
  580. /* not only ipc helper thread can receive messsage, anyone can
  581. receive message if they have acquired (locked) the port */
  582. int receive_ipc_message (struct shim_ipc_port * port, unsigned long seq,
  583. struct shim_ipc_msg ** msgptr)
  584. {
  585. int readahead = IPC_MSG_READAHEAD;
  586. int bufsize = IPC_MSG_MINIMAL_SIZE + readahead;
  587. struct shim_ipc_msg * msg = __alloca(bufsize);
  588. int expected_size;
  589. int bytes = 0, ret = 0;
  590. do {
  591. expected_size = IPC_MSG_MINIMAL_SIZE;
  592. while (bytes < expected_size) {
  593. retry_read:
  594. if (expected_size + readahead > bufsize) {
  595. while (expected_size + readahead > bufsize)
  596. bufsize *= 2;
  597. void * new_buff = __alloca(bufsize);
  598. memcpy(new_buff, msg, bytes);
  599. msg = new_buff;
  600. }
  601. if (!(ret = DkStreamRead(port->pal_handle, 0,
  602. expected_size - bytes + readahead,
  603. (void *) msg + bytes, NULL, 0)))
  604. break;
  605. bytes += ret;
  606. }
  607. if (!bytes) {
  608. if (PAL_NATIVE_ERRNO) {
  609. debug("port %p (handle %p) is removed at reading\n",
  610. port, port->pal_handle);
  611. del_ipc_port_fini(port, -ECHILD);
  612. ret = -PAL_ERRNO;
  613. }
  614. break;
  615. }
  616. debug("receive a message from port %p (handle %p): "
  617. "code=%d size=%d src=%u dst=%u seq=%lx\n",
  618. port, port->pal_handle,
  619. msg->code, msg->size, msg->src, msg->dst, msg->seq);
  620. expected_size = msg->size;
  621. if (bytes < expected_size)
  622. goto retry_read;
  623. if (msgptr && (!seq || msg->seq == seq)) {
  624. struct shim_ipc_msg * retmsg;
  625. if (*msgptr) {
  626. if (msg->size > (*msgptr)->size)
  627. msg->size = (*msgptr)->size;
  628. retmsg = *msgptr;
  629. } else {
  630. *msgptr = retmsg = malloc(msg->size);
  631. }
  632. memcpy(retmsg, msg, msg->size);
  633. return 0;
  634. }
  635. /* skip if the message comes from myself (it's possible because
  636. of the broadcast channel */
  637. if (msg->src == cur_process.vmid)
  638. goto next;
  639. ipc_callback callback = ipc_callbacks[msg->code];
  640. if (callback) {
  641. ret = (*callback) (msg, port);
  642. if ((ret < 0 || ret == RESPONSE_CALLBACK) && msg->seq)
  643. /* only helper thread sends back response */
  644. ret = __response_ipc_message(port, msg->src, ret, msg->seq);
  645. }
  646. next:
  647. if ((bytes -= expected_size) > 0)
  648. memmove(msg, (void *) msg + expected_size, bytes);
  649. } while (bytes > 0 || (seq && msg->seq != seq));
  650. if (msgptr)
  651. *msgptr = NULL;
  652. return ret;
  653. }
  654. #define IPC_HELPER_STACK_SIZE (allocsize * 4)
  655. #define IPC_HELPER_LIST_INIT_SIZE 32
  656. noreturn static void shim_ipc_helper_end(struct shim_thread * self)
  657. {
  658. /* Put our handle map reference */
  659. if (self->handle_map)
  660. put_handle_map(self->handle_map);
  661. /* Another thread may be calling shim_clean(). Lower the chances of our
  662. * IPC helper thread and another thread competing on shim_clean/shim_terminate
  663. * (which is benign due to protection via ipc_helper_lock) by adding a barrier
  664. * to ensure reading the latest IPC helper state. */
  665. COMPILER_BARRIER();
  666. if (ipc_helper_state == HELPER_HANDEDOVER) {
  667. debug("ipc helper thread is the last thread, process exiting\n");
  668. shim_terminate(0); // Same as shim_clean(), but this is the official termination function
  669. }
  670. lock(&ipc_helper_lock);
  671. ipc_helper_state = HELPER_NOTALIVE;
  672. ipc_helper_thread = NULL;
  673. unlock(&ipc_helper_lock);
  674. put_thread(self);
  675. debug("ipc helper thread terminated\n");
  676. DkThreadExit();
  677. }
  678. noreturn static void __shim_ipc_helper (void * dummy)
  679. {
  680. __UNUSED(dummy);
  681. struct shim_thread * self = get_cur_thread();
  682. void * stack = self->stack;
  683. int port_num = 0, port_size = IPC_HELPER_LIST_INIT_SIZE;
  684. struct shim_ipc_port ** local_pobjs = stack, * pobj;
  685. PAL_HANDLE * local_ports;
  686. PAL_HANDLE ipc_event_handle = event_handle(&ipc_helper_event);
  687. int nalive = 0;
  688. PAL_HANDLE polled = NULL;
  689. int count = -1;
  690. local_ports = (PAL_HANDLE *) (local_pobjs + port_size);
  691. local_ports[0] = ipc_event_handle;
  692. goto update_status;
  693. /* The compiler should be careful not to cache the ipc_helper_state or
  694. * else ths loop could fail to terminate on update. Use a compiler
  695. * barrier to force a re-read after sleeping. */
  696. while ((ipc_helper_state == HELPER_ALIVE) ||
  697. nalive) {
  698. /* do a global poll on all the ports */
  699. polled = DkObjectsWaitAny(port_num + 1, local_ports, NO_TIMEOUT);
  700. COMPILER_BARRIER();
  701. if (!polled)
  702. continue;
  703. /* before we locking pobj list, at least we can look at the returned
  704. port if it is the ipc helper event */
  705. if (polled == ipc_event_handle) {
  706. clear_event(&ipc_helper_event);
  707. update_status:
  708. COMPILER_BARRIER();
  709. if (ipc_helper_state == HELPER_NOTALIVE)
  710. goto end;
  711. else
  712. goto update_list;
  713. }
  714. pobj = NULL;
  715. count = -1;
  716. for (int i = 0 ; i < port_num ; i++)
  717. if (polled == local_pobjs[i]->pal_handle) {
  718. pobj = local_pobjs[i];
  719. count = i;
  720. break;
  721. }
  722. if (!pobj)
  723. continue;
  724. /* if the polled port is a server port, accept a client and add it
  725. to the port list */
  726. if (pobj->private.type & IPC_PORT_SERVER) {
  727. PAL_HANDLE cli = DkStreamWaitForClient(polled);
  728. if (cli) {
  729. IDTYPE type = (pobj->private.type & ~IPC_PORT_SERVER) |
  730. IPC_PORT_LISTEN;
  731. add_ipc_port_by_id(pobj->private.vmid, cli, type,
  732. NULL, NULL);
  733. } else {
  734. debug("port %p (handle %p) is removed at accepting\n",
  735. pobj, polled);
  736. del_ipc_port_fini(pobj, -ECHILD);
  737. }
  738. polled = NULL;
  739. count = -1;
  740. goto update_list;
  741. }
  742. PAL_STREAM_ATTR attr;
  743. if (!DkStreamAttributesQueryByHandle(polled, &attr)) {
  744. debug("port %p (handle %p) is removed at querying\n",
  745. pobj, polled);
  746. del_ipc_port_fini(pobj, -PAL_ERRNO);
  747. goto update_list;
  748. }
  749. if (attr.readable)
  750. receive_ipc_message(pobj, 0, NULL);
  751. if (attr.disconnected) {
  752. debug("port %p (handle %p) is disconnected\n",
  753. pobj, polled);
  754. del_ipc_port_fini(pobj, -ECONNRESET);
  755. goto update_list;
  756. }
  757. if (!ipc_helper_update)
  758. continue;
  759. update_list:
  760. ipc_helper_update = false;
  761. lock(&ipc_helper_lock);
  762. int compact = 0;
  763. /* first walk though all the polling ports and remove the one
  764. being deleted. */
  765. for (int i = 0 ; i < port_num ; i++) {
  766. struct shim_ipc_port * pobj = local_pobjs[i];
  767. // If the port is removed from the list or intended to be deleted,
  768. // remove the port from the polling array
  769. if (LIST_EMPTY(pobj, list)) {
  770. if (polled == pobj->pal_handle) {
  771. polled = NULL;
  772. count = -1;
  773. }
  774. local_pobjs[i] = NULL;
  775. if (pobj->private.type & IPC_PORT_KEEPALIVE)
  776. nalive--;
  777. __put_ipc_port(pobj);
  778. compact++;
  779. continue;
  780. }
  781. if (pobj->update) {
  782. if (pobj->info.type & IPC_PORT_KEEPALIVE) {
  783. if (!(pobj->private.type & IPC_PORT_KEEPALIVE))
  784. nalive--;
  785. } else {
  786. if (pobj->private.type & IPC_PORT_KEEPALIVE)
  787. nalive++;
  788. }
  789. pobj->private = pobj->info;
  790. pobj->update = false;
  791. }
  792. if (compact) {
  793. if (polled == pobj->pal_handle)
  794. count -= compact;
  795. local_pobjs[i - compact] = pobj;
  796. local_ports[i - compact + 1] = pobj->pal_handle;
  797. }
  798. }
  799. port_num -= compact;
  800. LISTP_FOR_EACH_ENTRY(pobj, &pobj_list, list) {
  801. /* we only update among recently updated ports */
  802. if (!pobj->recent)
  803. break;
  804. if (pobj->update) {
  805. pobj->private = pobj->info;
  806. pobj->update = false;
  807. }
  808. assert(pobj->private.type & IPC_PORT_IFPOLL);
  809. if (port_num == port_size) {
  810. port_size *= 2;
  811. memmove(local_pobjs + port_size,
  812. local_ports,
  813. (port_num + 1) * sizeof(PAL_HANDLE));
  814. local_ports = (PAL_HANDLE *) (local_pobjs + port_size);
  815. }
  816. pobj->recent = false;
  817. __get_ipc_port(pobj);
  818. local_pobjs[port_num] = pobj;
  819. local_ports[port_num + 1] = pobj->pal_handle;
  820. port_num++;
  821. if (pobj->private.type & IPC_PORT_KEEPALIVE)
  822. nalive++;
  823. debug("listen to process %u on port %p (handle %p, type %04x)\n",
  824. pobj->private.vmid,
  825. pobj,
  826. pobj->pal_handle,
  827. pobj->private.type);
  828. }
  829. unlock(&ipc_helper_lock);
  830. }
  831. for (int i = 0 ; i < port_num ; i++) {
  832. struct shim_ipc_port * pobj = local_pobjs[i];
  833. __put_ipc_port(pobj);
  834. }
  835. end:
  836. shim_ipc_helper_end(self);
  837. }
  838. static void shim_ipc_helper (void * arg)
  839. {
  840. /* set ipc helper thread */
  841. struct shim_thread * self = (struct shim_thread *) arg;
  842. if (!arg)
  843. return;
  844. __libc_tcb_t tcb;
  845. allocate_tls(&tcb, false, self);
  846. debug_setbuf(&tcb.shim_tcb, true);
  847. debug("set tcb to %p\n", &tcb);
  848. lock(&ipc_helper_lock);
  849. bool notme = (self != ipc_helper_thread);
  850. unlock(&ipc_helper_lock);
  851. if (notme) {
  852. put_thread(self);
  853. DkThreadExit();
  854. return;
  855. }
  856. debug("ipc helper thread started\n");
  857. void * stack = allocate_stack(IPC_HELPER_STACK_SIZE, allocsize, false);
  858. if (!stack) {
  859. shim_ipc_helper_end(self);
  860. return;
  861. }
  862. self->stack_top = stack + IPC_HELPER_STACK_SIZE;
  863. self->stack = stack;
  864. __SWITCH_STACK(self->stack_top, __shim_ipc_helper, NULL);
  865. }
  866. /* This function shoudl be called with the ipc_helper_lock held */
  867. static int create_ipc_helper (void)
  868. {
  869. int ret = 0;
  870. /* If we are holding the lock, no barrier is needed here, as
  871. * the lock (and new function) form an implicit barrier, and
  872. * any "recent" changes should have come from this thread */
  873. if (ipc_helper_state == HELPER_ALIVE)
  874. return 0;
  875. struct shim_thread * new = get_new_internal_thread();
  876. if (!new)
  877. return -ENOMEM;
  878. ipc_helper_thread = new;
  879. ipc_helper_state = HELPER_ALIVE;
  880. PAL_HANDLE handle = thread_create(shim_ipc_helper, new);
  881. if (!handle) {
  882. ret = -PAL_ERRNO;
  883. ipc_helper_thread = NULL;
  884. ipc_helper_state = HELPER_NOTALIVE;
  885. put_thread(new);
  886. return ret;
  887. }
  888. new->pal_handle = handle;
  889. return 0;
  890. }
  891. /*
  892. * on success, the reference to the helper thread is returned with
  893. * reference count incremented.
  894. * The caller is responsible to wait for the IPC helper thread to exit
  895. * and release the final reference to free related resources.
  896. * It's problematic for the thread itself to release its resources which it's
  897. * using. For example stack.
  898. * So defer releasing it after its exit and make the releasing the caller
  899. * responsibility.
  900. */
  901. int exit_with_ipc_helper (bool handover, struct shim_thread ** ret)
  902. {
  903. *ret = NULL;
  904. if (IN_HELPER() || ipc_helper_state != HELPER_ALIVE)
  905. return 0;
  906. lock(&ipc_helper_lock);
  907. if (handover) {
  908. handover = false;
  909. struct shim_ipc_port * pobj;
  910. LISTP_FOR_EACH_ENTRY(pobj, &pobj_list, list)
  911. if (pobj->info.type & IPC_PORT_KEEPALIVE) {
  912. handover = true;
  913. break;
  914. }
  915. }
  916. int new_state = HELPER_NOTALIVE;
  917. if (handover) {
  918. debug("handing over to ipc helper\n");
  919. new_state = HELPER_HANDEDOVER;
  920. } else {
  921. debug("exiting ipc helper\n");
  922. }
  923. ipc_helper_state = new_state;
  924. if (ipc_helper_thread != NULL) {
  925. get_thread(ipc_helper_thread);
  926. *ret = ipc_helper_thread;
  927. }
  928. unlock(&ipc_helper_lock);
  929. set_event(&ipc_helper_event, 1);
  930. if (new_state != HELPER_NOTALIVE) {
  931. return -EAGAIN;
  932. } else {
  933. /* We could get here via a signal handler invoked during
  934. * receive_ipc_message. Let that complete so that whoever
  935. * generated the signal doesn't hang waiting for IPC_RESP. */
  936. int loops = 0;
  937. while (ipc_helper_thread != NULL && loops++ < 2000) {
  938. COMPILER_BARRIER();
  939. DkThreadDelayExecution(1000);
  940. }
  941. if (ipc_helper_thread != NULL) {
  942. debug("timed out waiting for ipc helper to exit\n");
  943. }
  944. return 0;
  945. }
  946. }
  947. int terminate_ipc_helper (void)
  948. {
  949. lock(&ipc_helper_lock);
  950. struct shim_thread * thread = ipc_helper_thread;
  951. if (!thread) {
  952. unlock(&ipc_helper_lock);
  953. return -ESRCH;
  954. }
  955. debug("terminating ipc helper\n");
  956. ipc_helper_state = HELPER_NOTALIVE;
  957. set_event(&ipc_helper_event, 1);
  958. unlock(&ipc_helper_lock);
  959. return 0;
  960. }