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