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