xref: /unit/src/nxt_port_memory.c (revision 613:e5dd7bc63d59)
1 
2 /*
3  * Copyright (C) Max Romanov
4  * Copyright (C) NGINX, Inc.
5  */
6 
7 #include <nxt_main.h>
8 
9 #if (NXT_HAVE_MEMFD_CREATE)
10 
11 #include <linux/memfd.h>
12 #include <unistd.h>
13 #include <sys/syscall.h>
14 
15 #endif
16 
17 #include <nxt_port_memory_int.h>
18 
19 
20 nxt_inline void
21 nxt_port_mmap_handler_use(nxt_port_mmap_handler_t *mmap_handler, int i)
22 {
23     int  c;
24 
25     c = nxt_atomic_fetch_add(&mmap_handler->use_count, i);
26 
27     if (i < 0 && c == -i) {
28         if (mmap_handler->hdr != NULL) {
29             nxt_mem_munmap(mmap_handler->hdr, PORT_MMAP_SIZE);
30             mmap_handler->hdr = NULL;
31         }
32 
33         nxt_free(mmap_handler);
34     }
35 }
36 
37 
38 static nxt_port_mmap_t *
39 nxt_port_mmap_at(nxt_port_mmaps_t *port_mmaps, uint32_t i)
40 {
41     uint32_t  cap;
42 
43     cap = port_mmaps->cap;
44 
45     if (cap == 0) {
46         cap = i + 1;
47     }
48 
49     while (i + 1 > cap) {
50 
51         if (cap < 16) {
52           cap = cap * 2;
53 
54         } else {
55           cap = cap + cap / 2;
56         }
57     }
58 
59     if (cap != port_mmaps->cap) {
60 
61         port_mmaps->elts = nxt_realloc(port_mmaps->elts,
62                                        cap * sizeof(nxt_port_mmap_t));
63         if (nxt_slow_path(port_mmaps->elts == NULL)) {
64             return NULL;
65         }
66 
67         nxt_memzero(port_mmaps->elts + port_mmaps->cap,
68                     sizeof(nxt_port_mmap_t) * (cap - port_mmaps->cap));
69 
70         port_mmaps->cap = cap;
71     }
72 
73     if (i + 1 > port_mmaps->size) {
74         port_mmaps->size = i + 1;
75     }
76 
77     return port_mmaps->elts + i;
78 }
79 
80 
81 void
82 nxt_port_mmaps_destroy(nxt_port_mmaps_t *port_mmaps, nxt_bool_t free_elts)
83 {
84     uint32_t         i;
85     nxt_port_mmap_t  *port_mmap;
86 
87     if (port_mmaps == NULL) {
88         return;
89     }
90 
91     port_mmap = port_mmaps->elts;
92 
93     for (i = 0; i < port_mmaps->size; i++) {
94         nxt_port_mmap_handler_use(port_mmap[i].mmap_handler, -1);
95     }
96 
97     port_mmaps->size = 0;
98 
99     if (free_elts != 0) {
100         nxt_free(port_mmaps->elts);
101     }
102 }
103 
104 
105 #define nxt_port_mmap_free_junk(p, size)                                      \
106     memset((p), 0xA5, size)
107 
108 
109 static void
110 nxt_port_mmap_buf_completion(nxt_task_t *task, void *obj, void *data)
111 {
112     u_char                   *p;
113     nxt_mp_t                 *mp;
114     nxt_buf_t                *b;
115     nxt_chunk_id_t           c;
116     nxt_port_mmap_header_t   *hdr;
117     nxt_port_mmap_handler_t  *mmap_handler;
118 
119     if (nxt_buf_ts_handle(task, obj, data)) {
120         return;
121     }
122 
123     b = obj;
124 
125     mp = b->data;
126 
127     nxt_assert(data == b->parent);
128 
129     mmap_handler = data;
130     hdr = mmap_handler->hdr;
131 
132     if (nxt_slow_path(hdr->src_pid != nxt_pid && hdr->dst_pid != nxt_pid)) {
133         nxt_debug(task, "mmap buf completion: mmap for other process pair "
134                   "%PI->%PI", hdr->src_pid, hdr->dst_pid);
135 
136         goto release_buf;
137     }
138 
139     if (b->is_port_mmap_sent && b->mem.pos > b->mem.start) {
140         /*
141          * Chunks until b->mem.pos has been sent to other side,
142          * let's release rest (if any).
143          */
144         p = b->mem.pos - 1;
145         c = nxt_port_mmap_chunk_id(hdr, p) + 1;
146         p = nxt_port_mmap_chunk_start(hdr, c);
147 
148     } else {
149         p = b->mem.start;
150         c = nxt_port_mmap_chunk_id(hdr, p);
151     }
152 
153     nxt_port_mmap_free_junk(p, b->mem.end - p);
154 
155     nxt_debug(task, "mmap buf completion: %p [%p,%uz] (sent=%d), "
156               "%PI->%PI,%d,%d", b, b->mem.start, b->mem.end - b->mem.start,
157               b->is_port_mmap_sent, hdr->src_pid, hdr->dst_pid, hdr->id, c);
158 
159     while (p < b->mem.end) {
160         nxt_port_mmap_set_chunk_free(hdr->free_map, c);
161 
162         p += PORT_MMAP_CHUNK_SIZE;
163         c++;
164     }
165 
166 release_buf:
167 
168     nxt_port_mmap_handler_use(mmap_handler, -1);
169 
170     nxt_mp_free(mp, b);
171     nxt_mp_release(mp);
172 }
173 
174 
175 nxt_port_mmap_handler_t *
176 nxt_port_incoming_port_mmap(nxt_task_t *task, nxt_process_t *process,
177     nxt_fd_t fd)
178 {
179     void                     *mem;
180     struct stat              mmap_stat;
181     nxt_port_mmap_t          *port_mmap;
182     nxt_port_mmap_header_t   *hdr;
183     nxt_port_mmap_handler_t  *mmap_handler;
184 
185     nxt_debug(task, "got new mmap fd #%FD from process %PI",
186               fd, process->pid);
187 
188     port_mmap = NULL;
189 
190     if (fstat(fd, &mmap_stat) == -1) {
191         nxt_log(task, NXT_LOG_WARN, "fstat(%FD) failed %E", fd, nxt_errno);
192 
193         return NULL;
194     }
195 
196     mem = nxt_mem_mmap(NULL, mmap_stat.st_size,
197                        PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
198 
199     if (nxt_slow_path(mem == MAP_FAILED)) {
200         nxt_log(task, NXT_LOG_WARN, "mmap() failed %E", nxt_errno);
201 
202         return NULL;
203     }
204 
205     hdr = mem;
206 
207     mmap_handler = nxt_zalloc(sizeof(nxt_port_mmap_handler_t));
208     if (nxt_slow_path(mmap_handler == NULL)) {
209         nxt_log(task, NXT_LOG_WARN, "failed to allocate mmap_handler");
210 
211         nxt_mem_munmap(mem, PORT_MMAP_SIZE);
212 
213         return NULL;
214     }
215 
216     mmap_handler->hdr = hdr;
217 
218     if (nxt_slow_path(hdr->src_pid != process->pid
219                       || hdr->dst_pid != nxt_pid))
220     {
221         nxt_log(task, NXT_LOG_WARN, "unexpected pid in mmap header detected: "
222                 "%PI != %PI or %PI != %PI", hdr->src_pid, process->pid,
223                 hdr->dst_pid, nxt_pid);
224 
225         return NULL;
226     }
227 
228     nxt_thread_mutex_lock(&process->incoming.mutex);
229 
230     port_mmap = nxt_port_mmap_at(&process->incoming, hdr->id);
231     if (nxt_slow_path(port_mmap == NULL)) {
232         nxt_log(task, NXT_LOG_WARN, "failed to add mmap to incoming array");
233 
234         nxt_mem_munmap(mem, PORT_MMAP_SIZE);
235         hdr = NULL;
236 
237         nxt_free(mmap_handler);
238         mmap_handler = NULL;
239 
240         goto fail;
241     }
242 
243     port_mmap->mmap_handler = mmap_handler;
244     nxt_port_mmap_handler_use(mmap_handler, 1);
245 
246     hdr->sent_over = 0xFFFFu;
247 
248 fail:
249 
250     nxt_thread_mutex_unlock(&process->incoming.mutex);
251 
252     return mmap_handler;
253 }
254 
255 
256 static nxt_port_mmap_handler_t *
257 nxt_port_new_port_mmap(nxt_task_t *task, nxt_process_t *process,
258     nxt_port_t *port, nxt_bool_t tracking)
259 {
260     void                     *mem;
261     u_char                   *p, name[64];
262     nxt_fd_t                 fd;
263     nxt_free_map_t           *free_map;
264     nxt_port_mmap_t          *port_mmap;
265     nxt_port_mmap_header_t   *hdr;
266     nxt_port_mmap_handler_t  *mmap_handler;
267 
268     mmap_handler = nxt_zalloc(sizeof(nxt_port_mmap_handler_t));
269     if (nxt_slow_path(mmap_handler == NULL)) {
270         nxt_log(task, NXT_LOG_WARN, "failed to allocate mmap_handler");
271 
272         return NULL;
273     }
274 
275     port_mmap = nxt_port_mmap_at(&process->outgoing, process->outgoing.size);
276     if (nxt_slow_path(port_mmap == NULL)) {
277         nxt_log(task, NXT_LOG_WARN,
278                 "failed to add port mmap to outgoing array");
279 
280         nxt_free(mmap_handler);
281         return NULL;
282     }
283 
284     p = nxt_sprintf(name, name + sizeof(name), NXT_SHM_PREFIX "unit.%PI.%uxD",
285                     nxt_pid, nxt_random(&task->thread->random));
286     *p = '\0';
287 
288 #if (NXT_HAVE_MEMFD_CREATE)
289 
290     fd = syscall(SYS_memfd_create, name, MFD_CLOEXEC);
291 
292     if (nxt_slow_path(fd == -1)) {
293         nxt_alert(task, "memfd_create(%s) failed %E", name, nxt_errno);
294 
295         goto remove_fail;
296     }
297 
298     nxt_debug(task, "memfd_create(%s): %FD", name, fd);
299 
300 #elif (NXT_HAVE_SHM_OPEN_ANON)
301 
302     fd = shm_open(SHM_ANON, O_RDWR, S_IRUSR | S_IWUSR);
303 
304     nxt_debug(task, "shm_open(SHM_ANON): %FD", fd);
305 
306     if (nxt_slow_path(fd == -1)) {
307         nxt_alert(task, "shm_open(SHM_ANON) failed %E", nxt_errno);
308 
309         goto remove_fail;
310     }
311 
312 #elif (NXT_HAVE_SHM_OPEN)
313 
314     /* Just in case. */
315     shm_unlink((char *) name);
316 
317     fd = shm_open((char *) name, O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR);
318 
319     nxt_debug(task, "shm_open(%s): %FD", name, fd);
320 
321     if (nxt_slow_path(fd == -1)) {
322         nxt_alert(task, "shm_open(%s) failed %E", name, nxt_errno);
323 
324         goto remove_fail;
325     }
326 
327     if (nxt_slow_path(shm_unlink((char *) name) == -1)) {
328         nxt_log(task, NXT_LOG_WARN, "shm_unlink(%s) failed %E", name,
329                 nxt_errno);
330     }
331 
332 #else
333 
334 #error No working shared memory implementation.
335 
336 #endif
337 
338     if (nxt_slow_path(ftruncate(fd, PORT_MMAP_SIZE) == -1)) {
339         nxt_log(task, NXT_LOG_WARN, "ftruncate() failed %E", nxt_errno);
340 
341         goto remove_fail;
342     }
343 
344     mem = nxt_mem_mmap(NULL, PORT_MMAP_SIZE, PROT_READ | PROT_WRITE,
345                        MAP_SHARED, fd, 0);
346 
347     if (nxt_slow_path(mem == MAP_FAILED)) {
348         goto remove_fail;
349     }
350 
351     mmap_handler->hdr = mem;
352     port_mmap->mmap_handler = mmap_handler;
353     nxt_port_mmap_handler_use(mmap_handler, 1);
354 
355     /* Init segment header. */
356     hdr = mmap_handler->hdr;
357 
358     nxt_memset(hdr->free_map, 0xFFU, sizeof(hdr->free_map));
359     nxt_memset(hdr->free_tracking_map, 0xFFU, sizeof(hdr->free_tracking_map));
360 
361     hdr->id = process->outgoing.size - 1;
362     hdr->src_pid = nxt_pid;
363     hdr->dst_pid = process->pid;
364     hdr->sent_over = port->id;
365 
366     /* Mark first chunk as busy */
367     free_map = tracking ? hdr->free_tracking_map : hdr->free_map;
368 
369     nxt_port_mmap_set_chunk_busy(free_map, 0);
370 
371     /* Mark as busy chunk followed the last available chunk. */
372     nxt_port_mmap_set_chunk_busy(hdr->free_map, PORT_MMAP_CHUNK_COUNT);
373     nxt_port_mmap_set_chunk_busy(hdr->free_tracking_map, PORT_MMAP_CHUNK_COUNT);
374 
375     nxt_debug(task, "send mmap fd %FD to process %PI", fd, port->pid);
376 
377     /* TODO handle error */
378     (void) nxt_port_socket_write(task, port, NXT_PORT_MSG_MMAP, fd, 0, 0, NULL);
379 
380     nxt_log(task, NXT_LOG_DEBUG, "new mmap #%D created for %PI -> %PI",
381             hdr->id, nxt_pid, process->pid);
382 
383     return mmap_handler;
384 
385 remove_fail:
386 
387     nxt_free(mmap_handler);
388 
389     process->outgoing.size--;
390 
391     return NULL;
392 }
393 
394 
395 static nxt_port_mmap_handler_t *
396 nxt_port_mmap_get(nxt_task_t *task, nxt_port_t *port, nxt_chunk_id_t *c,
397     nxt_bool_t tracking)
398 {
399     nxt_process_t            *process;
400     nxt_free_map_t           *free_map;
401     nxt_port_mmap_t          *port_mmap;
402     nxt_port_mmap_t          *end_port_mmap;
403     nxt_port_mmap_header_t   *hdr;
404     nxt_port_mmap_handler_t  *mmap_handler;
405 
406     process = port->process;
407     if (nxt_slow_path(process == NULL)) {
408         return NULL;
409     }
410 
411     *c = 0;
412 
413     nxt_thread_mutex_lock(&process->outgoing.mutex);
414 
415     end_port_mmap = process->outgoing.elts + process->outgoing.size;
416 
417     for (port_mmap = process->outgoing.elts;
418          port_mmap < end_port_mmap;
419          port_mmap++)
420     {
421         mmap_handler = port_mmap->mmap_handler;
422         hdr = mmap_handler->hdr;
423 
424         if (hdr->sent_over != 0xFFFFu && hdr->sent_over != port->id) {
425             continue;
426         }
427 
428         free_map = tracking ? hdr->free_tracking_map : hdr->free_map;
429 
430         if (nxt_port_mmap_get_free_chunk(free_map, c)) {
431             goto unlock_return;
432         }
433     }
434 
435     /* TODO introduce port_mmap limit and release wait. */
436 
437     mmap_handler = nxt_port_new_port_mmap(task, process, port, tracking);
438 
439 unlock_return:
440 
441     nxt_thread_mutex_unlock(&process->outgoing.mutex);
442 
443     return mmap_handler;
444 }
445 
446 
447 static nxt_port_mmap_handler_t *
448 nxt_port_get_port_incoming_mmap(nxt_task_t *task, nxt_pid_t spid, uint32_t id)
449 {
450     nxt_process_t            *process;
451     nxt_port_mmap_handler_t  *mmap_handler;
452 
453     process = nxt_runtime_process_find(task->thread->runtime, spid);
454     if (nxt_slow_path(process == NULL)) {
455         return NULL;
456     }
457 
458     nxt_thread_mutex_lock(&process->incoming.mutex);
459 
460     if (nxt_fast_path(process->incoming.size > id)) {
461         mmap_handler = process->incoming.elts[id].mmap_handler;
462 
463     } else {
464         mmap_handler = NULL;
465 
466         nxt_debug(task, "invalid incoming mmap id %uD for pid %PI", id, spid);
467     }
468 
469     nxt_thread_mutex_unlock(&process->incoming.mutex);
470 
471     return mmap_handler;
472 }
473 
474 
475 nxt_int_t
476 nxt_port_mmap_get_tracking(nxt_task_t *task, nxt_port_t *port,
477     nxt_port_mmap_tracking_t *tracking, uint32_t stream)
478 {
479     nxt_chunk_id_t           c;
480     nxt_port_mmap_header_t   *hdr;
481     nxt_port_mmap_handler_t  *mmap_handler;
482 
483     nxt_debug(task, "request tracking for stream #%uD", stream);
484 
485     mmap_handler = nxt_port_mmap_get(task, port, &c, 1);
486     if (nxt_slow_path(mmap_handler == NULL)) {
487         return NXT_ERROR;
488     }
489 
490     nxt_port_mmap_handler_use(mmap_handler, 1);
491 
492     hdr = mmap_handler->hdr;
493 
494     tracking->mmap_handler = mmap_handler;
495     tracking->tracking = hdr->tracking + c;
496 
497     *tracking->tracking = stream;
498 
499     nxt_debug(task, "outgoing tracking allocation: %PI->%PI,%d,%d",
500               hdr->src_pid, hdr->dst_pid, hdr->id, c);
501 
502     return NXT_OK;
503 }
504 
505 
506 nxt_bool_t
507 nxt_port_mmap_tracking_cancel(nxt_task_t *task,
508     nxt_port_mmap_tracking_t *tracking, uint32_t stream)
509 {
510     nxt_bool_t               res;
511     nxt_chunk_id_t           c;
512     nxt_port_mmap_header_t   *hdr;
513     nxt_port_mmap_handler_t  *mmap_handler;
514 
515     mmap_handler = tracking->mmap_handler;
516 
517     if (nxt_slow_path(mmap_handler == NULL)) {
518         return 0;
519     }
520 
521     hdr = mmap_handler->hdr;
522 
523     res = nxt_atomic_cmp_set(tracking->tracking, stream, 0);
524 
525     nxt_debug(task, "%s tracking for stream #%uD",
526               (res ? "cancelled" : "failed to cancel"), stream);
527 
528     if (!res) {
529         c = tracking->tracking - hdr->tracking;
530         nxt_port_mmap_set_chunk_free(hdr->free_tracking_map, c);
531     }
532 
533     nxt_port_mmap_handler_use(mmap_handler, -1);
534 
535     return res;
536 }
537 
538 
539 nxt_int_t
540 nxt_port_mmap_tracking_write(uint32_t *buf, nxt_port_mmap_tracking_t *t)
541 {
542     nxt_port_mmap_handler_t  *mmap_handler;
543 
544     mmap_handler = t->mmap_handler;
545 
546 #if (NXT_DEBUG)
547     {
548     nxt_atomic_t  *tracking;
549 
550     tracking = mmap_handler->hdr->tracking;
551 
552     nxt_assert(t->tracking >= tracking);
553     nxt_assert(t->tracking < tracking + PORT_MMAP_CHUNK_COUNT);
554     }
555 #endif
556 
557     buf[0] = mmap_handler->hdr->id;
558     buf[1] = t->tracking - mmap_handler->hdr->tracking;
559 
560     return NXT_OK;
561 }
562 
563 nxt_bool_t
564 nxt_port_mmap_tracking_read(nxt_task_t *task, nxt_port_recv_msg_t *msg)
565 {
566     nxt_buf_t                     *b;
567     nxt_bool_t                    res;
568     nxt_chunk_id_t                c;
569     nxt_port_mmap_header_t        *hdr;
570     nxt_port_mmap_handler_t       *mmap_handler;
571     nxt_port_mmap_tracking_msg_t  *tracking_msg;
572 
573     b = msg->buf;
574 
575     if (nxt_buf_used_size(b) < (int) sizeof(nxt_port_mmap_tracking_msg_t)) {
576         nxt_debug(task, "too small message %O", nxt_buf_used_size(b));
577         return 0;
578     }
579 
580     tracking_msg = (nxt_port_mmap_tracking_msg_t *) b->mem.pos;
581 
582     b->mem.pos += sizeof(nxt_port_mmap_tracking_msg_t);
583     mmap_handler = nxt_port_get_port_incoming_mmap(task, msg->port_msg.pid,
584                                                    tracking_msg->mmap_id);
585 
586     if (nxt_slow_path(mmap_handler == NULL)) {
587         return 0;
588     }
589 
590     hdr = mmap_handler->hdr;
591 
592     c = tracking_msg->tracking_id;
593     res = nxt_atomic_cmp_set(hdr->tracking + c, msg->port_msg.stream, 0);
594 
595     nxt_debug(task, "tracking for stream #%uD %s", msg->port_msg.stream,
596               (res ? "received" : "already cancelled"));
597 
598     if (!res) {
599         nxt_port_mmap_set_chunk_free(hdr->free_tracking_map, c);
600     }
601 
602     return res;
603 }
604 
605 
606 nxt_buf_t *
607 nxt_port_mmap_get_buf(nxt_task_t *task, nxt_port_t *port, size_t size)
608 {
609     size_t                   nchunks;
610     nxt_mp_t                 *mp;
611     nxt_buf_t                *b;
612     nxt_chunk_id_t           c;
613     nxt_port_mmap_header_t   *hdr;
614     nxt_port_mmap_handler_t  *mmap_handler;
615 
616     nxt_debug(task, "request %z bytes shm buffer", size);
617 
618     b = nxt_buf_mem_ts_alloc(task, task->thread->engine->mem_pool, 0);
619     if (nxt_slow_path(b == NULL)) {
620         return NULL;
621     }
622 
623     b->completion_handler = nxt_port_mmap_buf_completion;
624     nxt_buf_set_port_mmap(b);
625 
626     mmap_handler = nxt_port_mmap_get(task, port, &c, 0);
627     if (nxt_slow_path(mmap_handler == NULL)) {
628         mp = task->thread->engine->mem_pool;
629         nxt_mp_free(mp, b);
630         nxt_mp_release(mp);
631         return NULL;
632     }
633 
634     b->parent = mmap_handler;
635 
636     nxt_port_mmap_handler_use(mmap_handler, 1);
637 
638     hdr = mmap_handler->hdr;
639 
640     b->mem.start = nxt_port_mmap_chunk_start(hdr, c);
641     b->mem.pos = b->mem.start;
642     b->mem.free = b->mem.start;
643     b->mem.end = b->mem.start + PORT_MMAP_CHUNK_SIZE;
644 
645     nchunks = size / PORT_MMAP_CHUNK_SIZE;
646     if ((size % PORT_MMAP_CHUNK_SIZE) != 0 || nchunks == 0) {
647         nchunks++;
648     }
649 
650     nxt_debug(task, "outgoing mmap buf allocation: %p [%p,%uz] %PI->%PI,%d,%d",
651               b, b->mem.start, b->mem.end - b->mem.start,
652               hdr->src_pid, hdr->dst_pid, hdr->id, c);
653 
654     c++;
655     nchunks--;
656 
657     /* Try to acquire as much chunks as required. */
658     while (nchunks > 0) {
659 
660         if (nxt_port_mmap_chk_set_chunk_busy(hdr->free_map, c) == 0) {
661             break;
662         }
663 
664         b->mem.end += PORT_MMAP_CHUNK_SIZE;
665         c++;
666         nchunks--;
667     }
668 
669     return b;
670 }
671 
672 
673 nxt_int_t
674 nxt_port_mmap_increase_buf(nxt_task_t *task, nxt_buf_t *b, size_t size,
675     size_t min_size)
676 {
677     size_t                   nchunks, free_size;
678     nxt_chunk_id_t           c, start;
679     nxt_port_mmap_header_t   *hdr;
680     nxt_port_mmap_handler_t  *mmap_handler;
681 
682     nxt_debug(task, "request increase %z bytes shm buffer", size);
683 
684     if (nxt_slow_path(nxt_buf_is_port_mmap(b) == 0)) {
685         nxt_log(task, NXT_LOG_WARN,
686                 "failed to increase, not a mmap buffer");
687         return NXT_ERROR;
688     }
689 
690     free_size = nxt_buf_mem_free_size(&b->mem);
691 
692     if (nxt_slow_path(size <= free_size)) {
693         return NXT_OK;
694     }
695 
696     mmap_handler = b->parent;
697     hdr = mmap_handler->hdr;
698 
699     start = nxt_port_mmap_chunk_id(hdr, b->mem.end);
700 
701     size -= free_size;
702 
703     nchunks = size / PORT_MMAP_CHUNK_SIZE;
704     if ((size % PORT_MMAP_CHUNK_SIZE) != 0 || nchunks == 0) {
705         nchunks++;
706     }
707 
708     c = start;
709 
710     /* Try to acquire as much chunks as required. */
711     while (nchunks > 0) {
712 
713         if (nxt_port_mmap_chk_set_chunk_busy(hdr->free_map, c) == 0) {
714             break;
715         }
716 
717         c++;
718         nchunks--;
719     }
720 
721     if (nchunks != 0
722         && min_size > free_size + PORT_MMAP_CHUNK_SIZE * (c - start))
723     {
724         c--;
725         while (c >= start) {
726             nxt_port_mmap_set_chunk_free(hdr->free_map, c);
727             c--;
728         }
729 
730         nxt_debug(task, "failed to increase, %uz chunks busy", nchunks);
731 
732         return NXT_ERROR;
733 
734     } else {
735         b->mem.end += PORT_MMAP_CHUNK_SIZE * (c - start);
736 
737         return NXT_OK;
738     }
739 }
740 
741 
742 static nxt_buf_t *
743 nxt_port_mmap_get_incoming_buf(nxt_task_t *task, nxt_port_t *port,
744     nxt_pid_t spid, nxt_port_mmap_msg_t *mmap_msg)
745 {
746     size_t                   nchunks;
747     nxt_buf_t                *b;
748     nxt_port_mmap_header_t   *hdr;
749     nxt_port_mmap_handler_t  *mmap_handler;
750 
751     mmap_handler = nxt_port_get_port_incoming_mmap(task, spid,
752                                                    mmap_msg->mmap_id);
753     if (nxt_slow_path(mmap_handler == NULL)) {
754         return NULL;
755     }
756 
757     b = nxt_buf_mem_ts_alloc(task, port->mem_pool, 0);
758     if (nxt_slow_path(b == NULL)) {
759         return NULL;
760     }
761 
762     b->completion_handler = nxt_port_mmap_buf_completion;
763 
764     nxt_buf_set_port_mmap(b);
765 
766     nchunks = mmap_msg->size / PORT_MMAP_CHUNK_SIZE;
767     if ((mmap_msg->size % PORT_MMAP_CHUNK_SIZE) != 0) {
768         nchunks++;
769     }
770 
771     hdr = mmap_handler->hdr;
772 
773     b->mem.start = nxt_port_mmap_chunk_start(hdr, mmap_msg->chunk_id);
774     b->mem.pos = b->mem.start;
775     b->mem.free = b->mem.start + mmap_msg->size;
776     b->mem.end = b->mem.start + nchunks * PORT_MMAP_CHUNK_SIZE;
777 
778     b->parent = mmap_handler;
779     nxt_port_mmap_handler_use(mmap_handler, 1);
780 
781     nxt_debug(task, "incoming mmap buf allocation: %p [%p,%uz] %PI->%PI,%d,%d",
782               b, b->mem.start, b->mem.end - b->mem.start,
783               hdr->src_pid, hdr->dst_pid, hdr->id, mmap_msg->chunk_id);
784 
785     return b;
786 }
787 
788 
789 void
790 nxt_port_mmap_write(nxt_task_t *task, nxt_port_t *port,
791     nxt_port_send_msg_t *msg, nxt_sendbuf_coalesce_t *sb)
792 {
793     size_t                   bsize;
794     nxt_buf_t                *bmem;
795     nxt_uint_t               i;
796     nxt_port_mmap_msg_t      *mmap_msg;
797     nxt_port_mmap_header_t   *hdr;
798     nxt_port_mmap_handler_t  *mmap_handler;
799 
800     nxt_debug(task, "prepare %z bytes message for transfer to process %PI "
801                     "via shared memory", sb->size, port->pid);
802 
803     bsize = sb->niov * sizeof(nxt_port_mmap_msg_t);
804     mmap_msg = port->mmsg_buf;
805 
806     bmem = msg->buf;
807 
808     for (i = 0; i < sb->niov; i++, mmap_msg++) {
809 
810         /* Lookup buffer which starts current iov_base. */
811         while (bmem && sb->iobuf[i].iov_base != bmem->mem.pos) {
812             bmem = bmem->next;
813         }
814 
815         if (nxt_slow_path(bmem == NULL)) {
816             nxt_log_error(NXT_LOG_ERR, task->log,
817                           "failed to find buf for iobuf[%d]", i);
818             return;
819             /* TODO clear b and exit */
820         }
821 
822         mmap_handler = bmem->parent;
823         hdr = mmap_handler->hdr;
824 
825         mmap_msg->mmap_id = hdr->id;
826         mmap_msg->chunk_id = nxt_port_mmap_chunk_id(hdr, bmem->mem.pos);
827         mmap_msg->size = sb->iobuf[i].iov_len;
828 
829         nxt_debug(task, "mmap_msg={%D, %D, %D} to %PI",
830                   mmap_msg->mmap_id, mmap_msg->chunk_id, mmap_msg->size,
831                   port->pid);
832     }
833 
834     sb->iobuf[0].iov_base = port->mmsg_buf;
835     sb->iobuf[0].iov_len = bsize;
836     sb->niov = 1;
837     sb->size = bsize;
838 
839     msg->port_msg.mmap = 1;
840 }
841 
842 
843 void
844 nxt_port_mmap_read(nxt_task_t *task, nxt_port_recv_msg_t *msg)
845 {
846     nxt_buf_t            *b, **pb;
847     nxt_port_mmap_msg_t  *end, *mmap_msg;
848 
849     pb = &msg->buf;
850     msg->size = 0;
851 
852     for (b = msg->buf; b != NULL; b = b->next) {
853 
854         mmap_msg = (nxt_port_mmap_msg_t *) b->mem.pos;
855         end = (nxt_port_mmap_msg_t *) b->mem.free;
856 
857         while (mmap_msg < end) {
858             nxt_debug(task, "mmap_msg={%D, %D, %D} from %PI",
859                       mmap_msg->mmap_id, mmap_msg->chunk_id, mmap_msg->size,
860                       msg->port_msg.pid);
861 
862             *pb = nxt_port_mmap_get_incoming_buf(task, msg->port,
863                                                  msg->port_msg.pid, mmap_msg);
864             if (nxt_slow_path(*pb == NULL)) {
865                 nxt_log_error(NXT_LOG_ERR, task->log,
866                               "failed to get mmap buffer");
867 
868                 break;
869             }
870 
871             msg->size += mmap_msg->size;
872             pb = &(*pb)->next;
873             mmap_msg++;
874 
875             /* Mark original buf as complete. */
876             b->mem.pos += sizeof(nxt_port_mmap_msg_t);
877         }
878     }
879 }
880 
881 
882 nxt_port_method_t
883 nxt_port_mmap_get_method(nxt_task_t *task, nxt_port_t *port, nxt_buf_t *b)
884 {
885     nxt_port_method_t        m;
886     nxt_port_mmap_header_t   *hdr;
887     nxt_port_mmap_handler_t  *mmap_handler;
888 
889     m = NXT_PORT_METHOD_ANY;
890 
891     for (/* void */; b != NULL; b = b->next) {
892         if (nxt_buf_used_size(b) == 0) {
893             /* empty buffers does not affect method */
894             continue;
895         }
896 
897         if (nxt_buf_is_port_mmap(b)) {
898             mmap_handler = b->parent;
899             hdr = mmap_handler->hdr;
900 
901             if (m == NXT_PORT_METHOD_PLAIN) {
902                 nxt_log_error(NXT_LOG_ERR, task->log,
903                               "mixing plain and mmap buffers, "
904                               "using plain mode");
905 
906                 break;
907             }
908 
909             if (port->pid != hdr->dst_pid) {
910                 nxt_log_error(NXT_LOG_ERR, task->log,
911                               "send mmap buffer for %PI to %PI, "
912                               "using plain mode", hdr->dst_pid, port->pid);
913 
914                 m = NXT_PORT_METHOD_PLAIN;
915 
916                 break;
917             }
918 
919             if (m == NXT_PORT_METHOD_ANY) {
920                 nxt_debug(task, "using mmap mode");
921 
922                 m = NXT_PORT_METHOD_MMAP;
923             }
924         } else {
925             if (m == NXT_PORT_METHOD_MMAP) {
926                 nxt_log_error(NXT_LOG_ERR, task->log,
927                               "mixing mmap and plain buffers, "
928                               "switching to plain mode");
929 
930                 m = NXT_PORT_METHOD_PLAIN;
931 
932                 break;
933             }
934 
935             if (m == NXT_PORT_METHOD_ANY) {
936                 nxt_debug(task, "using plain mode");
937 
938                 m = NXT_PORT_METHOD_PLAIN;
939             }
940         }
941     }
942 
943     return m;
944 }
945