session: reserve memory for rbtree
[vpp.git] / src / svm / fifo_segment.c
1 /*
2  * Copyright (c) 2016-2019 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <svm/fifo_segment.h>
17
18 /**
19  * Fifo segment free space
20  *
21  * Queries the underlying memory manager, dlmalloc, for free space. Since this
22  * ends up walking the internal data structures, it should not be called
23  * indiscriminately.
24  *
25  * @param fs            fifo segment
26  * @return              number of free bytes
27  */
28 static uword
29 fs_free_space (fifo_segment_t * fs)
30 {
31   struct dlmallinfo dlminfo;
32
33   dlminfo = mspace_mallinfo (fs->ssvm.sh->heap);
34   return dlminfo.fordblks;
35 }
36
37 static inline void
38 fsh_free_bytes_sub (fifo_segment_header_t * fsh, int size)
39 {
40   clib_atomic_fetch_sub_rel (&fsh->n_free_bytes, size);
41 }
42
43 static inline uword
44 fsh_n_free_bytes (fifo_segment_header_t * fsh)
45 {
46   uword n_free = clib_atomic_load_relax_n (&fsh->n_free_bytes);
47   return n_free > fsh->n_reserved_bytes ? n_free - fsh->n_reserved_bytes : 0;
48 }
49
50 static inline void
51 fsh_update_free_btes (fifo_segment_header_t * fsh)
52 {
53   clib_atomic_store_rel_n (&fsh->n_free_bytes,
54                            fs_free_space (fsh->ssvm_sh->heap));
55 }
56
57 static void
58 fsh_check_mem (fifo_segment_header_t * fsh)
59 {
60   uword thresh;
61
62   if (fsh->flags & FIFO_SEGMENT_F_MEM_LIMIT)
63     return;
64
65   thresh = clib_max (0.01 * fsh->ssvm_sh->ssvm_size,
66                      2 * fsh->n_reserved_bytes);
67   if (fsh->n_free_bytes > thresh)
68     return;
69
70   fsh->flags |= FIFO_SEGMENT_F_MEM_LIMIT;
71   fsh_update_free_btes (fsh);
72 }
73
74 static inline fifo_segment_slice_t *
75 fsh_slice_get (fifo_segment_header_t * fsh, u32 slice_index)
76 {
77   return &fsh->slices[slice_index];
78 }
79
80 static inline void
81 fsh_active_fifos_update (fifo_segment_header_t * fsh, int inc)
82 {
83   clib_atomic_fetch_add_rel (&fsh->n_active_fifos, inc);
84 }
85
86 /**
87  * Initialize fifo segment shared header
88  */
89 int
90 fifo_segment_init (fifo_segment_t * fs)
91 {
92   fifo_segment_header_t *fsh;
93   fifo_segment_slice_t *fss;
94   ssvm_shared_header_t *sh;
95   u32 max_chunk_sz, max_chunks;
96   uword max_fifo;
97   void *oldheap;
98   int i;
99
100   sh = fs->ssvm.sh;
101   oldheap = ssvm_push_heap (sh);
102
103   /*
104    * Manually align the fifo segment header to sizeof(uword) = 8 bytes.
105    * Long story made short: the "process-private" fifo segment
106    * is allocated from the main heap, not mmapped. dlmalloc
107    * only guarantees 4-byte alignment, and on aarch64
108    * the fsh can end up 4-byte but not 8-byte aligned.
109    * That eventually causes the atomic op in fifo_segment_update_free_bytes
110    * to backfire.
111    */
112   fsh = clib_mem_alloc_aligned (sizeof (*fsh), sizeof (uword));
113   clib_memset (fsh, 0, sizeof (*fsh));
114   fs->h = sh->opaque[0] = fsh;
115   fs->n_slices = clib_max (fs->n_slices, 1);
116
117   fsh->ssvm_sh = fs->ssvm.sh;
118   fsh->n_slices = fs->n_slices;
119   max_fifo = clib_min ((fs_free_space (fs) - 4096) / 2,
120                        FIFO_SEGMENT_MAX_FIFO_SIZE);
121   fsh->max_log2_chunk_size = max_log2 (max_fifo);
122
123   fsh->slices = clib_mem_alloc (sizeof (*fss) * fs->n_slices);
124   clib_memset (fsh->slices, 0, sizeof (*fss) * fs->n_slices);
125   max_chunk_sz = fsh->max_log2_chunk_size - FIFO_SEGMENT_MIN_LOG2_FIFO_SIZE;
126
127   for (i = 0; i < fs->n_slices; i++)
128     {
129       fss = fsh_slice_get (fsh, i);
130       vec_validate_init_empty (fss->free_chunks, max_chunk_sz, 0);
131     }
132
133   ssvm_pop_heap (oldheap);
134
135   fsh->n_free_bytes = fs_free_space (fs);
136   max_chunks = fsh->n_free_bytes / FIFO_SEGMENT_MIN_FIFO_SIZE;
137   fsh->n_reserved_bytes = (max_chunks / 4) * sizeof (rb_node_t);
138   sh->ready = 1;
139   return (0);
140 }
141
142 /**
143  * Create a fifo segment and initialize as master
144  */
145 int
146 fifo_segment_create (fifo_segment_main_t * sm, fifo_segment_create_args_t * a)
147 {
148   fifo_segment_t *fs;
149   uword baseva;
150   int rv;
151
152   /* Allocate a fresh segment */
153   pool_get_zero (sm->segments, fs);
154
155   baseva = a->segment_type == SSVM_SEGMENT_PRIVATE ? ~0ULL : sm->next_baseva;
156   fs->ssvm.ssvm_size = a->segment_size;
157   fs->ssvm.i_am_master = 1;
158   fs->ssvm.my_pid = getpid ();
159   fs->ssvm.name = format (0, "%s%c", a->segment_name, 0);
160   fs->ssvm.requested_va = baseva;
161
162   if ((rv = ssvm_master_init (&fs->ssvm, a->segment_type)))
163     {
164       pool_put (sm->segments, fs);
165       return (rv);
166     }
167
168   /* Note: requested_va updated due to seg base addr randomization */
169   sm->next_baseva = fs->ssvm.sh->ssvm_va + fs->ssvm.ssvm_size;
170
171   fifo_segment_init (fs);
172   vec_add1 (a->new_segment_indices, fs - sm->segments);
173   return (0);
174 }
175
176 /**
177  * Attach as slave to a fifo segment
178  */
179 int
180 fifo_segment_attach (fifo_segment_main_t * sm, fifo_segment_create_args_t * a)
181 {
182   fifo_segment_t *fs;
183   int rv;
184
185   pool_get_zero (sm->segments, fs);
186
187   fs->ssvm.ssvm_size = a->segment_size;
188   fs->ssvm.my_pid = getpid ();
189   fs->ssvm.name = format (0, "%s%c", a->segment_name, 0);
190   fs->ssvm.requested_va = sm->next_baseva;
191   if (a->segment_type == SSVM_SEGMENT_MEMFD)
192     fs->ssvm.fd = a->memfd_fd;
193   else
194     fs->ssvm.attach_timeout = sm->timeout_in_seconds;
195
196   if ((rv = ssvm_slave_init (&fs->ssvm, a->segment_type)))
197     {
198       _vec_len (fs) = vec_len (fs) - 1;
199       return (rv);
200     }
201
202   /* Fish the segment header */
203   fs->h = fs->ssvm.sh->opaque[0];
204
205   vec_add1 (a->new_segment_indices, fs - sm->segments);
206   return (0);
207 }
208
209 void
210 fifo_segment_delete (fifo_segment_main_t * sm, fifo_segment_t * s)
211 {
212   ssvm_delete (&s->ssvm);
213   clib_memset (s, 0xfe, sizeof (*s));
214   pool_put (sm->segments, s);
215 }
216
217 u32
218 fifo_segment_index (fifo_segment_main_t * sm, fifo_segment_t * s)
219 {
220   return s - sm->segments;
221 }
222
223 fifo_segment_t *
224 fifo_segment_get_segment (fifo_segment_main_t * sm, u32 segment_index)
225 {
226   return pool_elt_at_index (sm->segments, segment_index);
227 }
228
229 void
230 fifo_segment_info (fifo_segment_t * seg, char **address, size_t * size)
231 {
232   *address = (char *) seg->ssvm.sh->ssvm_va;
233   *size = seg->ssvm.ssvm_size;
234 }
235
236 void
237 fifo_segment_main_init (fifo_segment_main_t * sm, u64 baseva,
238                         u32 timeout_in_seconds)
239 {
240   sm->next_baseva = baseva;
241   sm->timeout_in_seconds = timeout_in_seconds;
242 }
243
244 static inline u32
245 fs_freelist_for_size (u32 size)
246 {
247   return max_log2 (size) - FIFO_SEGMENT_MIN_LOG2_FIFO_SIZE;
248 }
249
250 static inline u32
251 fs_freelist_index_to_size (u32 fl_index)
252 {
253   return 1 << (fl_index + FIFO_SEGMENT_MIN_LOG2_FIFO_SIZE);
254 }
255
256 static inline int
257 fs_chunk_size_is_valid (fifo_segment_header_t * fsh, u32 size)
258 {
259   /*
260    * 4K minimum. It's not likely that anything good will happen
261    * with a smaller FIFO.
262    */
263   return size >= FIFO_SEGMENT_MIN_FIFO_SIZE
264     && size <= (1 << fsh->max_log2_chunk_size);
265 }
266
267 static svm_fifo_t *
268 fs_try_alloc_fifo_freelist (fifo_segment_slice_t * fss,
269                             u32 fl_index, u32 data_bytes)
270 {
271   svm_fifo_chunk_t *c;
272   svm_fifo_t *f;
273
274   f = fss->free_fifos;
275   c = fss->free_chunks[fl_index];
276
277   if (!f || !c)
278     return 0;
279
280   fss->free_fifos = f->next;
281   fss->free_chunks[fl_index] = c->next;
282   c->next = c;
283   c->start_byte = 0;
284   c->length = data_bytes;
285   memset (f, 0, sizeof (*f));
286   f->start_chunk = c;
287   f->end_chunk = c;
288
289   fss->n_fl_chunk_bytes -= fs_freelist_index_to_size (fl_index);
290   return f;
291 }
292
293 static svm_fifo_t *
294 fs_try_alloc_fifo_freelist_multi_chunk (fifo_segment_header_t * fsh,
295                                         fifo_segment_slice_t * fss,
296                                         u32 data_bytes)
297 {
298   svm_fifo_chunk_t *c, *first = 0, *last = 0;
299   u32 fl_index, fl_size, n_alloc = 0;
300   svm_fifo_t *f;
301
302   f = fss->free_fifos;
303   if (!f)
304     {
305       void *oldheap = ssvm_push_heap (fsh->ssvm_sh);
306       f = clib_mem_alloc_aligned (sizeof (*f), CLIB_CACHE_LINE_BYTES);
307       ssvm_pop_heap (oldheap);
308       if (!f)
309         return 0;
310       memset (f, 0, sizeof (*f));
311       fsh_free_bytes_sub (fsh, sizeof (*f));
312     }
313   else
314     {
315       fss->free_fifos = f->next;
316     }
317
318   fl_index = fs_freelist_for_size (data_bytes) - 1;
319   fl_size = fs_freelist_index_to_size (fl_index);
320
321   while (data_bytes)
322     {
323       c = fss->free_chunks[fl_index];
324       if (c)
325         {
326           fss->free_chunks[fl_index] = c->next;
327           if (!last)
328             last = c;
329           c->next = first;
330           first = c;
331           n_alloc += fl_size;
332           c->length = clib_min (fl_size, data_bytes);
333           data_bytes -= c->length;
334         }
335       else
336         {
337           ASSERT (fl_index > 0);
338           fl_index -= 1;
339           fl_size = fl_size >> 1;
340         }
341     }
342   f->start_chunk = first;
343   f->end_chunk = last;
344   last->next = first;
345   fss->n_fl_chunk_bytes -= n_alloc;
346   return f;
347 }
348
349 static int
350 fs_try_alloc_fifo_batch (fifo_segment_header_t * fsh,
351                          fifo_segment_slice_t * fss,
352                          u32 fl_index, u32 batch_size)
353 {
354   u32 size, hdrs, rounded_data_size;
355   svm_fifo_chunk_t *c;
356   svm_fifo_t *f;
357   void *oldheap;
358   u8 *fmem;
359   int i;
360
361   rounded_data_size = fs_freelist_index_to_size (fl_index);
362   hdrs = sizeof (*f) + sizeof (*c);
363   size = (hdrs + rounded_data_size) * batch_size;
364
365   oldheap = ssvm_push_heap (fsh->ssvm_sh);
366   fmem = clib_mem_alloc_aligned_at_offset (size, CLIB_CACHE_LINE_BYTES,
367                                            0 /* align_offset */ ,
368                                            0 /* os_out_of_memory */ );
369   ssvm_pop_heap (oldheap);
370
371   /* Out of space.. */
372   if (fmem == 0)
373     return -1;
374
375   /* Carve fifo + chunk space */
376   for (i = 0; i < batch_size; i++)
377     {
378       f = (svm_fifo_t *) fmem;
379       memset (f, 0, sizeof (*f));
380       f->next = fss->free_fifos;
381       fss->free_fifos = f;
382       c = (svm_fifo_chunk_t *) (fmem + sizeof (*f));
383       c->start_byte = 0;
384       c->length = rounded_data_size;
385       c->next = fss->free_chunks[fl_index];
386       fss->free_chunks[fl_index] = c;
387       fmem += hdrs + rounded_data_size;
388     }
389
390   fss->n_fl_chunk_bytes += batch_size * rounded_data_size;
391   fsh_free_bytes_sub (fsh, size);
392
393   return 0;
394 }
395
396 /**
397  * Try to allocate new fifo
398  *
399  * Tries the following steps in order:
400  * - grab fifo and chunk from freelists
401  * - batch fifo and chunk allocation
402  * - single fifo allocation
403  * - grab multiple fifo chunks from freelists
404  */
405 static svm_fifo_t *
406 fs_try_alloc_fifo (fifo_segment_header_t * fsh, fifo_segment_slice_t * fss,
407                    u32 data_bytes)
408 {
409   u32 fifo_sz, fl_index;
410   svm_fifo_t *f = 0;
411   uword n_free_bytes;
412
413   fl_index = fs_freelist_for_size (data_bytes);
414   fifo_sz = sizeof (svm_fifo_t) + sizeof (svm_fifo_chunk_t);
415   fifo_sz += 1 << max_log2 (data_bytes);
416
417   if (fss->free_fifos && fss->free_chunks[fl_index])
418     {
419       f = fs_try_alloc_fifo_freelist (fss, fl_index, data_bytes);
420       if (f)
421         goto done;
422     }
423
424   fsh_check_mem (fsh);
425   n_free_bytes = fsh_n_free_bytes (fsh);
426   if (fifo_sz * FIFO_SEGMENT_ALLOC_BATCH_SIZE < n_free_bytes)
427     {
428       if (fs_try_alloc_fifo_batch (fsh, fss, fl_index,
429                                    FIFO_SEGMENT_ALLOC_BATCH_SIZE))
430         goto done;
431
432       f = fs_try_alloc_fifo_freelist (fss, fl_index, data_bytes);
433       goto done;
434     }
435   if (fifo_sz <= n_free_bytes)
436     {
437       void *oldheap = ssvm_push_heap (fsh->ssvm_sh);
438       f = svm_fifo_create (data_bytes);
439       ssvm_pop_heap (oldheap);
440       if (f)
441         {
442           fsh_free_bytes_sub (fsh, fifo_sz);
443           goto done;
444         }
445     }
446   if (data_bytes <= fss->n_fl_chunk_bytes)
447     f = fs_try_alloc_fifo_freelist_multi_chunk (fsh, fss, data_bytes);
448
449 done:
450
451   return f;
452 }
453
454 /**
455  * Allocate fifo in fifo segment
456  */
457 svm_fifo_t *
458 fifo_segment_alloc_fifo_w_slice (fifo_segment_t * fs, u32 slice_index,
459                                  u32 data_bytes, fifo_segment_ftype_t ftype)
460 {
461   fifo_segment_header_t *fsh = fs->h;
462   fifo_segment_slice_t *fss;
463   svm_fifo_t *f = 0;
464
465   ASSERT (slice_index < fs->n_slices);
466
467   fss = fsh_slice_get (fsh, slice_index);
468   f = fs_try_alloc_fifo (fsh, fss, data_bytes);
469   if (!f)
470     goto done;
471
472   f->slice_index = slice_index;
473
474   /* (re)initialize the fifo, as in svm_fifo_create */
475   svm_fifo_init (f, data_bytes);
476
477   /* Initialize chunks and rbtree for multi-chunk fifos */
478   if (f->start_chunk->next != f->start_chunk)
479     {
480       void *oldheap = ssvm_push_heap (fsh->ssvm_sh);
481       svm_fifo_init_chunks (f);
482       ssvm_pop_heap (oldheap);
483     }
484
485   /* If rx fifo type add to active fifos list. When cleaning up segment,
486    * we need a list of active sessions that should be disconnected. Since
487    * both rx and tx fifos keep pointers to the session, it's enough to track
488    * only one. */
489   if (ftype == FIFO_SEGMENT_RX_FIFO)
490     {
491       if (fss->fifos)
492         {
493           fss->fifos->prev = f;
494           f->next = fss->fifos;
495         }
496       fss->fifos = f;
497       f->flags |= SVM_FIFO_F_LL_TRACKED;
498     }
499   fsh_active_fifos_update (fsh, 1);
500
501 done:
502   return (f);
503 }
504
505 /**
506  * Free fifo allocated in fifo segment
507  */
508 void
509 fifo_segment_free_fifo (fifo_segment_t * fs, svm_fifo_t * f)
510 {
511   fifo_segment_header_t *fsh = fs->h;
512   svm_fifo_chunk_t *cur, *next;
513   fifo_segment_slice_t *fss;
514   void *oldheap;
515   int fl_index;
516
517   ASSERT (f->refcnt > 0);
518
519   if (--f->refcnt > 0)
520     return;
521
522   fss = fsh_slice_get (fsh, f->slice_index);
523
524   /* Remove from active list. Only rx fifos are tracked */
525   if (f->flags & SVM_FIFO_F_LL_TRACKED)
526     {
527       if (f->prev)
528         f->prev->next = f->next;
529       else
530         fss->fifos = f->next;
531       if (f->next)
532         f->next->prev = f->prev;
533       f->flags &= ~SVM_FIFO_F_LL_TRACKED;
534     }
535
536   /* Add to free list */
537   f->next = fss->free_fifos;
538   f->prev = 0;
539   fss->free_fifos = f;
540
541   /* Free fifo chunks */
542   cur = f->start_chunk;
543   do
544     {
545       next = cur->next;
546       fl_index = fs_freelist_for_size (cur->length);
547       ASSERT (fl_index < vec_len (fss->free_chunks));
548       cur->next = fss->free_chunks[fl_index];
549       fss->free_chunks[fl_index] = cur;
550       fss->n_fl_chunk_bytes += fs_freelist_index_to_size (fl_index);
551       cur = next;
552     }
553   while (cur != f->start_chunk);
554
555   f->start_chunk = f->end_chunk = f->new_chunks = 0;
556   f->head_chunk = f->tail_chunk = f->ooo_enq = f->ooo_deq = 0;
557
558   oldheap = ssvm_push_heap (fsh->ssvm_sh);
559   svm_fifo_free_chunk_lookup (f);
560   ssvm_pop_heap (oldheap);
561
562   /* not allocated on segment heap */
563   svm_fifo_free_ooo_data (f);
564
565   if (CLIB_DEBUG)
566     {
567       f->master_session_index = ~0;
568       f->master_thread_index = ~0;
569     }
570
571   fsh_active_fifos_update (fsh, -1);
572 }
573
574 int
575 fifo_segment_prealloc_fifo_hdrs (fifo_segment_t * fs, u32 slice_index,
576                                  u32 batch_size)
577 {
578   fifo_segment_header_t *fsh = fs->h;
579   fifo_segment_slice_t *fss;
580   svm_fifo_t *f;
581   void *oldheap;
582   u32 size;
583   u8 *fmem;
584   int i;
585
586   fss = fsh_slice_get (fsh, slice_index);
587   size = (sizeof (*f)) * batch_size;
588
589   oldheap = ssvm_push_heap (fsh->ssvm_sh);
590   fmem = clib_mem_alloc_aligned_at_offset (size, CLIB_CACHE_LINE_BYTES,
591                                            0 /* align_offset */ ,
592                                            0 /* os_out_of_memory */ );
593   ssvm_pop_heap (oldheap);
594
595   /* Out of space.. */
596   if (fmem == 0)
597     return -1;
598
599   /* Carve fifo + chunk space */
600   for (i = 0; i < batch_size; i++)
601     {
602       f = (svm_fifo_t *) fmem;
603       memset (f, 0, sizeof (*f));
604       f->next = fss->free_fifos;
605       fss->free_fifos = f;
606       fmem += sizeof (*f);
607     }
608
609   fsh_free_bytes_sub (fsh, size);
610
611   return 0;
612 }
613
614 int
615 fifo_segment_prealloc_fifo_chunks (fifo_segment_t * fs, u32 slice_index,
616                                    u32 chunk_size, u32 batch_size)
617 {
618   u32 size, rounded_data_size, fl_index;
619   fifo_segment_header_t *fsh = fs->h;
620   fifo_segment_slice_t *fss;
621   svm_fifo_chunk_t *c;
622   void *oldheap;
623   u8 *cmem;
624   int i;
625
626   if (!fs_chunk_size_is_valid (fsh, chunk_size))
627     {
628       clib_warning ("chunk size out of range %d", chunk_size);
629       return -1;
630     }
631
632   fl_index = fs_freelist_for_size (chunk_size);
633   rounded_data_size = fs_freelist_index_to_size (fl_index);
634   size = (sizeof (*c) + rounded_data_size) * batch_size;
635
636   oldheap = ssvm_push_heap (fsh->ssvm_sh);
637   cmem = clib_mem_alloc_aligned_at_offset (size, CLIB_CACHE_LINE_BYTES,
638                                            0 /* align_offset */ ,
639                                            0 /* os_out_of_memory */ );
640   ssvm_pop_heap (oldheap);
641
642   /* Out of space.. */
643   if (cmem == 0)
644     return -1;
645
646   fss = fsh_slice_get (fsh, slice_index);
647
648   /* Carve fifo + chunk space */
649   for (i = 0; i < batch_size; i++)
650     {
651       c = (svm_fifo_chunk_t *) cmem;
652       c->start_byte = 0;
653       c->length = rounded_data_size;
654       c->next = fss->free_chunks[fl_index];
655       fss->free_chunks[fl_index] = c;
656       cmem += sizeof (*c) + rounded_data_size;
657     }
658
659   fss->n_fl_chunk_bytes += batch_size * rounded_data_size;
660   fsh_free_bytes_sub (fsh, size);
661
662   return 0;
663 }
664
665 /**
666  * Pre-allocates fifo pairs in fifo segment
667  */
668 void
669 fifo_segment_preallocate_fifo_pairs (fifo_segment_t * fs,
670                                      u32 rx_fifo_size, u32 tx_fifo_size,
671                                      u32 * n_fifo_pairs)
672 {
673   u32 rx_rounded_data_size, tx_rounded_data_size, pair_size, pairs_to_alloc;
674   fifo_segment_header_t *fsh = fs->h;
675   int rx_fl_index, tx_fl_index, i;
676   fifo_segment_slice_t *fss;
677   u32 hdrs, pairs_per_slice;
678   uword space_available;
679
680   /* Parameter check */
681   if (rx_fifo_size == 0 || tx_fifo_size == 0 || *n_fifo_pairs == 0)
682     return;
683
684   if (!fs_chunk_size_is_valid (fsh, rx_fifo_size))
685     {
686       clib_warning ("rx fifo_size out of range %d", rx_fifo_size);
687       return;
688     }
689
690   if (!fs_chunk_size_is_valid (fsh, tx_fifo_size))
691     {
692       clib_warning ("tx fifo_size out of range %d", tx_fifo_size);
693       return;
694     }
695
696   rx_rounded_data_size = (1 << (max_log2 (rx_fifo_size)));
697   rx_fl_index = fs_freelist_for_size (rx_fifo_size);
698   tx_rounded_data_size = (1 << (max_log2 (tx_fifo_size)));
699   tx_fl_index = fs_freelist_for_size (tx_fifo_size);
700
701   hdrs = sizeof (svm_fifo_t) + sizeof (svm_fifo_chunk_t);
702
703   /* Calculate space requirements */
704   pair_size = 2 * hdrs + rx_rounded_data_size + tx_rounded_data_size;
705   space_available = fs_free_space (fs);
706   pairs_to_alloc = space_available / pair_size;
707   pairs_to_alloc = clib_min (pairs_to_alloc, *n_fifo_pairs);
708   pairs_per_slice = pairs_to_alloc / fs->n_slices;
709
710   if (!pairs_per_slice)
711     return;
712
713   for (i = 0; i < fs->n_slices; i++)
714     {
715       fss = fsh_slice_get (fsh, i);
716       if (fs_try_alloc_fifo_batch (fsh, fss, rx_fl_index, pairs_to_alloc))
717         clib_warning ("rx prealloc failed: pairs %u", pairs_to_alloc);
718       if (fs_try_alloc_fifo_batch (fsh, fss, tx_fl_index, pairs_to_alloc))
719         clib_warning ("tx prealloc failed: pairs %u", pairs_to_alloc);
720     }
721
722   /* Account for the pairs allocated */
723   *n_fifo_pairs -= pairs_per_slice * fs->n_slices;
724 }
725
726 int
727 fifo_segment_grow_fifo (fifo_segment_t * fs, svm_fifo_t * f, u32 chunk_size)
728 {
729   fifo_segment_header_t *fsh = fs->h;
730   fifo_segment_slice_t *fss;
731   svm_fifo_chunk_t *c;
732   void *oldheap;
733   int fl_index;
734
735   fl_index = fs_freelist_for_size (chunk_size);
736   fss = fsh_slice_get (fsh, f->slice_index);
737
738   oldheap = ssvm_push_heap (fsh->ssvm_sh);
739
740   c = fss->free_chunks[fl_index];
741
742   if (!c)
743     {
744       fsh_check_mem (fsh);
745       if (fsh_n_free_bytes (fsh) < chunk_size)
746         {
747           ssvm_pop_heap (oldheap);
748           return -1;
749         }
750
751       c = svm_fifo_chunk_alloc (chunk_size);
752       if (!c)
753         {
754           ssvm_pop_heap (oldheap);
755           return -1;
756         }
757       fsh_free_bytes_sub (fsh, chunk_size + sizeof (*c));
758     }
759   else
760     {
761       fss->free_chunks[fl_index] = c->next;
762       c->next = 0;
763       fss->n_fl_chunk_bytes -= fs_freelist_index_to_size (fl_index);
764     }
765
766   svm_fifo_add_chunk (f, c);
767
768   ssvm_pop_heap (oldheap);
769   return 0;
770 }
771
772 int
773 fifo_segment_collect_fifo_chunks (fifo_segment_t * fs, svm_fifo_t * f)
774 {
775   fifo_segment_header_t *fsh = fs->h;
776   svm_fifo_chunk_t *cur, *next;
777   fifo_segment_slice_t *fss;
778   void *oldheap;
779   int fl_index;
780
781   oldheap = ssvm_push_heap (fsh->ssvm_sh);
782   cur = svm_fifo_collect_chunks (f);
783
784   fss = fsh_slice_get (fsh, f->slice_index);
785
786   while (cur)
787     {
788       next = cur->next;
789       fl_index = fs_freelist_for_size (cur->length);
790       cur->next = fss->free_chunks[fl_index];
791       fss->free_chunks[fl_index] = cur;
792       cur = next;
793     }
794
795   ssvm_pop_heap (oldheap);
796
797   return 0;
798 }
799
800 /**
801  * Get number of active fifos
802  */
803 u32
804 fifo_segment_num_fifos (fifo_segment_t * fs)
805 {
806   return clib_atomic_load_relax_n (&fs->h->n_active_fifos);
807 }
808
809 static u32
810 fs_slice_num_free_fifos (fifo_segment_slice_t * fss)
811 {
812   svm_fifo_t *f;
813   u32 count = 0;
814
815   f = fss->free_fifos;
816   if (f == 0)
817     return 0;
818
819   while (f)
820     {
821       f = f->next;
822       count++;
823     }
824   return count;
825 }
826
827 u32
828 fifo_segment_num_free_fifos (fifo_segment_t * fs)
829 {
830   fifo_segment_header_t *fsh = fs->h;
831   fifo_segment_slice_t *fss;
832   int slice_index;
833   u32 count = 0;
834
835   for (slice_index = 0; slice_index < fs->n_slices; slice_index++)
836     {
837       fss = fsh_slice_get (fsh, slice_index);
838       count += fs_slice_num_free_fifos (fss);
839     }
840   return count;
841 }
842
843 static u32
844 fs_slice_num_free_chunks (fifo_segment_slice_t * fss, u32 size)
845 {
846   u32 count = 0, rounded_size, fl_index;
847   svm_fifo_chunk_t *c;
848   int i;
849
850   /* Count all free chunks? */
851   if (size == ~0)
852     {
853       for (i = 0; i < vec_len (fss->free_chunks); i++)
854         {
855           c = fss->free_chunks[i];
856           if (c == 0)
857             continue;
858
859           while (c)
860             {
861               c = c->next;
862               count++;
863             }
864         }
865       return count;
866     }
867
868   rounded_size = (1 << (max_log2 (size)));
869   fl_index = fs_freelist_for_size (rounded_size);
870
871   if (fl_index >= vec_len (fss->free_chunks))
872     return 0;
873
874   c = fss->free_chunks[fl_index];
875   if (c == 0)
876     return 0;
877
878   while (c)
879     {
880       c = c->next;
881       count++;
882     }
883   return count;
884 }
885
886 u32
887 fifo_segment_num_free_chunks (fifo_segment_t * fs, u32 size)
888 {
889   fifo_segment_header_t *fsh = fs->h;
890   fifo_segment_slice_t *fss;
891   int slice_index;
892   u32 count = 0;
893
894   for (slice_index = 0; slice_index < fs->n_slices; slice_index++)
895     {
896       fss = fsh_slice_get (fsh, slice_index);
897       count += fs_slice_num_free_chunks (fss, size);
898     }
899   return count;
900 }
901
902 void
903 fifo_segment_update_free_bytes (fifo_segment_t * fs)
904 {
905   fifo_segment_header_t *fsh = fs->h;
906   clib_atomic_store_rel_n (&fsh->n_free_bytes, fs_free_space (fs));
907 }
908
909 uword
910 fifo_segment_free_bytes (fifo_segment_t * fs)
911 {
912   return fsh_n_free_bytes (fs->h);
913 }
914
915 uword
916 fifo_segment_fl_chunk_bytes (fifo_segment_t * fs)
917 {
918   fifo_segment_header_t *fsh = fs->h;
919   fifo_segment_slice_t *fss;
920   uword n_bytes = 0;
921   int slice_index;
922
923   for (slice_index = 0; slice_index < fs->n_slices; slice_index++)
924     {
925       fss = fsh_slice_get (fsh, slice_index);
926       n_bytes += fss->n_fl_chunk_bytes;
927     }
928
929   return n_bytes;
930 }
931
932 u8
933 fifo_segment_has_fifos (fifo_segment_t * fs)
934 {
935   fifo_segment_header_t *fsh = fs->h;
936   fifo_segment_slice_t *fss;
937   int slice_index;
938
939   for (slice_index = 0; slice_index < fs->n_slices; slice_index++)
940     {
941       fss = fsh_slice_get (fsh, slice_index);
942       if (fss->fifos)
943         return 1;
944     }
945   return 0;
946 }
947
948 svm_fifo_t *
949 fifo_segment_get_slice_fifo_list (fifo_segment_t * fs, u32 slice_index)
950 {
951   fifo_segment_header_t *fsh = fs->h;
952   fifo_segment_slice_t *fss;
953
954   fss = fsh_slice_get (fsh, slice_index);
955   return fss->fifos;
956 }
957
958 u8 *
959 format_fifo_segment_type (u8 * s, va_list * args)
960 {
961   fifo_segment_t *sp;
962   sp = va_arg (*args, fifo_segment_t *);
963   ssvm_segment_type_t st = ssvm_type (&sp->ssvm);
964
965   if (st == SSVM_SEGMENT_PRIVATE)
966     s = format (s, "%s", "private-heap");
967   else if (st == SSVM_SEGMENT_MEMFD)
968     s = format (s, "%s", "memfd");
969   else if (st == SSVM_SEGMENT_SHM)
970     s = format (s, "%s", "shm");
971   else
972     s = format (s, "%s", "unknown");
973   return s;
974 }
975
976 /**
977  * Segment format function
978  */
979 u8 *
980 format_fifo_segment (u8 * s, va_list * args)
981 {
982   u32 count, indent, active_fifos, free_fifos, fifo_hdr = 0;
983   fifo_segment_t *fs = va_arg (*args, fifo_segment_t *);
984   int verbose __attribute__ ((unused)) = va_arg (*args, int);
985   uword est_chunk_bytes, est_free_seg_bytes, free_chunks;
986   uword chunk_bytes = 0, free_seg_bytes, chunk_size;
987   fifo_segment_header_t *fsh;
988   fifo_segment_slice_t *fss;
989   svm_fifo_chunk_t *c;
990   u32 slice_index;
991   char *address;
992   size_t size;
993   int i;
994
995   indent = format_get_indent (s) + 2;
996 #if USE_DLMALLOC == 0
997   s = format (s, "%U segment heap: %U\n", format_white_space, indent,
998               format_mheap, fsh->ssvm_sh->heap, verbose);
999   s = format (s, "%U segment has %u active fifos\n",
1000               format_white_space, indent, fifo_segment_num_fifos (fsh));
1001 #endif
1002
1003   if (fs == 0)
1004     {
1005       s = format (s, "%-15s%15s%15s%15s%15s%15s", "Name", "Type",
1006                   "HeapSize (M)", "ActiveFifos", "FreeFifos", "Address");
1007       return s;
1008     }
1009
1010   fifo_segment_info (fs, &address, &size);
1011   active_fifos = fifo_segment_num_fifos (fs);
1012   free_fifos = fifo_segment_num_free_fifos (fs);
1013
1014   s = format (s, "%-15v%15U%15llu%15u%15u%15llx", ssvm_name (&fs->ssvm),
1015               format_fifo_segment_type, fs, size >> 20ULL, active_fifos,
1016               free_fifos, address);
1017
1018   if (!verbose)
1019     return s;
1020
1021   fsh = fs->h;
1022
1023   free_chunks = fifo_segment_num_free_chunks (fs, ~0);
1024   if (free_chunks)
1025     s = format (s, "\n\n%UFree chunks by size:\n", format_white_space,
1026                 indent + 2);
1027   else
1028     s = format (s, "\n");
1029
1030   for (slice_index = 0; slice_index < fs->n_slices; slice_index++)
1031     {
1032       fss = fsh_slice_get (fsh, slice_index);
1033       for (i = 0; i < vec_len (fss->free_chunks); i++)
1034         {
1035           c = fss->free_chunks[i];
1036           if (c == 0)
1037             continue;
1038           count = 0;
1039           while (c)
1040             {
1041               c = c->next;
1042               count++;
1043             }
1044
1045           chunk_size = fs_freelist_index_to_size (i);
1046           s = format (s, "%U%-5u kB: %u\n", format_white_space, indent + 2,
1047                       chunk_size >> 10, count);
1048
1049           chunk_bytes += count * chunk_size;
1050         }
1051     }
1052
1053   fifo_hdr = free_fifos * sizeof (svm_fifo_t);
1054   est_chunk_bytes = fifo_segment_fl_chunk_bytes (fs);
1055   est_free_seg_bytes = fifo_segment_free_bytes (fs);
1056   fifo_segment_update_free_bytes (fs);
1057   free_seg_bytes = fifo_segment_free_bytes (fs);
1058
1059   s = format (s, "\n%Useg free bytes: %U (%lu) estimated: %U (%lu)\n",
1060               format_white_space, indent + 2, format_memory_size,
1061               free_seg_bytes, free_seg_bytes, format_memory_size,
1062               est_free_seg_bytes, est_free_seg_bytes);
1063   s = format (s, "%Uchunk free bytes: %U (%lu) estimated: %U (%lu)\n",
1064               format_white_space, indent + 2, format_memory_size, chunk_bytes,
1065               chunk_bytes, format_memory_size, est_chunk_bytes,
1066               est_chunk_bytes);
1067   s = format (s, "%Ufifo hdr free bytes: %U (%u) reserved %U (%lu)\n",
1068               format_white_space, indent + 2, format_memory_size, fifo_hdr,
1069               fifo_hdr, format_memory_size, fsh->n_reserved_bytes,
1070               fsh->n_reserved_bytes);
1071   s = format (s, "\n");
1072
1073   return s;
1074 }
1075
1076 /*
1077  * fd.io coding-style-patch-verification: ON
1078  *
1079  * Local Variables:
1080  * eval: (c-set-style "gnu")
1081  * End:
1082  */