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