49cd1161a4bfeb5d2dda75a6a4030b58c2e14da7
[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       clib_spinlock_init (&fss->chunk_lock);
131     }
132
133   ssvm_pop_heap (oldheap);
134
135   fsh->n_free_bytes = fsh_free_space (fsh);
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   if (PREDICT_FALSE (size < FIFO_SEGMENT_MIN_FIFO_SIZE))
248     return 0;
249   return max_log2 (size) - FIFO_SEGMENT_MIN_LOG2_FIFO_SIZE;
250 }
251
252 static inline u32
253 fs_freelist_index_to_size (u32 fl_index)
254 {
255   return 1 << (fl_index + FIFO_SEGMENT_MIN_LOG2_FIFO_SIZE);
256 }
257
258 static inline int
259 fs_chunk_size_is_valid (fifo_segment_header_t * fsh, u32 size)
260 {
261   /*
262    * 4K minimum. It's not likely that anything good will happen
263    * with a smaller FIFO.
264    */
265   return size >= FIFO_SEGMENT_MIN_FIFO_SIZE
266     && size <= (1 << fsh->max_log2_chunk_size);
267 }
268
269 static svm_fifo_t *
270 fs_try_alloc_fifo_freelist (fifo_segment_slice_t * fss,
271                             u32 fl_index, u32 data_bytes)
272 {
273   svm_fifo_chunk_t *c;
274   svm_fifo_t *f;
275
276   f = fss->free_fifos;
277   c = fss->free_chunks[fl_index];
278
279   if (!f || !c)
280     return 0;
281
282   fss->free_fifos = f->next;
283   fss->free_chunks[fl_index] = c->next;
284   c->next = 0;
285   c->start_byte = 0;
286   memset (f, 0, sizeof (*f));
287   f->start_chunk = c;
288   f->end_chunk = c;
289
290   fss->n_fl_chunk_bytes -= fs_freelist_index_to_size (fl_index);
291   return f;
292 }
293
294 static svm_fifo_t *
295 fs_try_alloc_fifo_freelist_multi_chunk (fifo_segment_header_t * fsh,
296                                         fifo_segment_slice_t * fss,
297                                         u32 data_bytes)
298 {
299   svm_fifo_chunk_t *c, *first = 0, *last = 0;
300   u32 fl_index, fl_size, n_alloc = 0;
301   svm_fifo_t *f;
302
303   f = fss->free_fifos;
304   if (!f)
305     {
306       void *oldheap = ssvm_push_heap (fsh->ssvm_sh);
307       f = clib_mem_alloc_aligned (sizeof (*f), CLIB_CACHE_LINE_BYTES);
308       ssvm_pop_heap (oldheap);
309       if (!f)
310         return 0;
311       memset (f, 0, sizeof (*f));
312       fsh_free_bytes_sub (fsh, sizeof (*f));
313     }
314   else
315     {
316       fss->free_fifos = f->next;
317     }
318
319   fl_index = fs_freelist_for_size (data_bytes);
320   if (fl_index > 0)
321     fl_index -= 1;
322
323   fl_size = fs_freelist_index_to_size (fl_index);
324
325   while (data_bytes)
326     {
327       c = fss->free_chunks[fl_index];
328       if (c)
329         {
330           fss->free_chunks[fl_index] = c->next;
331           if (!last)
332             last = c;
333           c->next = first;
334           first = c;
335           n_alloc += fl_size;
336           data_bytes -= c->length;
337         }
338       else
339         {
340           /* Failed to allocate with smaller chunks */
341           if (fl_index == 0)
342             {
343               /* free all chunks if any allocated */
344               c = first;
345               while (c)
346                 {
347                   fl_index = fs_freelist_for_size (c->length);
348                   fl_size = fs_freelist_index_to_size (fl_index);
349                   c->next = fss->free_chunks[fl_index];
350                   fss->free_chunks[fl_index] = c;
351                   fss->n_fl_chunk_bytes += fl_size;
352                   data_bytes += fl_size;
353                 }
354               first = last = 0;
355               fl_index = fs_freelist_for_size (data_bytes);
356               if (fss->free_chunks[fl_index + 1])
357                 {
358                   fl_index += 1;
359                   fl_size = fs_freelist_index_to_size (fl_index);
360                   continue;
361                 }
362
363               f->next = fss->free_fifos;
364               fss->free_fifos = f;
365               return 0;
366             }
367           fl_index -= 1;
368           fl_size = fl_size >> 1;
369         }
370     }
371
372   f->start_chunk = first;
373   f->end_chunk = last;
374   fss->n_fl_chunk_bytes -= n_alloc;
375   return f;
376 }
377
378 static int
379 fs_try_alloc_fifo_batch (fifo_segment_header_t * fsh,
380                          fifo_segment_slice_t * fss,
381                          u32 fl_index, u32 batch_size)
382 {
383   u32 hdrs, rounded_data_size;
384   svm_fifo_chunk_t *c;
385   svm_fifo_t *f;
386   void *oldheap;
387   uword size;
388   u8 *fmem;
389   int i;
390
391   rounded_data_size = fs_freelist_index_to_size (fl_index);
392   hdrs = sizeof (*f) + sizeof (*c);
393   size = (uword) (hdrs + rounded_data_size) * batch_size;
394
395   oldheap = ssvm_push_heap (fsh->ssvm_sh);
396   fmem = clib_mem_alloc_aligned_at_offset (size, CLIB_CACHE_LINE_BYTES,
397                                            0 /* align_offset */ ,
398                                            0 /* os_out_of_memory */ );
399   ssvm_pop_heap (oldheap);
400
401   /* Out of space.. */
402   if (fmem == 0)
403     return -1;
404
405   /* Carve fifo + chunk space */
406   for (i = 0; i < batch_size; i++)
407     {
408       f = (svm_fifo_t *) fmem;
409       memset (f, 0, sizeof (*f));
410       f->next = fss->free_fifos;
411       fss->free_fifos = f;
412       c = (svm_fifo_chunk_t *) (fmem + sizeof (*f));
413       c->start_byte = 0;
414       c->length = rounded_data_size;
415       c->enq_rb_index = RBTREE_TNIL_INDEX;
416       c->deq_rb_index = RBTREE_TNIL_INDEX;
417       c->next = fss->free_chunks[fl_index];
418       fss->free_chunks[fl_index] = c;
419       fmem += hdrs + rounded_data_size;
420     }
421
422   fss->n_fl_chunk_bytes += batch_size * rounded_data_size;
423   fsh_free_bytes_sub (fsh, size);
424
425   return 0;
426 }
427
428 /**
429  * Try to allocate new fifo
430  *
431  * Tries the following steps in order:
432  * - grab fifo and chunk from freelists
433  * - batch fifo and chunk allocation
434  * - single fifo allocation
435  * - grab multiple fifo chunks from freelists
436  */
437 static svm_fifo_t *
438 fs_try_alloc_fifo (fifo_segment_header_t * fsh, fifo_segment_slice_t * fss,
439                    u32 data_bytes)
440 {
441   u32 fifo_sz, fl_index;
442   svm_fifo_t *f = 0;
443   uword n_free_bytes;
444
445   fl_index = fs_freelist_for_size (data_bytes);
446   fifo_sz = sizeof (svm_fifo_t) + sizeof (svm_fifo_chunk_t);
447   fifo_sz += 1 << max_log2 (data_bytes);
448
449   if (fss->free_fifos && fss->free_chunks[fl_index])
450     {
451       f = fs_try_alloc_fifo_freelist (fss, fl_index, data_bytes);
452       if (f)
453         goto done;
454     }
455
456   fsh_check_mem (fsh);
457   n_free_bytes = fsh_n_free_bytes (fsh);
458   if (fifo_sz * FIFO_SEGMENT_ALLOC_BATCH_SIZE < n_free_bytes)
459     {
460       if (fs_try_alloc_fifo_batch (fsh, fss, fl_index,
461                                    FIFO_SEGMENT_ALLOC_BATCH_SIZE))
462         goto done;
463
464       f = fs_try_alloc_fifo_freelist (fss, fl_index, data_bytes);
465       goto done;
466     }
467   if (fifo_sz <= n_free_bytes)
468     {
469       void *oldheap = ssvm_push_heap (fsh->ssvm_sh);
470       f = svm_fifo_alloc (data_bytes);
471       ssvm_pop_heap (oldheap);
472       if (f)
473         {
474           fsh_free_bytes_sub (fsh, fifo_sz);
475           goto done;
476         }
477     }
478   if (data_bytes <= fss->n_fl_chunk_bytes)
479     f = fs_try_alloc_fifo_freelist_multi_chunk (fsh, fss, data_bytes);
480
481 done:
482
483   if (f)
484     f->fs_hdr = fsh;
485   return f;
486 }
487
488 svm_fifo_chunk_t *
489 fsh_alloc_chunk (fifo_segment_header_t * fsh, u32 slice_index, u32 chunk_size)
490 {
491   fifo_segment_slice_t *fss;
492   svm_fifo_chunk_t *c;
493   void *oldheap;
494   int fl_index;
495
496   fl_index = fs_freelist_for_size (chunk_size);
497   fss = fsh_slice_get (fsh, slice_index);
498
499   clib_spinlock_lock (&fss->chunk_lock);
500   c = fss->free_chunks[fl_index];
501
502   if (!c)
503     {
504       fsh_check_mem (fsh);
505       chunk_size = fs_freelist_index_to_size (fl_index);
506       if (fsh_n_free_bytes (fsh) < chunk_size)
507         goto done;
508
509       oldheap = ssvm_push_heap (fsh->ssvm_sh);
510       c = svm_fifo_chunk_alloc (chunk_size);
511       ssvm_pop_heap (oldheap);
512
513       if (!c)
514         goto done;
515
516       fsh_free_bytes_sub (fsh, chunk_size + sizeof (*c));
517     }
518   else
519     {
520       fss->free_chunks[fl_index] = c->next;
521       c->next = 0;
522       fss->n_fl_chunk_bytes -= fs_freelist_index_to_size (fl_index);
523     }
524
525 done:
526
527   clib_spinlock_unlock (&fss->chunk_lock);
528
529   return c;
530 }
531
532 static void
533 fsh_slice_collect_chunks (fifo_segment_slice_t * fss, svm_fifo_chunk_t * cur)
534 {
535   svm_fifo_chunk_t *next;
536   int fl_index;
537
538   clib_spinlock_lock (&fss->chunk_lock);
539
540   while (cur)
541     {
542       next = cur->next;
543       fl_index = fs_freelist_for_size (cur->length);
544       cur->next = fss->free_chunks[fl_index];
545       cur->enq_rb_index = RBTREE_TNIL_INDEX;
546       cur->deq_rb_index = RBTREE_TNIL_INDEX;
547       fss->free_chunks[fl_index] = cur;
548       fss->n_fl_chunk_bytes += fs_freelist_index_to_size (fl_index);
549       cur = next;
550     }
551
552   clib_spinlock_unlock (&fss->chunk_lock);
553 }
554
555 void
556 fsh_collect_chunks (fifo_segment_header_t * fsh, u32 slice_index,
557                     svm_fifo_chunk_t * cur)
558 {
559   fifo_segment_slice_t *fss;
560   fss = fsh_slice_get (fsh, slice_index);
561   fsh_slice_collect_chunks (fss, cur);
562 }
563
564 /**
565  * Allocate fifo in fifo segment
566  */
567 svm_fifo_t *
568 fifo_segment_alloc_fifo_w_slice (fifo_segment_t * fs, u32 slice_index,
569                                  u32 data_bytes, fifo_segment_ftype_t ftype)
570 {
571   fifo_segment_header_t *fsh = fs->h;
572   fifo_segment_slice_t *fss;
573   svm_fifo_t *f = 0;
574
575   ASSERT (slice_index < fs->n_slices);
576
577   fss = fsh_slice_get (fsh, slice_index);
578   f = fs_try_alloc_fifo (fsh, fss, data_bytes);
579   if (!f)
580     goto done;
581
582   f->slice_index = slice_index;
583
584   svm_fifo_init (f, data_bytes);
585
586   /* If rx fifo type add to active fifos list. When cleaning up segment,
587    * we need a list of active sessions that should be disconnected. Since
588    * both rx and tx fifos keep pointers to the session, it's enough to track
589    * only one. */
590   if (ftype == FIFO_SEGMENT_RX_FIFO)
591     {
592       if (fss->fifos)
593         {
594           fss->fifos->prev = f;
595           f->next = fss->fifos;
596         }
597       fss->fifos = f;
598       f->flags |= SVM_FIFO_F_LL_TRACKED;
599
600       svm_fifo_init_ooo_lookup (f, 0 /* ooo enq */ );
601     }
602   else
603     {
604       svm_fifo_init_ooo_lookup (f, 1 /* ooo deq */ );
605     }
606
607   fsh_active_fifos_update (fsh, 1);
608
609 done:
610   return (f);
611 }
612
613 /**
614  * Free fifo allocated in fifo segment
615  */
616 void
617 fifo_segment_free_fifo (fifo_segment_t * fs, svm_fifo_t * f)
618 {
619   fifo_segment_header_t *fsh = fs->h;
620   fifo_segment_slice_t *fss;
621
622   ASSERT (f->refcnt > 0);
623
624   if (--f->refcnt > 0)
625     return;
626
627   fss = fsh_slice_get (fsh, f->slice_index);
628
629   /* Remove from active list. Only rx fifos are tracked */
630   if (f->flags & SVM_FIFO_F_LL_TRACKED)
631     {
632       if (f->prev)
633         f->prev->next = f->next;
634       else
635         fss->fifos = f->next;
636       if (f->next)
637         f->next->prev = f->prev;
638       f->flags &= ~SVM_FIFO_F_LL_TRACKED;
639     }
640
641   /* Add to free list */
642   f->next = fss->free_fifos;
643   f->prev = 0;
644   fss->free_fifos = f;
645
646   /* Free fifo chunks */
647   fsh_slice_collect_chunks (fss, f->start_chunk);
648
649   f->start_chunk = f->end_chunk = 0;
650   f->head_chunk = f->tail_chunk = f->ooo_enq = f->ooo_deq = 0;
651
652   /* not allocated on segment heap */
653   svm_fifo_free_chunk_lookup (f);
654   svm_fifo_free_ooo_data (f);
655
656   if (CLIB_DEBUG)
657     {
658       f->master_session_index = ~0;
659       f->master_thread_index = ~0;
660     }
661
662   fsh_active_fifos_update (fsh, -1);
663 }
664
665 int
666 fifo_segment_prealloc_fifo_hdrs (fifo_segment_t * fs, u32 slice_index,
667                                  u32 batch_size)
668 {
669   fifo_segment_header_t *fsh = fs->h;
670   fifo_segment_slice_t *fss;
671   svm_fifo_t *f;
672   void *oldheap;
673   uword size;
674   u8 *fmem;
675   int i;
676
677   fss = fsh_slice_get (fsh, slice_index);
678   size = (uword) (sizeof (*f)) * batch_size;
679
680   oldheap = ssvm_push_heap (fsh->ssvm_sh);
681   fmem = clib_mem_alloc_aligned_at_offset (size, CLIB_CACHE_LINE_BYTES,
682                                            0 /* align_offset */ ,
683                                            0 /* os_out_of_memory */ );
684   ssvm_pop_heap (oldheap);
685
686   /* Out of space.. */
687   if (fmem == 0)
688     return -1;
689
690   /* Carve fifo + chunk space */
691   for (i = 0; i < batch_size; i++)
692     {
693       f = (svm_fifo_t *) fmem;
694       memset (f, 0, sizeof (*f));
695       f->next = fss->free_fifos;
696       fss->free_fifos = f;
697       fmem += sizeof (*f);
698     }
699
700   fsh_free_bytes_sub (fsh, size);
701
702   return 0;
703 }
704
705 int
706 fifo_segment_prealloc_fifo_chunks (fifo_segment_t * fs, u32 slice_index,
707                                    u32 chunk_size, u32 batch_size)
708 {
709   fifo_segment_header_t *fsh = fs->h;
710   u32 rounded_data_size, fl_index;
711   fifo_segment_slice_t *fss;
712   svm_fifo_chunk_t *c;
713   void *oldheap;
714   uword size;
715   u8 *cmem;
716   int i;
717
718   if (!fs_chunk_size_is_valid (fsh, chunk_size))
719     {
720       clib_warning ("chunk size out of range %d", chunk_size);
721       return -1;
722     }
723
724   fl_index = fs_freelist_for_size (chunk_size);
725   rounded_data_size = fs_freelist_index_to_size (fl_index);
726   size = (uword) (sizeof (*c) + rounded_data_size) * batch_size;
727
728   oldheap = ssvm_push_heap (fsh->ssvm_sh);
729   cmem = clib_mem_alloc_aligned_at_offset (size, CLIB_CACHE_LINE_BYTES,
730                                            0 /* align_offset */ ,
731                                            0 /* os_out_of_memory */ );
732   ssvm_pop_heap (oldheap);
733
734   /* Out of space.. */
735   if (cmem == 0)
736     return -1;
737
738   fss = fsh_slice_get (fsh, slice_index);
739
740   /* Carve fifo + chunk space */
741   for (i = 0; i < batch_size; i++)
742     {
743       c = (svm_fifo_chunk_t *) cmem;
744       c->start_byte = 0;
745       c->length = rounded_data_size;
746       c->next = fss->free_chunks[fl_index];
747       fss->free_chunks[fl_index] = c;
748       cmem += sizeof (*c) + rounded_data_size;
749     }
750
751   fss->n_fl_chunk_bytes += batch_size * rounded_data_size;
752   fsh_free_bytes_sub (fsh, size);
753
754   return 0;
755 }
756
757 /**
758  * Pre-allocates fifo pairs in fifo segment
759  */
760 void
761 fifo_segment_preallocate_fifo_pairs (fifo_segment_t * fs,
762                                      u32 rx_fifo_size, u32 tx_fifo_size,
763                                      u32 * n_fifo_pairs)
764 {
765   u32 rx_rounded_data_size, tx_rounded_data_size, pair_size, pairs_to_alloc;
766   u32 hdrs, pairs_per_slice, alloc_now;
767   fifo_segment_header_t *fsh = fs->h;
768   int rx_fl_index, tx_fl_index, i;
769   fifo_segment_slice_t *fss;
770   uword space_available;
771
772   /* Parameter check */
773   if (rx_fifo_size == 0 || tx_fifo_size == 0 || *n_fifo_pairs == 0)
774     return;
775
776   if (!fs_chunk_size_is_valid (fsh, rx_fifo_size))
777     {
778       clib_warning ("rx fifo_size out of range %d", rx_fifo_size);
779       return;
780     }
781
782   if (!fs_chunk_size_is_valid (fsh, tx_fifo_size))
783     {
784       clib_warning ("tx fifo_size out of range %d", tx_fifo_size);
785       return;
786     }
787
788   rx_rounded_data_size = (1 << (max_log2 (rx_fifo_size)));
789   rx_fl_index = fs_freelist_for_size (rx_fifo_size);
790   tx_rounded_data_size = (1 << (max_log2 (tx_fifo_size)));
791   tx_fl_index = fs_freelist_for_size (tx_fifo_size);
792
793   hdrs = sizeof (svm_fifo_t) + sizeof (svm_fifo_chunk_t);
794
795   /* Calculate space requirements */
796   pair_size = 2 * hdrs + rx_rounded_data_size + tx_rounded_data_size;
797   space_available = fsh_free_space (fsh);
798   pairs_to_alloc = space_available / pair_size;
799   pairs_to_alloc = clib_min (pairs_to_alloc, *n_fifo_pairs);
800   pairs_per_slice = pairs_to_alloc / fs->n_slices;
801   pairs_per_slice += pairs_to_alloc % fs->n_slices ? 1 : 0;
802
803   if (!pairs_per_slice)
804     return;
805
806   for (i = 0; i < fs->n_slices; i++)
807     {
808       fss = fsh_slice_get (fsh, i);
809       alloc_now = clib_min (pairs_per_slice, *n_fifo_pairs);
810       if (fs_try_alloc_fifo_batch (fsh, fss, rx_fl_index, alloc_now))
811         clib_warning ("rx prealloc failed: pairs %u", alloc_now);
812       if (fs_try_alloc_fifo_batch (fsh, fss, tx_fl_index, alloc_now))
813         clib_warning ("tx prealloc failed: pairs %u", alloc_now);
814
815       /* Account for the pairs allocated */
816       *n_fifo_pairs -= alloc_now;
817     }
818 }
819
820 /**
821  * Get number of active fifos
822  */
823 u32
824 fifo_segment_num_fifos (fifo_segment_t * fs)
825 {
826   return clib_atomic_load_relax_n (&fs->h->n_active_fifos);
827 }
828
829 static u32
830 fs_slice_num_free_fifos (fifo_segment_slice_t * fss)
831 {
832   svm_fifo_t *f;
833   u32 count = 0;
834
835   f = fss->free_fifos;
836   if (f == 0)
837     return 0;
838
839   while (f)
840     {
841       f = f->next;
842       count++;
843     }
844   return count;
845 }
846
847 u32
848 fifo_segment_num_free_fifos (fifo_segment_t * fs)
849 {
850   fifo_segment_header_t *fsh = fs->h;
851   fifo_segment_slice_t *fss;
852   int slice_index;
853   u32 count = 0;
854
855   for (slice_index = 0; slice_index < fs->n_slices; slice_index++)
856     {
857       fss = fsh_slice_get (fsh, slice_index);
858       count += fs_slice_num_free_fifos (fss);
859     }
860   return count;
861 }
862
863 static u32
864 fs_slice_num_free_chunks (fifo_segment_slice_t * fss, u32 size)
865 {
866   u32 count = 0, rounded_size, fl_index;
867   svm_fifo_chunk_t *c;
868   int i;
869
870   /* Count all free chunks? */
871   if (size == ~0)
872     {
873       for (i = 0; i < vec_len (fss->free_chunks); i++)
874         {
875           c = fss->free_chunks[i];
876           if (c == 0)
877             continue;
878
879           while (c)
880             {
881               c = c->next;
882               count++;
883             }
884         }
885       return count;
886     }
887
888   rounded_size = (1 << (max_log2 (size)));
889   fl_index = fs_freelist_for_size (rounded_size);
890
891   if (fl_index >= vec_len (fss->free_chunks))
892     return 0;
893
894   c = fss->free_chunks[fl_index];
895   if (c == 0)
896     return 0;
897
898   while (c)
899     {
900       c = c->next;
901       count++;
902     }
903   return count;
904 }
905
906 u32
907 fifo_segment_num_free_chunks (fifo_segment_t * fs, u32 size)
908 {
909   fifo_segment_header_t *fsh = fs->h;
910   fifo_segment_slice_t *fss;
911   int slice_index;
912   u32 count = 0;
913
914   for (slice_index = 0; slice_index < fs->n_slices; slice_index++)
915     {
916       fss = fsh_slice_get (fsh, slice_index);
917       count += fs_slice_num_free_chunks (fss, size);
918     }
919   return count;
920 }
921
922 void
923 fifo_segment_update_free_bytes (fifo_segment_t * fs)
924 {
925   fsh_update_free_bytes (fs->h);
926 }
927
928 uword
929 fifo_segment_free_bytes (fifo_segment_t * fs)
930 {
931   return fsh_n_free_bytes (fs->h);
932 }
933
934 uword
935 fifo_segment_fl_chunk_bytes (fifo_segment_t * fs)
936 {
937   fifo_segment_header_t *fsh = fs->h;
938   fifo_segment_slice_t *fss;
939   uword n_bytes = 0;
940   int slice_index;
941
942   for (slice_index = 0; slice_index < fs->n_slices; slice_index++)
943     {
944       fss = fsh_slice_get (fsh, slice_index);
945       n_bytes += fss->n_fl_chunk_bytes;
946     }
947
948   return n_bytes;
949 }
950
951 u8
952 fifo_segment_has_fifos (fifo_segment_t * fs)
953 {
954   fifo_segment_header_t *fsh = fs->h;
955   fifo_segment_slice_t *fss;
956   int slice_index;
957
958   for (slice_index = 0; slice_index < fs->n_slices; slice_index++)
959     {
960       fss = fsh_slice_get (fsh, slice_index);
961       if (fss->fifos)
962         return 1;
963     }
964   return 0;
965 }
966
967 svm_fifo_t *
968 fifo_segment_get_slice_fifo_list (fifo_segment_t * fs, u32 slice_index)
969 {
970   fifo_segment_header_t *fsh = fs->h;
971   fifo_segment_slice_t *fss;
972
973   fss = fsh_slice_get (fsh, slice_index);
974   return fss->fifos;
975 }
976
977 u8 *
978 format_fifo_segment_type (u8 * s, va_list * args)
979 {
980   fifo_segment_t *sp;
981   sp = va_arg (*args, fifo_segment_t *);
982   ssvm_segment_type_t st = ssvm_type (&sp->ssvm);
983
984   if (st == SSVM_SEGMENT_PRIVATE)
985     s = format (s, "%s", "private-heap");
986   else if (st == SSVM_SEGMENT_MEMFD)
987     s = format (s, "%s", "memfd");
988   else if (st == SSVM_SEGMENT_SHM)
989     s = format (s, "%s", "shm");
990   else
991     s = format (s, "%s", "unknown");
992   return s;
993 }
994
995 /**
996  * Segment format function
997  */
998 u8 *
999 format_fifo_segment (u8 * s, va_list * args)
1000 {
1001   u32 count, indent, active_fifos, free_fifos, fifo_hdr = 0;
1002   fifo_segment_t *fs = va_arg (*args, fifo_segment_t *);
1003   int verbose __attribute__ ((unused)) = va_arg (*args, int);
1004   uword est_chunk_bytes, est_free_seg_bytes, free_chunks;
1005   uword chunk_bytes = 0, free_seg_bytes, chunk_size;
1006   fifo_segment_header_t *fsh;
1007   fifo_segment_slice_t *fss;
1008   svm_fifo_chunk_t *c;
1009   u32 slice_index;
1010   char *address;
1011   size_t size;
1012   int i;
1013
1014   indent = format_get_indent (s) + 2;
1015
1016   if (fs == 0)
1017     {
1018       s = format (s, "%-15s%15s%15s%15s%15s%15s", "Name", "Type",
1019                   "HeapSize (M)", "ActiveFifos", "FreeFifos", "Address");
1020       return s;
1021     }
1022
1023   fifo_segment_info (fs, &address, &size);
1024   active_fifos = fifo_segment_num_fifos (fs);
1025   free_fifos = fifo_segment_num_free_fifos (fs);
1026
1027   s = format (s, "%-15v%15U%15llu%15u%15u%15llx", ssvm_name (&fs->ssvm),
1028               format_fifo_segment_type, fs, size >> 20ULL, active_fifos,
1029               free_fifos, address);
1030
1031   if (!verbose)
1032     return s;
1033
1034   fsh = fs->h;
1035
1036   free_chunks = fifo_segment_num_free_chunks (fs, ~0);
1037   if (free_chunks)
1038     s = format (s, "\n\n%UFree chunks by size:\n", format_white_space,
1039                 indent + 2);
1040   else
1041     s = format (s, "\n");
1042
1043   for (slice_index = 0; slice_index < fs->n_slices; slice_index++)
1044     {
1045       fss = fsh_slice_get (fsh, slice_index);
1046       for (i = 0; i < vec_len (fss->free_chunks); i++)
1047         {
1048           c = fss->free_chunks[i];
1049           if (c == 0)
1050             continue;
1051           count = 0;
1052           while (c)
1053             {
1054               c = c->next;
1055               count++;
1056             }
1057
1058           chunk_size = fs_freelist_index_to_size (i);
1059           s = format (s, "%U%-5u kB: %u\n", format_white_space, indent + 2,
1060                       chunk_size >> 10, count);
1061
1062           chunk_bytes += count * chunk_size;
1063         }
1064     }
1065
1066   fifo_hdr = free_fifos * sizeof (svm_fifo_t);
1067   est_chunk_bytes = fifo_segment_fl_chunk_bytes (fs);
1068   est_free_seg_bytes = fifo_segment_free_bytes (fs);
1069   fifo_segment_update_free_bytes (fs);
1070   free_seg_bytes = fifo_segment_free_bytes (fs);
1071
1072   s = format (s, "\n%Useg free bytes: %U (%lu) estimated: %U (%lu)\n",
1073               format_white_space, indent + 2, format_memory_size,
1074               free_seg_bytes, free_seg_bytes, format_memory_size,
1075               est_free_seg_bytes, est_free_seg_bytes);
1076   s = format (s, "%Uchunk free bytes: %U (%lu) estimated: %U (%lu)\n",
1077               format_white_space, indent + 2, format_memory_size, chunk_bytes,
1078               chunk_bytes, format_memory_size, est_chunk_bytes,
1079               est_chunk_bytes);
1080   s = format (s, "%Ufifo hdr free bytes: %U (%u) reserved %U (%lu)\n",
1081               format_white_space, indent + 2, format_memory_size, fifo_hdr,
1082               fifo_hdr, format_memory_size, fsh->n_reserved_bytes,
1083               fsh->n_reserved_bytes);
1084   s = format (s, "\n");
1085
1086   return s;
1087 }
1088
1089 /*
1090  * fd.io coding-style-patch-verification: ON
1091  *
1092  * Local Variables:
1093  * eval: (c-set-style "gnu")
1094  * End:
1095  */