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