shim_checkpoint.c 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  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_checkpoint.c
  15. *
  16. * This file contains codes for checkpoint / migration scheme of library OS.
  17. */
  18. #include "asm-offsets.h"
  19. #include <shim_internal.h>
  20. #include <shim_utils.h>
  21. #include <shim_thread.h>
  22. #include <shim_handle.h>
  23. #include <shim_vma.h>
  24. #include <shim_fs.h>
  25. #include <shim_checkpoint.h>
  26. #include <shim_ipc.h>
  27. #include <shim_profile.h>
  28. #include <pal.h>
  29. #include <pal_error.h>
  30. #include <list.h>
  31. #include <stdarg.h>
  32. #include <asm/fcntl.h>
  33. #include <asm/mman.h>
  34. DEFINE_PROFILE_CATEGORY(migrate, );
  35. DEFINE_PROFILE_CATEGORY(checkpoint, migrate);
  36. DEFINE_PROFILE_INTERVAL(checkpoint_create_map, checkpoint);
  37. DEFINE_PROFILE_INTERVAL(checkpoint_copy, checkpoint);
  38. DEFINE_PROFILE_CATEGORY(checkpoint_func, checkpoint);
  39. DEFINE_PROFILE_INTERVAL(checkpoint_destroy_map, checkpoint);
  40. DEFINE_PROFILE_OCCURENCE(checkpoint_count, checkpoint);
  41. DEFINE_PROFILE_OCCURENCE(checkpoint_total_size, checkpoint);
  42. DEFINE_PROFILE_CATEGORY(resume, migrate);
  43. DEFINE_PROFILE_INTERVAL(child_created_in_new_process, resume);
  44. DEFINE_PROFILE_INTERVAL(child_wait_header, resume);
  45. DEFINE_PROFILE_INTERVAL(child_receive_header, resume);
  46. DEFINE_PROFILE_INTERVAL(do_migration, resume);
  47. DEFINE_PROFILE_INTERVAL(child_load_checkpoint_on_pipe, resume);
  48. DEFINE_PROFILE_INTERVAL(child_receive_handles, resume);
  49. DEFINE_PROFILE_INTERVAL(restore_checkpoint, resume);
  50. DEFINE_PROFILE_CATEGORY(resume_func, resume);
  51. DEFINE_PROFILE_INTERVAL(child_total_migration_time, resume);
  52. #define CP_HASH_SIZE 256
  53. #define CP_HASH(addr) ((hashfunc((ptr_t)(addr))) & (CP_HASH_SIZE - 1))
  54. typedef uint16_t FASTHASHTYPE;
  55. #define CP_MAP_ENTRY_NUM 64
  56. DEFINE_LIST(cp_map_entry);
  57. struct cp_map_entry
  58. {
  59. LIST_TYPE(cp_map_entry) hlist;
  60. struct shim_cp_map_entry entry;
  61. };
  62. DEFINE_LISTP(cp_map_entry);
  63. struct cp_map {
  64. struct cp_map_buffer {
  65. struct cp_map_buffer * next;
  66. int num, cnt;
  67. struct cp_map_entry entries[0];
  68. } * buffers;
  69. struct hash_map {
  70. LISTP_TYPE(cp_map_entry) head[CP_HASH_SIZE];
  71. } map;
  72. };
  73. void * create_cp_map (void)
  74. {
  75. void * data = malloc(sizeof(struct cp_map) + sizeof(struct cp_map_buffer) +
  76. sizeof(struct cp_map_entry) * CP_MAP_ENTRY_NUM);
  77. if (!data)
  78. return NULL;
  79. struct cp_map * map = (struct cp_map *) data;
  80. struct cp_map_buffer * buffer =
  81. (struct cp_map_buffer *) (data + sizeof(struct cp_map));
  82. memset(map, 0, sizeof(*map));
  83. map->buffers = buffer;
  84. buffer->next = NULL;
  85. buffer->num = CP_MAP_ENTRY_NUM;
  86. buffer->cnt = 0;
  87. return (void *) map;
  88. }
  89. void destroy_cp_map (void * map)
  90. {
  91. struct cp_map * m = (struct cp_map *) map;
  92. struct cp_map_buffer * buffer = m->buffers, * next;
  93. for (next = buffer ? buffer->next : NULL ;
  94. buffer && next ;
  95. buffer = next, next = next ? next->next : NULL)
  96. free(buffer);
  97. free(m);
  98. }
  99. static inline
  100. struct cp_map_buffer * extend_cp_map (struct cp_map * map)
  101. {
  102. struct cp_map_buffer * buffer =
  103. malloc(sizeof(struct cp_map_buffer) +
  104. sizeof(struct cp_map_entry) * CP_MAP_ENTRY_NUM);
  105. if (!buffer)
  106. return NULL;
  107. buffer->next = map->buffers;
  108. map->buffers = buffer;
  109. buffer->num = CP_MAP_ENTRY_NUM;
  110. buffer->cnt = 0;
  111. return buffer;
  112. }
  113. struct shim_cp_map_entry *
  114. get_cp_map_entry (void * map, void * addr, bool create)
  115. {
  116. struct cp_map * m = (struct cp_map *) map;
  117. FASTHASHTYPE hash = CP_HASH(addr);
  118. LISTP_TYPE(cp_map_entry) * head = &m->map.head[hash];
  119. struct cp_map_entry * tmp;
  120. struct shim_cp_map_entry * e = NULL;
  121. LISTP_FOR_EACH_ENTRY(tmp, head, hlist)
  122. if (tmp->entry.addr == addr)
  123. e = &tmp->entry;
  124. if (create && !e) {
  125. struct cp_map_buffer * buffer = m->buffers;
  126. if (buffer->cnt == buffer->num)
  127. buffer = extend_cp_map(m);
  128. struct cp_map_entry *new = &buffer->entries[buffer->cnt++];
  129. INIT_LIST_HEAD(new, hlist);
  130. LISTP_ADD(new, head, hlist);
  131. new->entry.addr = addr;
  132. new->entry.off = 0;
  133. e = &new->entry;
  134. }
  135. return e;
  136. }
  137. BEGIN_CP_FUNC(memory)
  138. {
  139. struct shim_mem_entry * entry =
  140. (void *) (base + ADD_CP_OFFSET(sizeof(struct shim_mem_entry)));
  141. entry->addr = obj;
  142. entry->size = size;
  143. entry->paddr = NULL;
  144. entry->prot = PAL_PROT_READ|PAL_PROT_WRITE;
  145. entry->data = NULL;
  146. entry->prev = store->last_mem_entry;
  147. store->last_mem_entry = entry;
  148. store->mem_nentries++;
  149. store->mem_size += size;
  150. if (objp)
  151. *objp = entry;
  152. }
  153. END_CP_FUNC_NO_RS(memory)
  154. BEGIN_CP_FUNC(palhdl)
  155. {
  156. __UNUSED(size);
  157. ptr_t off = ADD_CP_OFFSET(sizeof(struct shim_palhdl_entry));
  158. struct shim_palhdl_entry * entry = (void *) (base + off);
  159. entry->handle = (PAL_HANDLE) obj;
  160. entry->uri = NULL;
  161. entry->phandle = NULL;
  162. entry->prev = store->last_palhdl_entry;
  163. store->last_palhdl_entry = entry;
  164. store->palhdl_nentries++;
  165. ADD_CP_FUNC_ENTRY(off);
  166. if (objp)
  167. *objp = entry;
  168. }
  169. END_CP_FUNC(palhdl)
  170. BEGIN_RS_FUNC(palhdl)
  171. {
  172. __UNUSED(offset);
  173. __UNUSED(rebase);
  174. struct shim_palhdl_entry * ent = (void *) (base + GET_CP_FUNC_ENTRY());
  175. if (ent->phandle && !ent->phandle && ent->uri) {
  176. /* XXX: reopen the stream */
  177. }
  178. }
  179. END_RS_FUNC(palhdl)
  180. BEGIN_CP_FUNC(migratable)
  181. {
  182. __UNUSED(obj);
  183. __UNUSED(size);
  184. __UNUSED(objp);
  185. struct shim_mem_entry * mem_entry;
  186. DO_CP_SIZE(memory, &__migratable, &__migratable_end - &__migratable,
  187. &mem_entry);
  188. struct shim_cp_entry * entry = ADD_CP_FUNC_ENTRY(0UL);
  189. mem_entry->paddr = (void **) &entry->cp_un.cp_val;
  190. }
  191. END_CP_FUNC(migratable)
  192. BEGIN_RS_FUNC(migratable)
  193. {
  194. __UNUSED(base);
  195. __UNUSED(offset);
  196. void * data = (void *) GET_CP_FUNC_ENTRY();
  197. CP_REBASE(data);
  198. memcpy(&__migratable, data, &__migratable_end - &__migratable);
  199. }
  200. END_RS_FUNC(migratable)
  201. BEGIN_CP_FUNC(environ)
  202. {
  203. __UNUSED(size);
  204. __UNUSED(objp);
  205. const char ** e, ** envp = (void *) obj;
  206. int nenvp = 0;
  207. int envp_bytes = 0;
  208. for (e = envp ; *e ; e++) {
  209. nenvp++;
  210. envp_bytes += strlen(*e) + 1;
  211. }
  212. ptr_t off = ADD_CP_OFFSET(sizeof(char *) * (nenvp + 1) + envp_bytes);
  213. const char ** new_envp = (void *) base + off;
  214. char * ptr = (void *) base + off + sizeof(char *) * (nenvp + 1);
  215. for (int i = 0 ; i < nenvp ; i++) {
  216. int len = strlen(envp[i]);
  217. new_envp[i] = ptr;
  218. memcpy(ptr, envp[i], len + 1);
  219. ptr += len + 1;
  220. }
  221. new_envp[nenvp] = NULL;
  222. ADD_CP_FUNC_ENTRY(off);
  223. }
  224. END_CP_FUNC(environ)
  225. BEGIN_RS_FUNC(environ)
  226. {
  227. __UNUSED(offset);
  228. const char ** envp = (void *) base + GET_CP_FUNC_ENTRY();
  229. const char ** e;
  230. for (e = envp ; *e ; e++) {
  231. CP_REBASE(*e);
  232. DEBUG_RS("%s", *e);
  233. }
  234. initial_envp = envp;
  235. }
  236. END_RS_FUNC(environ)
  237. BEGIN_CP_FUNC(qstr)
  238. {
  239. __UNUSED(size);
  240. __UNUSED(objp);
  241. struct shim_qstr * qstr = (struct shim_qstr *) obj;
  242. /* qstr is always embedded as sub-object in other objects so it is
  243. * automatically checkpointed as part of other checkpoint routines.
  244. * However, its oflow string resides in some other memory region
  245. * and must be checkpointed and restored explicitly. Copy oflow
  246. * string inside checkpoint right before qstr cp entry. */
  247. if (qstr->oflow) {
  248. struct shim_str * str =
  249. (void *) (base + ADD_CP_OFFSET(qstr->len + 1));
  250. memcpy(str, qstr->oflow, qstr->len + 1);
  251. ADD_CP_FUNC_ENTRY((ptr_t) qstr - base);
  252. }
  253. }
  254. END_CP_FUNC(qstr)
  255. BEGIN_RS_FUNC(qstr)
  256. {
  257. __UNUSED(offset);
  258. __UNUSED(rebase);
  259. /* If we are here, qstr has oflow string. We know that oflow string
  260. * is right before this qstr cp entry (aligned to 8B). Calculate
  261. * oflow string's base address and update qstr to point to it. */
  262. struct shim_qstr * qstr = (void *) (base + GET_CP_FUNC_ENTRY());
  263. size_t size = qstr->len + 1;
  264. size = ALIGN_UP(size, sizeof(void*));
  265. qstr->oflow = (void *)entry - size;
  266. }
  267. END_RS_FUNC(qstr)
  268. static int send_checkpoint_on_stream (PAL_HANDLE stream,
  269. struct shim_cp_store * store)
  270. {
  271. int mem_nentries = store->mem_nentries;
  272. struct shim_mem_entry ** mem_entries;
  273. if (mem_nentries) {
  274. mem_entries = __alloca(sizeof(struct shim_mem_entry *) * mem_nentries);
  275. int mem_cnt = mem_nentries;
  276. struct shim_mem_entry * mem_ent = store->last_mem_entry;
  277. for (; mem_ent ; mem_ent = mem_ent->prev) {
  278. if (!mem_cnt)
  279. return -EINVAL;
  280. mem_entries[--mem_cnt] = mem_ent;
  281. }
  282. void * mem_addr = (void *) store->base + store->offset;
  283. mem_entries += mem_cnt;
  284. mem_nentries -= mem_cnt;
  285. for (int i = 0 ; i < mem_nentries ; i++) {
  286. int mem_size = mem_entries[i]->size;
  287. mem_entries[i]->data = mem_addr;
  288. mem_addr += mem_size;
  289. }
  290. }
  291. size_t total_bytes = store->offset;
  292. size_t bytes = 0;
  293. do {
  294. PAL_NUM ret = DkStreamWrite(stream, 0, total_bytes - bytes,
  295. (void *) store->base + bytes, NULL);
  296. if (ret == PAL_STREAM_ERROR) {
  297. if (PAL_ERRNO == EINTR || PAL_ERRNO == EAGAIN ||
  298. PAL_ERRNO == EWOULDBLOCK)
  299. continue;
  300. return -PAL_ERRNO;
  301. }
  302. bytes += ret;
  303. } while (bytes < total_bytes);
  304. ADD_PROFILE_OCCURENCE(migrate_send_on_stream, total_bytes);
  305. for (int i = 0 ; i < mem_nentries ; i++) {
  306. size_t mem_size = mem_entries[i]->size;
  307. void * mem_addr = mem_entries[i]->addr;
  308. bytes = 0;
  309. do {
  310. PAL_NUM ret = DkStreamWrite(stream, 0, mem_size - bytes,
  311. mem_addr + bytes, NULL);
  312. if (ret == PAL_STREAM_ERROR) {
  313. if (PAL_ERRNO == EINTR || PAL_ERRNO == EAGAIN ||
  314. PAL_ERRNO == EWOULDBLOCK)
  315. continue;
  316. return -PAL_ERRNO;
  317. }
  318. bytes += ret;
  319. } while (bytes < mem_entries[i]->size);
  320. if (!(mem_entries[i]->prot & PAL_PROT_READ))
  321. DkVirtualMemoryProtect(mem_addr, mem_size, mem_entries[i]->prot);
  322. mem_entries[i]->size = mem_size;
  323. ADD_PROFILE_OCCURENCE(migrate_send_on_stream, mem_size);
  324. }
  325. return 0;
  326. }
  327. int restore_checkpoint (struct cp_header * cphdr, struct mem_header * memhdr,
  328. ptr_t base, ptr_t type)
  329. {
  330. ptr_t cpoffset = cphdr->offset;
  331. ptr_t * offset = &cpoffset;
  332. long rebase = base - (ptr_t) cphdr->addr;
  333. int ret = 0;
  334. if (type)
  335. debug("restore checkpoint at 0x%08lx rebased from %p (%s only)\n",
  336. base, cphdr->addr, CP_FUNC_NAME(type));
  337. else
  338. debug("restore checkpoint at 0x%08lx rebased from %p\n",
  339. base, cphdr->addr);
  340. if (memhdr && memhdr->nentries) {
  341. struct shim_mem_entry * entry =
  342. (void *) (base + memhdr->entoffset);
  343. for (; entry ; entry = entry->prev) {
  344. CP_REBASE(entry->prev);
  345. CP_REBASE(entry->paddr);
  346. if (entry->paddr) {
  347. *entry->paddr = entry->data;
  348. } else {
  349. debug("memory entry [%p]: %p-%p\n", entry, entry->addr,
  350. entry->addr + entry->size);
  351. PAL_PTR addr = ALLOC_ALIGN_DOWN_PTR(entry->addr);
  352. PAL_NUM size = ALLOC_ALIGN_UP_PTR(entry->addr + entry->size) - (void*)addr;
  353. PAL_FLG prot = entry->prot;
  354. if (!DkVirtualMemoryAlloc(addr, size, 0, prot|PAL_PROT_WRITE)) {
  355. debug("failed allocating %p-%p\n", addr, addr + size);
  356. return -PAL_ERRNO;
  357. }
  358. CP_REBASE(entry->data);
  359. memcpy(entry->addr, entry->data, entry->size);
  360. if (!(entry->prot & PAL_PROT_WRITE) &&
  361. !DkVirtualMemoryProtect(addr, size, prot)) {
  362. debug("failed protecting %p-%p (ignored)\n", addr, addr + size);
  363. }
  364. }
  365. }
  366. }
  367. struct shim_cp_entry * cpent = NEXT_CP_ENTRY();
  368. while (cpent) {
  369. if (cpent->cp_type < CP_FUNC_BASE)
  370. goto next;
  371. if (type && cpent->cp_type != type)
  372. goto next;
  373. rs_func rs = (&__rs_func) [cpent->cp_type - CP_FUNC_BASE];
  374. ret = (*rs) (cpent, base, offset, rebase);
  375. if (ret < 0) {
  376. SYS_PRINTF("restore_checkpoint() at %s (%d)\n",
  377. CP_FUNC_NAME(cpent->cp_type), ret);
  378. return ret;
  379. }
  380. next:
  381. cpent = NEXT_CP_ENTRY();
  382. }
  383. debug("successfully restore checkpoint loaded at 0x%08lx - 0x%08lx\n",
  384. base, base + cphdr->size);
  385. return 0;
  386. }
  387. int init_from_checkpoint_file (const char * filename,
  388. struct newproc_cp_header * hdr,
  389. void ** cpptr)
  390. {
  391. struct shim_dentry * dir = NULL;
  392. int ret;
  393. /* XXX: Not sure what to do here yet */
  394. __abort();
  395. ret = path_lookupat(NULL, filename, LOOKUP_ACCESS|LOOKUP_DIRECTORY, &dir, NULL);
  396. if (ret < 0)
  397. return ret;
  398. struct shim_mount * fs = dir->fs;
  399. struct shim_dirent * dirent;
  400. if (!fs->d_ops || !fs->d_ops->readdir) {
  401. ret = -EACCES;
  402. goto out;
  403. }
  404. if ((ret = fs->d_ops->readdir(dir, &dirent)) < 0)
  405. goto out;
  406. struct shim_dentry * first = NULL;
  407. struct shim_dirent * d = dirent;
  408. for ( ; d ; d = d->next) {
  409. struct shim_dentry * file;
  410. if ((ret = lookup_dentry(dir, d->name, strlen(d->name),
  411. &file, dir->fs)) < 0)
  412. continue;
  413. if (file->state & DENTRY_NEGATIVE)
  414. continue;
  415. if (!first) {
  416. first = file;
  417. continue;
  418. }
  419. const char * argv[3];
  420. argv[0] = "-resume-file";
  421. argv[1] = dentry_get_path(file, true, NULL);
  422. argv[2] = 0;
  423. PAL_HANDLE proc = DkProcessCreate(NULL, argv);
  424. if (!proc) {
  425. ret = -PAL_ERRNO;
  426. goto out;
  427. }
  428. put_dentry(file);
  429. }
  430. if (first) {
  431. ret = restore_from_file(dentry_get_path(first, true, NULL), hdr, cpptr);
  432. put_dentry(first);
  433. }
  434. free(dirent);
  435. out:
  436. put_dentry(dir);
  437. return ret;
  438. }
  439. int restore_from_file (const char * filename, struct newproc_cp_header * hdr,
  440. void ** cpptr)
  441. {
  442. struct shim_handle * file = get_new_handle();
  443. if (!file)
  444. return -ENOMEM;
  445. int ret = open_namei(file, NULL, filename, O_RDWR, 0, NULL);
  446. if (ret < 0) {
  447. put_handle(file);
  448. return ret;
  449. }
  450. struct shim_mount * fs = file->fs;
  451. get_handle(file);
  452. debug("restore %s\n", filename);
  453. struct cp_header cphdr;
  454. ret = fs->fs_ops->read(file, &cphdr, sizeof(struct cp_header));
  455. if (ret < 0)
  456. goto out;
  457. void * cpaddr = cphdr.addr;
  458. ret = fs->fs_ops->mmap(file, &cpaddr, ALLOC_ALIGN_UP(cphdr.size), PROT_READ|PROT_WRITE,
  459. MAP_PRIVATE|MAP_FILE, 0);
  460. if (ret < 0)
  461. goto out;
  462. hdr->hdr = cphdr;
  463. *cpptr = cpaddr;
  464. migrated_memory_start = cpaddr;
  465. migrated_memory_end = cpaddr + hdr->hdr.size;
  466. out:
  467. put_handle(file);
  468. return ret;
  469. }
  470. int send_handles_on_stream (PAL_HANDLE stream, struct shim_cp_store * store)
  471. {
  472. int nentries = store->palhdl_nentries;
  473. if (!nentries)
  474. return 0;
  475. struct shim_palhdl_entry ** entries =
  476. __alloca(sizeof(struct shim_palhdl_entry *) * nentries);
  477. struct shim_palhdl_entry * entry = store->last_palhdl_entry;
  478. int cnt = nentries;
  479. for ( ; entry ; entry = entry->prev)
  480. if (entry->handle) {
  481. if (!cnt)
  482. return -EINVAL;
  483. entries[--cnt] = entry;
  484. }
  485. entries += cnt;
  486. nentries -= cnt;
  487. for (int i = 0 ; i < nentries ; i++) {
  488. /* We need to abort migration from parent to child if DkSendHandle() returned error,
  489. * otherwise the application may fail. */
  490. if (!DkSendHandle(stream, entries[i]->handle))
  491. return -EINVAL;
  492. }
  493. return 0;
  494. }
  495. int receive_handles_on_stream (struct palhdl_header * hdr, ptr_t base,
  496. long rebase)
  497. {
  498. struct shim_palhdl_entry * palhdl_entries =
  499. (void *) (base + hdr->entoffset);
  500. int nentries = hdr->nentries;
  501. if (!nentries)
  502. return 0;
  503. debug("receive handles: %d entries\n", nentries);
  504. struct shim_palhdl_entry ** entries =
  505. __alloca(sizeof(struct shim_palhdl_entry *) * nentries);
  506. struct shim_palhdl_entry * entry = palhdl_entries;
  507. int cnt = nentries;
  508. for ( ; entry ; entry = entry->prev) {
  509. CP_REBASE(entry->prev);
  510. CP_REBASE(entry->phandle);
  511. if (!cnt)
  512. return -EINVAL;
  513. entries[--cnt] = entry;
  514. }
  515. entries += cnt;
  516. nentries -= cnt;
  517. for (int i = 0 ; i < nentries ; i++) {
  518. entry = entries[i];
  519. if (entry->handle) {
  520. PAL_HANDLE hdl = DkReceiveHandle(PAL_CB(parent_process));
  521. /* We need to abort migration from parent to child if DkReceiveHandle() returned error,
  522. * otherwise the application may fail. */
  523. if (!hdl)
  524. return -EINVAL;
  525. *entry->phandle = hdl;
  526. }
  527. }
  528. return 0;
  529. }
  530. static void * cp_alloc (struct shim_cp_store * store, void * addr, size_t size)
  531. {
  532. // Keeping for api compatibility; not 100% sure this is needed
  533. __UNUSED(store);
  534. if (addr) {
  535. /*
  536. * If the checkpoint needs more space, try to extend the checkpoint
  537. * store at the current address.
  538. */
  539. debug("try extend checkpoint store: %p-%p (size = %ld)\n",
  540. addr, addr + size, size);
  541. if (bkeep_mmap(addr, size, PROT_READ|PROT_WRITE, CP_VMA_FLAGS,
  542. NULL, 0, "cpstore") < 0)
  543. return NULL;
  544. } else {
  545. /*
  546. * Here we use a strategy to reduce internal fragmentation of virtual
  547. * memory space. Because we need a relatively large, continuous space
  548. * for dumping the checkpoint data, internal fragmentation can cause
  549. * the process to drain the virtual address space after forking a few
  550. * times. The previous space used for checkpoint may be fragmented
  551. * at the next fork.
  552. *
  553. * A simple trick we use here is to reserve some space right after the
  554. * checkpoint space. The reserved space is half of the size of the
  555. * checkpoint space, but can be further fine-tuned.
  556. */
  557. size_t reserve_size = ALLOC_ALIGN_UP(size >> 1);
  558. debug("try allocate checkpoint store (size = %ld, reserve = %ld)\n",
  559. size, reserve_size);
  560. /*
  561. * Allocating the checkpoint space at the first space found from the
  562. * top of the virtual address space.
  563. */
  564. addr = bkeep_unmapped_any(size + reserve_size, PROT_READ|PROT_WRITE,
  565. CP_VMA_FLAGS, 0, "cpstore");
  566. if (!addr)
  567. return NULL;
  568. bkeep_munmap(addr + size, reserve_size, CP_VMA_FLAGS);
  569. }
  570. addr = (void *) DkVirtualMemoryAlloc(addr, size, 0,
  571. PAL_PROT_READ|PAL_PROT_WRITE);
  572. if (!addr)
  573. bkeep_munmap(addr, size, CP_VMA_FLAGS);
  574. return addr;
  575. }
  576. DEFINE_PROFILE_CATEGORY(migrate_proc, migrate);
  577. DEFINE_PROFILE_INTERVAL(migrate_create_process, migrate_proc);
  578. DEFINE_PROFILE_INTERVAL(migrate_connect_ipc, migrate_proc);
  579. DEFINE_PROFILE_INTERVAL(migrate_init_checkpoint, migrate_proc);
  580. DEFINE_PROFILE_INTERVAL(migrate_save_checkpoint, migrate_proc);
  581. DEFINE_PROFILE_INTERVAL(migrate_send_header, migrate_proc);
  582. DEFINE_PROFILE_INTERVAL(migrate_send_checkpoint, migrate_proc);
  583. DEFINE_PROFILE_OCCURENCE(migrate_send_on_stream, migrate_proc);
  584. DEFINE_PROFILE_INTERVAL(migrate_send_pal_handles, migrate_proc);
  585. DEFINE_PROFILE_INTERVAL(migrate_free_checkpoint, migrate_proc);
  586. DEFINE_PROFILE_INTERVAL(migrate_wait_response, migrate_proc);
  587. /*
  588. * Create a new process and migrate the process states to the new process.
  589. *
  590. * @migrate: migration function defined by the caller
  591. * @exec: the executable to load in the new process
  592. * @argv: arguments passed to the new process
  593. * @thread: thread handle to be migrated to the new process
  594. *
  595. * The remaining arguments are passed into the migration function.
  596. */
  597. int do_migrate_process (int (*migrate) (struct shim_cp_store *,
  598. struct shim_thread *,
  599. struct shim_process *, va_list),
  600. struct shim_handle * exec,
  601. const char ** argv,
  602. struct shim_thread * thread, ...)
  603. {
  604. int ret = 0;
  605. struct shim_process * new_process = NULL;
  606. struct newproc_header hdr;
  607. PAL_NUM bytes;
  608. memset(&hdr, 0, sizeof(hdr));
  609. #ifdef PROFILE
  610. unsigned long begin_create_time = GET_PROFILE_INTERVAL();
  611. unsigned long create_time = begin_create_time;
  612. #endif
  613. BEGIN_PROFILE_INTERVAL();
  614. /*
  615. * Create the process first. The new process requires some time
  616. * to initialize before starting to receive checkpoint data.
  617. * Parallizing the process creation and checkpointing can improve
  618. * the latency of forking.
  619. */
  620. PAL_HANDLE proc = DkProcessCreate(exec ? qstrgetstr(&exec->uri) :
  621. pal_control.executable, argv);
  622. if (!proc) {
  623. ret = -PAL_ERRNO;
  624. goto out;
  625. }
  626. SAVE_PROFILE_INTERVAL(migrate_create_process);
  627. /* Create process and IPC bookkeepings */
  628. new_process = create_process(exec ? /*execve case*/ true : /*fork case*/ false);
  629. if (!new_process) {
  630. ret = -EACCES;
  631. goto out;
  632. }
  633. SAVE_PROFILE_INTERVAL(migrate_connect_ipc);
  634. /* Allocate a space for dumping the checkpoint data. */
  635. struct shim_cp_store cpstore;
  636. memset(&cpstore, 0, sizeof(cpstore));
  637. cpstore.alloc = cp_alloc;
  638. cpstore.bound = CP_INIT_VMA_SIZE;
  639. while (1) {
  640. /*
  641. * Try allocating a space of a certain size. If the allocation fails,
  642. * continue to try with smaller sizes.
  643. */
  644. cpstore.base = (ptr_t) cp_alloc(&cpstore, 0, cpstore.bound);
  645. if (cpstore.base)
  646. break;
  647. cpstore.bound >>= 1;
  648. if (cpstore.bound < g_pal_alloc_align)
  649. break;
  650. }
  651. if (!cpstore.base) {
  652. ret = -ENOMEM;
  653. debug("failed creating checkpoint store\n");
  654. goto out;
  655. }
  656. SAVE_PROFILE_INTERVAL(migrate_init_checkpoint);
  657. /* Calling the migration function defined by caller. The thread argument
  658. * is new thread in case of fork/clone and cur_thread in case of execve. */
  659. va_list ap;
  660. va_start(ap, thread);
  661. ret = (*migrate) (&cpstore, thread, new_process, ap);
  662. va_end(ap);
  663. if (ret < 0) {
  664. debug("failed creating checkpoint (ret = %d)\n", ret);
  665. goto out;
  666. }
  667. SAVE_PROFILE_INTERVAL(migrate_save_checkpoint);
  668. unsigned long checkpoint_time = GET_PROFILE_INTERVAL();
  669. unsigned long checkpoint_size = cpstore.offset + cpstore.mem_size;
  670. /* Checkpoint data created. */
  671. debug("checkpoint of %lu bytes created, %lu microsecond is spent.\n",
  672. checkpoint_size, checkpoint_time);
  673. hdr.checkpoint.hdr.addr = (void *) cpstore.base;
  674. hdr.checkpoint.hdr.size = checkpoint_size;
  675. if (cpstore.mem_nentries) {
  676. hdr.checkpoint.mem.entoffset =
  677. (ptr_t) cpstore.last_mem_entry - cpstore.base;
  678. hdr.checkpoint.mem.nentries = cpstore.mem_nentries;
  679. }
  680. if (cpstore.palhdl_nentries) {
  681. hdr.checkpoint.palhdl.entoffset =
  682. (ptr_t) cpstore.last_palhdl_entry - cpstore.base;
  683. hdr.checkpoint.palhdl.nentries = cpstore.palhdl_nentries;
  684. }
  685. #ifdef PROFILE
  686. hdr.begin_create_time = begin_create_time;
  687. hdr.create_time = create_time;
  688. hdr.write_proc_time = GET_PROFILE_INTERVAL();
  689. #endif
  690. /*
  691. * Sending a header to the new process through the RPC stream to
  692. * notify the process to start receiving the checkpoint.
  693. */
  694. bytes = DkStreamWrite(proc, 0, sizeof(struct newproc_header), &hdr, NULL);
  695. if (bytes == PAL_STREAM_ERROR) {
  696. ret = -PAL_ERRNO;
  697. debug("failed writing to process stream (ret = %d)\n", ret);
  698. goto out;
  699. } else if (bytes < sizeof(struct newproc_header)) {
  700. ret = -EACCES;
  701. goto out;
  702. }
  703. ADD_PROFILE_OCCURENCE(migrate_send_on_stream, bytes);
  704. SAVE_PROFILE_INTERVAL(migrate_send_header);
  705. ret = send_checkpoint_on_stream(proc, &cpstore);
  706. if (ret < 0) {
  707. debug("failed sending checkpoint (ret = %d)\n", ret);
  708. goto out;
  709. }
  710. SAVE_PROFILE_INTERVAL(migrate_send_checkpoint);
  711. /*
  712. * For socket and RPC streams, we need to migrate the PAL handles
  713. * to the new process using PAL calls.
  714. */
  715. if ((ret = send_handles_on_stream(proc, &cpstore)) < 0)
  716. goto out;
  717. SAVE_PROFILE_INTERVAL(migrate_send_pal_handles);
  718. /* Free the checkpoint space */
  719. if ((ret = bkeep_munmap((void *) cpstore.base, cpstore.bound,
  720. CP_VMA_FLAGS)) < 0) {
  721. debug("failed unmaping checkpoint (ret = %d)\n", ret);
  722. goto out;
  723. }
  724. DkVirtualMemoryFree((PAL_PTR) cpstore.base, cpstore.bound);
  725. SAVE_PROFILE_INTERVAL(migrate_free_checkpoint);
  726. /* Wait for the response from the new process */
  727. struct newproc_response res;
  728. bytes = DkStreamRead(proc, 0, sizeof(struct newproc_response), &res,
  729. NULL, 0);
  730. if (bytes == PAL_STREAM_ERROR) {
  731. ret = -PAL_ERRNO;
  732. goto out;
  733. }
  734. SAVE_PROFILE_INTERVAL(migrate_wait_response);
  735. /* exec != NULL implies the execve case so the new process "replaces"
  736. * this current process: no need to notify the leader or establish IPC */
  737. if (!exec) {
  738. /* fork/clone case: new process is an actual child process for this
  739. * current process, so notify the leader regarding subleasing of TID
  740. * (child must create self-pipe with convention of pipe:child-vmid) */
  741. char new_process_self_uri[256];
  742. snprintf(new_process_self_uri, sizeof(new_process_self_uri), "pipe:%u", res.child_vmid);
  743. ipc_pid_sublease_send(res.child_vmid, thread->tid, new_process_self_uri, NULL);
  744. /* listen on the new IPC port to the new child process */
  745. add_ipc_port_by_id(res.child_vmid, proc,
  746. IPC_PORT_DIRCLD|IPC_PORT_LISTEN|IPC_PORT_KEEPALIVE,
  747. &ipc_port_with_child_fini,
  748. NULL);
  749. }
  750. /* remote child thread has VMID of the child process (note that we don't
  751. * care about execve case because the parent "intermediate" process will
  752. * die right after this anyway) */
  753. thread->vmid = res.child_vmid;
  754. ret = 0;
  755. out:
  756. if (new_process)
  757. free_process(new_process);
  758. if (ret < 0) {
  759. if (proc)
  760. DkObjectClose(proc);
  761. SYS_PRINTF("process creation failed\n");
  762. }
  763. return ret;
  764. }
  765. /*
  766. * Loading the checkpoint from the parent process or a checkpoint file
  767. *
  768. * @hdr: checkpoint header
  769. * @cpptr: returning the pointer of the loaded checkpoint
  770. */
  771. int do_migration (struct newproc_cp_header * hdr, void ** cpptr)
  772. {
  773. void * base = NULL;
  774. size_t size = hdr->hdr.size;
  775. PAL_PTR mapaddr;
  776. PAL_NUM mapsize;
  777. long rebase;
  778. int ret = 0;
  779. BEGIN_PROFILE_INTERVAL();
  780. /*
  781. * Allocate a large enough space to load the checkpoint data.
  782. *
  783. * If CPSTORE_DERANDOMIZATION is enabled, try to allocate the space
  784. * at the exact address where the checkpoint is created. Otherwise,
  785. * just allocate at the first space we found from the top of the virtual
  786. * memory space.
  787. */
  788. #if CPSTORE_DERANDOMIZATION == 1
  789. if (hdr->hdr.addr
  790. && lookup_overlap_vma(hdr->hdr.addr, size, NULL) == -ENOENT) {
  791. /* Try to load the checkpoint at the same address */
  792. base = hdr->hdr.addr;
  793. mapaddr = (PAL_PTR)ALLOC_ALIGN_DOWN_PTR(base);
  794. mapsize = (PAL_PTR)ALLOC_ALIGN_UP_PTR(base + size) - mapaddr;
  795. /* Need to create VMA before allocation */
  796. ret = bkeep_mmap((void *) mapaddr, mapsize,
  797. PROT_READ|PROT_WRITE, CP_VMA_FLAGS,
  798. NULL, 0, "cpstore");
  799. if (ret < 0)
  800. base = NULL;
  801. }
  802. #endif
  803. if (!base) {
  804. base = bkeep_unmapped_any(ALLOC_ALIGN_UP(size), PROT_READ|PROT_WRITE, CP_VMA_FLAGS, 0,
  805. "cpstore");
  806. if (!base)
  807. return -ENOMEM;
  808. mapaddr = (PAL_PTR)base;
  809. mapsize = (PAL_NUM)ALLOC_ALIGN_UP(size);
  810. }
  811. debug("checkpoint mapped at %p-%p\n", base, base + size);
  812. PAL_FLG pal_prot = PAL_PROT_READ|PAL_PROT_WRITE;
  813. PAL_PTR mapped = DkVirtualMemoryAlloc(mapaddr, mapsize, 0, pal_prot);
  814. if (!mapped)
  815. return -PAL_ERRNO;
  816. assert(mapaddr == mapped);
  817. /*
  818. * If the checkpoint is loaded at a different address from where it is
  819. * created, we need to rebase the pointers in the checkpoint.
  820. */
  821. rebase = (long) ((uintptr_t) base - (uintptr_t) hdr->hdr.addr);
  822. size_t total_bytes = 0;
  823. while (total_bytes < size) {
  824. PAL_NUM bytes = DkStreamRead(PAL_CB(parent_process), 0, size - total_bytes,
  825. (void*)base + total_bytes, NULL, 0);
  826. if (bytes == PAL_STREAM_ERROR) {
  827. if (PAL_ERRNO == EINTR || PAL_ERRNO == EAGAIN ||
  828. PAL_ERRNO == EWOULDBLOCK)
  829. continue;
  830. return -PAL_ERRNO;
  831. }
  832. total_bytes += bytes;
  833. }
  834. SAVE_PROFILE_INTERVAL(child_load_checkpoint_on_pipe);
  835. debug("%lu bytes read on stream\n", total_bytes);
  836. /* Receive socket or RPC handles from the parent process. */
  837. ret = receive_handles_on_stream(&hdr->palhdl, (ptr_t) base, rebase);
  838. if (ret < 0) {
  839. /* TODO: unload the checkpoint space */
  840. return ret;
  841. }
  842. SAVE_PROFILE_INTERVAL(child_receive_handles);
  843. migrated_memory_start = (void *) mapaddr;
  844. migrated_memory_end = (void *) mapaddr + mapsize;
  845. *cpptr = (void *) base;
  846. return 0;
  847. }
  848. void restore_context (struct shim_context * context)
  849. {
  850. assert(context->regs);
  851. struct shim_regs regs = *context->regs;
  852. debug("restore context: SP = 0x%08lx, IP = 0x%08lx\n", regs.rsp, regs.rip);
  853. /* don't clobber redzone. If sigaltstack is used,
  854. * this area won't be clobbered by signal context */
  855. *(unsigned long*) (regs.rsp - RED_ZONE_SIZE - 8) = regs.rip;
  856. /* Ready to resume execution, re-enable preemption. */
  857. shim_tcb_t * tcb = shim_get_tcb();
  858. __enable_preempt(tcb);
  859. unsigned long fs_base = context->fs_base;
  860. memset(context, 0, sizeof(struct shim_context));
  861. context->fs_base = fs_base;
  862. __asm__ volatile("movq %0, %%rsp\r\n"
  863. "addq $2 * 8, %%rsp\r\n" /* skip orig_rax and rsp */
  864. "popq %%r15\r\n"
  865. "popq %%r14\r\n"
  866. "popq %%r13\r\n"
  867. "popq %%r12\r\n"
  868. "popq %%r11\r\n"
  869. "popq %%r10\r\n"
  870. "popq %%r9\r\n"
  871. "popq %%r8\r\n"
  872. "popq %%rcx\r\n"
  873. "popq %%rdx\r\n"
  874. "popq %%rsi\r\n"
  875. "popq %%rdi\r\n"
  876. "popq %%rbx\r\n"
  877. "popq %%rbp\r\n"
  878. "popfq\r\n"
  879. "movq "XSTRINGIFY(SHIM_REGS_RSP)" - "XSTRINGIFY(SHIM_REGS_RIP)"(%%rsp), %%rsp\r\n"
  880. "movq $0, %%rax\r\n"
  881. "jmp *-"XSTRINGIFY(RED_ZONE_SIZE)"-8(%%rsp)\r\n"
  882. :: "g"(&regs) : "memory");
  883. }