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