svm: release mem order for fifo chunk list CAS
[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 #include <vppinfra/mem.h>
18
19 static inline void *
20 fsh_alloc_aligned (fifo_segment_header_t *fsh, uword size, uword align)
21 {
22   uword cur_pos, cur_pos_align, new_pos;
23
24   cur_pos = clib_atomic_load_relax_n (&fsh->byte_index);
25   cur_pos_align = round_pow2_u64 (cur_pos, align);
26   size = round_pow2_u64 (size, align);
27   new_pos = cur_pos_align + size;
28
29   if (new_pos >= fsh->max_byte_index)
30     return 0;
31
32   while (!clib_atomic_cmp_and_swap_acq_relax (&fsh->byte_index, &cur_pos,
33                                               &new_pos, 1 /* weak */))
34     {
35       cur_pos_align = round_pow2_u64 (cur_pos, align);
36       new_pos = cur_pos_align + size;
37       if (new_pos >= fsh->max_byte_index)
38         return 0;
39     }
40   return uword_to_pointer ((u8 *) fsh + cur_pos_align, void *);
41 }
42
43 static inline void *
44 fsh_alloc (fifo_segment_header_t *fsh, uword size)
45 {
46   return fsh_alloc_aligned (fsh, size, 8);
47 }
48
49 static inline fifo_segment_slice_t *
50 fsh_slice_get (fifo_segment_header_t * fsh, u32 slice_index)
51 {
52   return &fsh->slices[slice_index];
53 }
54
55 static inline fifo_slice_private_t *
56 fs_slice_private_get (fifo_segment_t *fs, u32 slice_index)
57 {
58   ASSERT (slice_index < fs->n_slices);
59   return &fs->slices[slice_index];
60 }
61
62 static char *fifo_segment_mem_status_strings[] = {
63 #define _(sym,str) str,
64   foreach_segment_mem_status
65 #undef _
66 };
67
68 static inline uword
69 fsh_n_free_bytes (fifo_segment_header_t * fsh)
70 {
71   uword cur_pos = clib_atomic_load_relax_n (&fsh->byte_index);
72   ASSERT (fsh->max_byte_index > cur_pos);
73   return fsh->max_byte_index - cur_pos;
74 }
75
76 static inline void
77 fsh_cached_bytes_add (fifo_segment_header_t * fsh, uword size)
78 {
79   clib_atomic_fetch_add_rel (&fsh->n_cached_bytes, size);
80 }
81
82 static inline void
83 fsh_cached_bytes_sub (fifo_segment_header_t * fsh, uword size)
84 {
85   clib_atomic_fetch_sub_rel (&fsh->n_cached_bytes, size);
86 }
87
88 static inline uword
89 fsh_n_cached_bytes (fifo_segment_header_t * fsh)
90 {
91   uword n_cached = clib_atomic_load_relax_n (&fsh->n_cached_bytes);
92   return n_cached;
93 }
94
95 static inline void
96 fsh_active_fifos_update (fifo_segment_header_t * fsh, int inc)
97 {
98   clib_atomic_fetch_add_rel (&fsh->n_active_fifos, inc);
99 }
100
101 static inline u32
102 fsh_n_active_fifos (fifo_segment_header_t * fsh)
103 {
104   return clib_atomic_load_relax_n (&fsh->n_active_fifos);
105 }
106
107 static inline uword
108 fsh_virtual_mem (fifo_segment_header_t * fsh)
109 {
110   fifo_segment_slice_t *fss;
111   uword total_vm = 0;
112   int i;
113
114   for (i = 0; i < fsh->n_slices; i++)
115     {
116       fss = fsh_slice_get (fsh, i);
117       total_vm += clib_atomic_load_relax_n (&fss->virtual_mem);
118     }
119   return total_vm;
120 }
121
122 void
123 fsh_virtual_mem_update (fifo_segment_header_t * fsh, u32 slice_index,
124                         int n_bytes)
125 {
126   fifo_segment_slice_t *fss = fsh_slice_get (fsh, slice_index);
127   fss->virtual_mem += n_bytes;
128 }
129
130 static inline int
131 fss_chunk_fl_index_is_valid (fifo_segment_slice_t *fss, u32 fl_index)
132 {
133   return (fl_index < FS_CHUNK_VEC_LEN);
134 }
135
136 #define FS_CL_HEAD_MASK  0xFFFFFFFFFFFF
137 #define FS_CL_HEAD_TMASK 0xFFFF000000000000
138 #define FS_CL_HEAD_TINC  (1ULL << 48)
139
140 static svm_fifo_chunk_t *
141 fss_chunk_free_list_head (fifo_segment_header_t *fsh,
142                           fifo_segment_slice_t *fss, u32 fl_index)
143 {
144   fs_sptr_t headsp = clib_atomic_load_relax_n (&fss->free_chunks[fl_index]);
145   return fs_chunk_ptr (fsh, headsp & FS_CL_HEAD_MASK);
146 }
147
148 static void
149 fss_chunk_free_list_push (fifo_segment_header_t *fsh,
150                           fifo_segment_slice_t *fss, u32 fl_index,
151                           svm_fifo_chunk_t *c)
152 {
153   fs_sptr_t old_head, new_head, csp;
154
155   csp = fs_chunk_sptr (fsh, c);
156   ASSERT (csp <= FS_CL_HEAD_MASK);
157   old_head = clib_atomic_load_acq_n (&fss->free_chunks[fl_index]);
158
159   do
160     {
161       c->next = old_head & FS_CL_HEAD_MASK;
162       new_head = csp + ((old_head + FS_CL_HEAD_TINC) & FS_CL_HEAD_TMASK);
163     }
164   while (!__atomic_compare_exchange (&fss->free_chunks[fl_index], &old_head,
165                                      &new_head, 0 /* weak */, __ATOMIC_RELEASE,
166                                      __ATOMIC_ACQUIRE));
167 }
168
169 static void
170 fss_chunk_free_list_push_list (fifo_segment_header_t *fsh,
171                                fifo_segment_slice_t *fss, u32 fl_index,
172                                svm_fifo_chunk_t *head, svm_fifo_chunk_t *tail)
173 {
174   fs_sptr_t old_head, new_head, headsp;
175
176   headsp = fs_chunk_sptr (fsh, head);
177   ASSERT (headsp <= FS_CL_HEAD_MASK);
178   old_head = clib_atomic_load_acq_n (&fss->free_chunks[fl_index]);
179
180   do
181     {
182       tail->next = old_head & FS_CL_HEAD_MASK;
183       new_head = headsp + ((old_head + FS_CL_HEAD_TINC) & FS_CL_HEAD_TMASK);
184     }
185   while (!__atomic_compare_exchange (&fss->free_chunks[fl_index], &old_head,
186                                      &new_head, 0 /* weak */, __ATOMIC_RELEASE,
187                                      __ATOMIC_ACQUIRE));
188 }
189
190 static svm_fifo_chunk_t *
191 fss_chunk_free_list_pop (fifo_segment_header_t *fsh, fifo_segment_slice_t *fss,
192                          u32 fl_index)
193 {
194   fs_sptr_t old_head, new_head;
195   svm_fifo_chunk_t *c;
196
197   ASSERT (fss_chunk_fl_index_is_valid (fss, fl_index));
198
199   old_head = clib_atomic_load_acq_n (&fss->free_chunks[fl_index]);
200
201   /* Lock-free stacks are affected by ABA if a side allocates a chunk and
202    * shortly thereafter frees it. To circumvent that, reuse the upper bits
203    * of the head of the list shared pointer, i.e., offset to where the chunk
204    * is, as a tag. The tag is incremented with each push/pop operation and
205    * therefore collisions can only happen if an element is popped and pushed
206    * exactly after a complete wrap of the tag (16 bits). It's unlikely either
207    * of the sides will be descheduled for that long */
208   do
209     {
210       if (!(old_head & FS_CL_HEAD_MASK))
211         return 0;
212       c = fs_chunk_ptr (fsh, old_head & FS_CL_HEAD_MASK);
213       new_head = c->next + ((old_head + FS_CL_HEAD_TINC) & FS_CL_HEAD_TMASK);
214     }
215   while (!__atomic_compare_exchange (&fss->free_chunks[fl_index], &old_head,
216                                      &new_head, 0 /* weak */, __ATOMIC_RELEASE,
217                                      __ATOMIC_ACQUIRE));
218
219   return c;
220 }
221
222 static void
223 fss_fifo_free_list_push (fifo_segment_header_t *fsh, fifo_segment_slice_t *fss,
224                          svm_fifo_shared_t *sf)
225 {
226   sf->next = fss->free_fifos;
227   fss->free_fifos = fs_sptr (fsh, sf);
228 }
229
230 static void
231 fss_fifo_free_list_push_list (fifo_segment_header_t *fsh,
232                               fifo_segment_slice_t *fss,
233                               svm_fifo_shared_t *head, svm_fifo_shared_t *tail)
234 {
235   tail->next = fss->free_fifos;
236   fss->free_fifos = fs_sptr (fsh, head);
237 }
238
239 svm_fifo_shared_t *
240 fss_fifo_free_list_pop (fifo_segment_header_t *fsh, fifo_segment_slice_t *fss)
241 {
242   svm_fifo_shared_t *sf;
243   sf = fs_ptr (fsh, fss->free_fifos);
244   fss->free_fifos = sf->next;
245   return sf;
246 }
247
248 static inline void
249 pfss_fifo_add_active_list (fifo_slice_private_t *pfss, svm_fifo_t *f)
250 {
251   if (pfss->active_fifos)
252     {
253       pfss->active_fifos->prev = f;
254       f->next = pfss->active_fifos;
255     }
256   pfss->active_fifos = f;
257 }
258
259 static inline void
260 pfss_fifo_del_active_list (fifo_slice_private_t *pfss, svm_fifo_t *f)
261 {
262   if (f->flags & SVM_FIFO_F_LL_TRACKED)
263     {
264       if (f->prev)
265         f->prev->next = f->next;
266       else
267         pfss->active_fifos = f->next;
268       if (f->next)
269         f->next->prev = f->prev;
270     }
271 }
272
273 static inline uword
274 fss_fl_chunk_bytes (fifo_segment_slice_t * fss)
275 {
276   return clib_atomic_load_relax_n (&fss->n_fl_chunk_bytes);
277 }
278
279 static inline void
280 fss_fl_chunk_bytes_add (fifo_segment_slice_t * fss, uword size)
281 {
282   clib_atomic_fetch_add_relax (&fss->n_fl_chunk_bytes, size);
283 }
284
285 static inline void
286 fss_fl_chunk_bytes_sub (fifo_segment_slice_t * fss, uword size)
287 {
288   clib_atomic_fetch_sub_relax (&fss->n_fl_chunk_bytes, size);
289 }
290
291 /**
292  * Initialize fifo segment shared header
293  */
294 int
295 fifo_segment_init (fifo_segment_t * fs)
296 {
297   u32 align = 8, offset = 2 * 4096, slices_sz, i;
298   uword max_fifo, seg_start, seg_sz;
299   fifo_segment_header_t *fsh;
300   ssvm_shared_header_t *sh;
301   void *seg_data;
302
303   /* TODO remove ssvm heap entirely */
304   sh = fs->ssvm.sh;
305
306   seg_data = (u8 *) sh + offset;
307   seg_sz = sh->ssvm_size - offset;
308
309   fs->n_slices = clib_max (fs->n_slices, 1);
310   slices_sz = sizeof (fifo_segment_slice_t) * fs->n_slices;
311
312   seg_start = round_pow2_u64 (pointer_to_uword (seg_data), align);
313   fsh = uword_to_pointer (seg_start, void *);
314   CLIB_MEM_UNPOISON (fsh, seg_sz);
315   memset (fsh, 0, sizeof (*fsh) + slices_sz);
316
317   fsh->byte_index = sizeof (*fsh) + slices_sz;
318   fsh->max_byte_index = seg_sz;
319   fsh->n_slices = fs->n_slices;
320   max_fifo = clib_min ((seg_sz - slices_sz) / 2, FIFO_SEGMENT_MAX_FIFO_SIZE);
321   fsh->max_log2_fifo_size = min_log2 (max_fifo);
322   fsh->n_cached_bytes = 0;
323   fsh->n_reserved_bytes = fsh->byte_index;
324   fsh->start_byte_index = fsh->byte_index;
325   ASSERT (fsh->max_byte_index <= sh->ssvm_size - offset);
326
327   fs->max_byte_index = fsh->max_byte_index;
328   fs->h = fsh;
329   sh->opaque[0] = (void *) ((u8 *) fsh - (u8 *) fs->ssvm.sh);
330
331   /* Allow random offsets */
332   fs->ssvm.sh->ssvm_va = 0;
333
334   vec_validate (fs->slices, fs->n_slices - 1);
335   for (i = 0; i < fs->n_slices; i++)
336     fs->slices[i].fifos =
337       clib_mem_bulk_init (sizeof (svm_fifo_t), CLIB_CACHE_LINE_BYTES, 32);
338
339   sh->ready = 1;
340   return (0);
341 }
342
343 /**
344  * Create a fifo segment and initialize as master
345  */
346 int
347 fifo_segment_create (fifo_segment_main_t * sm, fifo_segment_create_args_t * a)
348 {
349   fifo_segment_t *fs;
350   uword baseva;
351   int rv;
352
353   /* Allocate a fresh segment */
354   pool_get_zero (sm->segments, fs);
355
356   baseva = a->segment_type == SSVM_SEGMENT_PRIVATE ? ~0ULL : sm->next_baseva;
357   fs->ssvm.ssvm_size = a->segment_size;
358   fs->ssvm.is_server = 1;
359   fs->ssvm.my_pid = getpid ();
360   fs->ssvm.name = format (0, "%s%c", a->segment_name, 0);
361   fs->ssvm.requested_va = baseva;
362
363   if ((rv = ssvm_server_init (&fs->ssvm, a->segment_type)))
364     {
365       pool_put (sm->segments, fs);
366       return (rv);
367     }
368
369   /* Note: requested_va updated due to seg base addr randomization */
370   sm->next_baseva = fs->ssvm.sh->ssvm_va + fs->ssvm.ssvm_size;
371
372   fifo_segment_init (fs);
373   vec_add1 (a->new_segment_indices, fs - sm->segments);
374   return (0);
375 }
376
377 /**
378  * Attach as slave to a fifo segment
379  */
380 int
381 fifo_segment_attach (fifo_segment_main_t * sm, fifo_segment_create_args_t * a)
382 {
383   fifo_segment_header_t *fsh;
384   fifo_segment_t *fs;
385   int rv;
386
387   pool_get_zero (sm->segments, fs);
388
389   fs->ssvm.ssvm_size = a->segment_size;
390   fs->ssvm.my_pid = getpid ();
391   fs->ssvm.name = format (0, "%s%c", a->segment_name, 0);
392   fs->ssvm.requested_va = 0;
393   if (a->segment_type == SSVM_SEGMENT_MEMFD)
394     fs->ssvm.fd = a->memfd_fd;
395   else
396     fs->ssvm.attach_timeout = sm->timeout_in_seconds;
397
398   if ((rv = ssvm_client_init (&fs->ssvm, a->segment_type)))
399     {
400       pool_put (sm->segments, fs);
401       return (rv);
402     }
403
404   /* Probably a segment without fifos */
405   if (!fs->ssvm.sh->opaque[0])
406     goto done;
407
408   fsh = fs->h = (void *) fs->ssvm.sh + (uword) fs->ssvm.sh->opaque[0];
409   fs->max_byte_index = fsh->max_byte_index;
410   vec_validate (fs->slices, 0);
411   fs->slices[0].fifos =
412     clib_mem_bulk_init (sizeof (svm_fifo_t), CLIB_CACHE_LINE_BYTES, 32);
413
414 done:
415   vec_add1 (a->new_segment_indices, fs - sm->segments);
416   return (0);
417 }
418
419 void
420 fifo_segment_delete (fifo_segment_main_t * sm, fifo_segment_t * s)
421 {
422   fifo_segment_cleanup (s);
423   ssvm_delete (&s->ssvm);
424   clib_memset (s, 0xfe, sizeof (*s));
425   pool_put (sm->segments, s);
426 }
427
428 u32
429 fifo_segment_index (fifo_segment_main_t * sm, fifo_segment_t * s)
430 {
431   return s - sm->segments;
432 }
433
434 fifo_segment_t *
435 fifo_segment_get_segment (fifo_segment_main_t * sm, u32 segment_index)
436 {
437   return pool_elt_at_index (sm->segments, segment_index);
438 }
439
440 fifo_segment_t *
441 fifo_segment_get_segment_if_valid (fifo_segment_main_t *sm, u32 segment_index)
442 {
443   if (pool_is_free_index (sm->segments, segment_index))
444     return 0;
445   return pool_elt_at_index (sm->segments, segment_index);
446 }
447
448 void
449 fifo_segment_info (fifo_segment_t * seg, char **address, size_t * size)
450 {
451   *address = (char *) seg->ssvm.sh->ssvm_va;
452   *size = seg->ssvm.ssvm_size;
453 }
454
455 void
456 fifo_segment_main_init (fifo_segment_main_t * sm, u64 baseva,
457                         u32 timeout_in_seconds)
458 {
459   sm->next_baseva = baseva;
460   sm->timeout_in_seconds = timeout_in_seconds;
461 }
462
463 static inline u32
464 fs_freelist_for_size (u32 size)
465 {
466   if (PREDICT_FALSE (size < FIFO_SEGMENT_MIN_FIFO_SIZE))
467     return 0;
468   return clib_min (max_log2 (size) - FIFO_SEGMENT_MIN_LOG2_FIFO_SIZE,
469                    FS_CHUNK_VEC_LEN - 1);
470 }
471
472 static inline u32
473 fs_freelist_index_to_size (u32 fl_index)
474 {
475   return 1 << (fl_index + FIFO_SEGMENT_MIN_LOG2_FIFO_SIZE);
476 }
477
478 static inline int
479 fs_chunk_size_is_valid (fifo_segment_header_t * fsh, u32 size)
480 {
481   /*
482    * 4K minimum. It's not likely that anything good will happen
483    * with a smaller FIFO.
484    */
485   return size >= FIFO_SEGMENT_MIN_FIFO_SIZE &&
486          size <= (1ULL << fsh->max_log2_fifo_size);
487 }
488
489 svm_fifo_chunk_t *
490 fs_try_alloc_multi_chunk (fifo_segment_header_t * fsh,
491                           fifo_segment_slice_t * fss, u32 data_bytes)
492 {
493   u32 fl_index, fl_size, n_alloc = 0, req_bytes = data_bytes;
494   svm_fifo_chunk_t *c, *first = 0, *next;
495
496   fl_index = fs_freelist_for_size (req_bytes);
497   if (fl_index > 0)
498     fl_index -= 1;
499
500   fl_size = fs_freelist_index_to_size (fl_index);
501
502   while (req_bytes)
503     {
504       c = fss_chunk_free_list_pop (fsh, fss, fl_index);
505       if (c)
506         {
507           c->next = fs_chunk_sptr (fsh, first);
508           first = c;
509           n_alloc += fl_size;
510           req_bytes -= clib_min (fl_size, req_bytes);
511         }
512       else
513         {
514           /* Failed to allocate with smaller chunks */
515           if (fl_index == 0)
516             {
517               /* Free all chunks if any allocated */
518               c = first;
519               while (c)
520                 {
521                   fl_index = fs_freelist_for_size (c->length);
522                   next = fs_chunk_ptr (fsh, c->next);
523                   fss_chunk_free_list_push (fsh, fss, fl_index, c);
524                   c = next;
525                 }
526               n_alloc = 0;
527               first = 0;
528               /* As last attempt, try allocating a chunk larger than
529                * the requested size, if possible */
530               fl_index = fs_freelist_for_size (data_bytes) + 1;
531               if (!fss_chunk_fl_index_is_valid (fss, fl_index))
532                 return 0;
533               first = fss_chunk_free_list_pop (fsh, fss, fl_index);
534               if (first)
535                 {
536                   first->next = 0;
537                   n_alloc = fs_freelist_index_to_size (fl_index);
538                   goto done;
539                 }
540               return 0;
541             }
542           fl_index -= 1;
543           fl_size = fl_size >> 1;
544         }
545     }
546
547 done:
548   fss_fl_chunk_bytes_sub (fss, n_alloc);
549   fsh_cached_bytes_sub (fsh, n_alloc);
550   return first;
551 }
552
553 static int
554 fsh_try_alloc_fifo_hdr_batch (fifo_segment_header_t * fsh,
555                               fifo_segment_slice_t * fss, u32 batch_size)
556 {
557   svm_fifo_shared_t *f, *head = 0, *tail;
558   uword size;
559   u8 *fmem;
560   int i;
561
562   ASSERT (batch_size != 0);
563
564   size = (uword) sizeof (*f) * batch_size;
565
566   fmem = fsh_alloc_aligned (fsh, size, CLIB_CACHE_LINE_BYTES);
567   if (fmem == 0)
568     return -1;
569
570   /* Carve fifo hdr space */
571   tail = f = (svm_fifo_shared_t *) fmem;
572   for (i = 0; i < batch_size; i++)
573     {
574       clib_memset (f, 0, sizeof (*f));
575       f->next = fs_sptr (fsh, head);
576       head = f;
577       fmem += sizeof (*f);
578       f = (svm_fifo_shared_t *) fmem;
579     }
580
581   fss_fifo_free_list_push_list (fsh, fss, head, tail);
582
583   return 0;
584 }
585
586 static int
587 fsh_try_alloc_chunk_batch (fifo_segment_header_t * fsh,
588                            fifo_segment_slice_t * fss,
589                            u32 fl_index, u32 batch_size)
590 {
591   svm_fifo_chunk_t *c, *head = 0, *tail;
592   uword size, total_chunk_bytes;
593   u32 rounded_data_size;
594   u8 *cmem;
595   int i;
596
597   ASSERT (batch_size != 0);
598
599   rounded_data_size = fs_freelist_index_to_size (fl_index);
600   total_chunk_bytes = (uword) batch_size *rounded_data_size;
601   size = (uword) (sizeof (*c) + rounded_data_size) * batch_size;
602
603   cmem = fsh_alloc_aligned (fsh, size, 8 /* chunk hdr is 24B */);
604   if (cmem == 0)
605     return -1;
606
607   /* Carve fifo + chunk space */
608   tail = c = (svm_fifo_chunk_t *) cmem;
609   for (i = 0; i < batch_size; i++)
610     {
611       c->start_byte = 0;
612       c->length = rounded_data_size;
613       c->next = fs_chunk_sptr (fsh, head);
614       head = c;
615       cmem += sizeof (*c) + rounded_data_size;
616       c = (svm_fifo_chunk_t *) cmem;
617     }
618
619   fss_chunk_free_list_push_list (fsh, fss, fl_index, head, tail);
620   fss->num_chunks[fl_index] += batch_size;
621   fss_fl_chunk_bytes_add (fss, total_chunk_bytes);
622   fsh_cached_bytes_add (fsh, total_chunk_bytes);
623
624   return 0;
625 }
626
627 static int
628 fs_try_alloc_fifo_batch (fifo_segment_header_t * fsh,
629                          fifo_segment_slice_t * fss,
630                          u32 fl_index, u32 batch_size)
631 {
632   if (fsh_try_alloc_fifo_hdr_batch (fsh, fss, batch_size))
633     return 0;
634   return fsh_try_alloc_chunk_batch (fsh, fss, fl_index, batch_size);
635 }
636
637 static svm_fifo_shared_t *
638 fsh_try_alloc_fifo_hdr (fifo_segment_header_t *fsh, fifo_segment_slice_t *fss)
639 {
640   svm_fifo_shared_t *sf;
641
642   if (!fss->free_fifos)
643     {
644       if (fsh_try_alloc_fifo_hdr_batch (fsh, fss,
645                                         FIFO_SEGMENT_ALLOC_BATCH_SIZE))
646         return 0;
647     }
648
649   sf = fss_fifo_free_list_pop (fsh, fss);
650   clib_memset (sf, 0, sizeof (*sf));
651
652   return sf;
653 }
654
655 static svm_fifo_chunk_t *
656 fsh_try_alloc_chunk (fifo_segment_header_t * fsh,
657                      fifo_segment_slice_t * fss, u32 data_bytes)
658 {
659   svm_fifo_chunk_t *c;
660   u32 fl_index;
661
662   fl_index = fs_freelist_for_size (data_bytes);
663
664 free_list:
665   c = fss_chunk_free_list_pop (fsh, fss, fl_index);
666   if (c)
667     {
668       c->next = 0;
669       fss_fl_chunk_bytes_sub (fss, fs_freelist_index_to_size (fl_index));
670       fsh_cached_bytes_sub (fsh, fs_freelist_index_to_size (fl_index));
671     }
672   else
673     {
674       u32 chunk_size, batch = FIFO_SEGMENT_ALLOC_BATCH_SIZE;
675       uword n_free;
676
677       chunk_size = fs_freelist_index_to_size (fl_index);
678       n_free = fsh_n_free_bytes (fsh);
679
680       if (chunk_size <= n_free)
681         {
682           batch = chunk_size * batch <= n_free ? batch : 1;
683           if (!fsh_try_alloc_chunk_batch (fsh, fss, fl_index, batch))
684             goto free_list;
685         }
686       /* Failed to allocate larger chunk, try to allocate multi-chunk
687        * that is close to what was actually requested */
688       if (data_bytes <= fss_fl_chunk_bytes (fss))
689         {
690           c = fs_try_alloc_multi_chunk (fsh, fss, data_bytes);
691           if (c)
692             goto done;
693           batch = n_free / FIFO_SEGMENT_MIN_FIFO_SIZE;
694           if (!batch || fsh_try_alloc_chunk_batch (fsh, fss, 0, batch))
695             goto done;
696         }
697       if (data_bytes <= fss_fl_chunk_bytes (fss) + n_free)
698         {
699           u32 min_size = FIFO_SEGMENT_MIN_FIFO_SIZE;
700           if (n_free < min_size)
701             goto done;
702           batch = (data_bytes - fss_fl_chunk_bytes (fss)) / min_size;
703           batch = clib_min (batch + 1, n_free / min_size);
704           if (fsh_try_alloc_chunk_batch (fsh, fss, 0, batch))
705             goto done;
706           c = fs_try_alloc_multi_chunk (fsh, fss, data_bytes);
707         }
708     }
709
710 done:
711
712   return c;
713 }
714
715 /**
716  * Try to allocate new fifo
717  *
718  * Tries the following steps in order:
719  * - grab fifo and chunk from freelists
720  * - batch fifo and chunk allocation
721  * - single fifo allocation
722  * - grab multiple fifo chunks from freelists
723  */
724 static svm_fifo_shared_t *
725 fs_try_alloc_fifo (fifo_segment_header_t *fsh, u32 slice_index, u32 data_bytes)
726 {
727   fifo_segment_slice_t *fss;
728   u32 fl_index, min_size;
729   svm_fifo_chunk_t *c;
730   svm_fifo_shared_t *sf = 0;
731
732   fss = fsh_slice_get (fsh, slice_index);
733   min_size = clib_max ((fsh->pct_first_alloc * data_bytes) / 100, 4096);
734   fl_index = fs_freelist_for_size (min_size);
735
736   if (!fss_chunk_fl_index_is_valid (fss, fl_index))
737     return 0;
738
739   sf = fsh_try_alloc_fifo_hdr (fsh, fss);
740   if (!sf)
741     return 0;
742
743   c = fsh_try_alloc_chunk (fsh, fss, min_size);
744   if (!c)
745     {
746       fss_fifo_free_list_push (fsh, fss, sf);
747       return 0;
748     }
749
750   sf->start_chunk = fs_chunk_sptr (fsh, c);
751   while (c->next)
752     c = fs_chunk_ptr (fsh, c->next);
753   sf->end_chunk = fs_chunk_sptr (fsh, c);
754   sf->size = data_bytes;
755   sf->slice_index = slice_index;
756
757   return sf;
758 }
759
760 svm_fifo_chunk_t *
761 fsh_alloc_chunk (fifo_segment_header_t * fsh, u32 slice_index, u32 chunk_size)
762 {
763   fifo_segment_slice_t *fss;
764   svm_fifo_chunk_t *c;
765
766   fss = fsh_slice_get (fsh, slice_index);
767   c = fsh_try_alloc_chunk (fsh, fss, chunk_size);
768
769   return c;
770 }
771
772 static void
773 fsh_slice_collect_chunks (fifo_segment_header_t * fsh,
774                           fifo_segment_slice_t * fss, svm_fifo_chunk_t * c)
775 {
776   u32 n_collect = 0, fl_index;
777   svm_fifo_chunk_t *next;
778
779   while (c)
780     {
781       CLIB_MEM_UNPOISON (c, sizeof (*c));
782       next = fs_chunk_ptr (fsh, c->next);
783       fl_index = fs_freelist_for_size (c->length);
784       fss_chunk_free_list_push (fsh, fss, fl_index, c);
785       n_collect += fs_freelist_index_to_size (fl_index);
786       c = next;
787     }
788
789   fss_fl_chunk_bytes_add (fss, n_collect);
790   fsh_cached_bytes_add (fsh, n_collect);
791 }
792
793 void
794 fsh_collect_chunks (fifo_segment_header_t * fsh, u32 slice_index,
795                     svm_fifo_chunk_t * c)
796 {
797   fifo_segment_slice_t *fss;
798   fss = fsh_slice_get (fsh, slice_index);
799   fsh_slice_collect_chunks (fsh, fss, c);
800 }
801
802 svm_fifo_t *
803 fs_fifo_alloc (fifo_segment_t *fs, u32 slice_index)
804 {
805   fifo_slice_private_t *pfss = &fs->slices[slice_index];
806   svm_fifo_t *f;
807
808   f = clib_mem_bulk_alloc (pfss->fifos);
809   clib_memset (f, 0, sizeof (*f));
810   return f;
811 }
812
813 void
814 fs_fifo_free (fifo_segment_t *fs, svm_fifo_t *f, u32 slice_index)
815 {
816   fifo_slice_private_t *pfss;
817
818   if (CLIB_DEBUG)
819     clib_memset (f, 0xfc, sizeof (*f));
820
821   pfss = &fs->slices[slice_index];
822   clib_mem_bulk_free (pfss->fifos, f);
823 }
824
825 void
826 fifo_segment_cleanup (fifo_segment_t *fs)
827 {
828   int slice_index;
829   svm_msg_q_t *mq = 0;
830
831   for (slice_index = 0; slice_index < fs->n_slices; slice_index++)
832     clib_mem_bulk_destroy (fs->slices[slice_index].fifos);
833
834   vec_free (fs->slices);
835
836   vec_foreach (fs->mqs, mq)
837     svm_msg_q_cleanup (mq);
838
839   vec_free (fs->mqs);
840 }
841
842 /**
843  * Allocate fifo in fifo segment
844  */
845 svm_fifo_t *
846 fifo_segment_alloc_fifo_w_slice (fifo_segment_t * fs, u32 slice_index,
847                                  u32 data_bytes, fifo_segment_ftype_t ftype)
848 {
849   fifo_segment_header_t *fsh = fs->h;
850   fifo_slice_private_t *pfss;
851   fifo_segment_slice_t *fss;
852   svm_fifo_shared_t *sf;
853   svm_fifo_t *f = 0;
854
855   ASSERT (slice_index < fs->n_slices);
856
857   if (PREDICT_FALSE (data_bytes > 1 << fsh->max_log2_fifo_size))
858     return 0;
859
860   sf = fs_try_alloc_fifo (fsh, slice_index, data_bytes);
861   if (!sf)
862     goto done;
863
864   f = fs_fifo_alloc (fs, slice_index);
865   f->fs_hdr = fsh;
866   f->shr = sf;
867
868   svm_fifo_init (f, data_bytes);
869
870   fss = fsh_slice_get (fsh, slice_index);
871   pfss = fs_slice_private_get (fs, slice_index);
872
873   /* If rx fifo type add to active fifos list. When cleaning up segment,
874    * we need a list of active sessions that should be disconnected. Since
875    * both rx and tx fifos keep pointers to the session, it's enough to track
876    * only one. */
877   if (ftype == FIFO_SEGMENT_RX_FIFO)
878     {
879       pfss_fifo_add_active_list (pfss, f);
880       f->flags |= SVM_FIFO_F_LL_TRACKED;
881     }
882
883   fsh_active_fifos_update (fsh, 1);
884   fss->virtual_mem += svm_fifo_size (f);
885
886 done:
887   return (f);
888 }
889
890 svm_fifo_t *
891 fifo_segment_alloc_fifo_w_offset (fifo_segment_t *fs, uword offset)
892 {
893   svm_fifo_t *f = fs_fifo_alloc (fs, 0);
894   svm_fifo_shared_t *sf;
895
896   sf = (svm_fifo_shared_t *) ((u8 *) fs->h + offset);
897   f->fs_hdr = fs->h;
898   f->shr = sf;
899
900   f->ooos_list_head = OOO_SEGMENT_INVALID_INDEX;
901   f->segment_index = SVM_FIFO_INVALID_INDEX;
902   f->refcnt = 1;
903   return f;
904 }
905
906 /**
907  * Free fifo allocated in fifo segment
908  */
909 void
910 fifo_segment_free_fifo (fifo_segment_t * fs, svm_fifo_t * f)
911 {
912   fifo_segment_header_t *fsh = fs->h;
913   fifo_slice_private_t *pfss;
914   fifo_segment_slice_t *fss;
915   svm_fifo_shared_t *sf;
916
917   ASSERT (f->refcnt > 0);
918
919   if (--f->refcnt > 0)
920     return;
921
922   /*
923    * Cleanup shared state
924    */
925
926   sf = f->shr;
927   fss = fsh_slice_get (fsh, sf->slice_index);
928   pfss = fs_slice_private_get (fs, sf->slice_index);
929
930   /* Free fifo chunks */
931   fsh_slice_collect_chunks (fsh, fss, fs_chunk_ptr (fsh, f->shr->start_chunk));
932
933   sf->start_chunk = sf->end_chunk = 0;
934   sf->head_chunk = sf->tail_chunk = 0;
935
936   /* Add to free list */
937   fss_fifo_free_list_push (fsh, fss, sf);
938
939   fss->virtual_mem -= svm_fifo_size (f);
940
941   /*
942    *  Cleanup private state
943    */
944
945   /* Remove from active list. Only rx fifos are tracked */
946   if (f->flags & SVM_FIFO_F_LL_TRACKED)
947     {
948       pfss_fifo_del_active_list (pfss, f);
949       f->flags &= ~SVM_FIFO_F_LL_TRACKED;
950     }
951
952   svm_fifo_free_chunk_lookup (f);
953   svm_fifo_free_ooo_data (f);
954
955   if (CLIB_DEBUG)
956     {
957       sf->master_session_index = ~0;
958       f->master_thread_index = ~0;
959     }
960
961   f->ooo_enq = f->ooo_deq = 0;
962   f->prev = 0;
963
964   fs_fifo_free (fs, f, f->shr->slice_index);
965
966   fsh_active_fifos_update (fsh, -1);
967 }
968
969 void
970 fifo_segment_free_client_fifo (fifo_segment_t *fs, svm_fifo_t *f)
971 {
972   fs_fifo_free (fs, f, 0 /* clients attach fifos in slice 0 */);
973 }
974
975 void
976 fifo_segment_detach_fifo (fifo_segment_t *fs, svm_fifo_t **f)
977 {
978   fifo_slice_private_t *pfss;
979   fifo_segment_slice_t *fss;
980   svm_fifo_t *of = *f;
981   u32 slice_index;
982
983   slice_index = of->master_thread_index;
984   fss = fsh_slice_get (fs->h, slice_index);
985   pfss = fs_slice_private_get (fs, slice_index);
986   fss->virtual_mem -= svm_fifo_size (of);
987   if (of->flags & SVM_FIFO_F_LL_TRACKED)
988     pfss_fifo_del_active_list (pfss, of);
989
990   /* Collect chunks that were provided in return for those detached */
991   fsh_slice_collect_chunks (fs->h, fss, of->chunks_at_attach);
992   of->chunks_at_attach = 0;
993
994   /* Collect hdr that was provided in return for the detached */
995   fss_fifo_free_list_push (fs->h, fss, of->hdr_at_attach);
996   of->hdr_at_attach = 0;
997
998   clib_mem_bulk_free (pfss->fifos, *f);
999   *f = 0;
1000 }
1001
1002 void
1003 fifo_segment_attach_fifo (fifo_segment_t *fs, svm_fifo_t **f, u32 slice_index)
1004 {
1005   svm_fifo_chunk_t *c, *nc, *pc = 0;
1006   fifo_slice_private_t *pfss;
1007   fifo_segment_slice_t *fss;
1008   svm_fifo_t *nf, *of;
1009
1010   nf = fs_fifo_alloc (fs, slice_index);
1011   clib_memcpy_fast (nf, *f, sizeof (*nf));
1012
1013   fss = fsh_slice_get (fs->h, slice_index);
1014   pfss = fs_slice_private_get (fs, slice_index);
1015   fss->virtual_mem += svm_fifo_size (nf);
1016   nf->next = nf->prev = 0;
1017   if (nf->flags & SVM_FIFO_F_LL_TRACKED)
1018     pfss_fifo_add_active_list (pfss, nf);
1019
1020   /* Allocate shared hdr and chunks to be collected at detach in return
1021    * for those that are being attached now */
1022   of = *f;
1023   of->hdr_at_attach = fsh_try_alloc_fifo_hdr (fs->h, fss);
1024
1025   c = fs_chunk_ptr (fs->h, nf->shr->start_chunk);
1026   of->chunks_at_attach = pc = fsh_try_alloc_chunk (fs->h, fss, c->length);
1027
1028   while ((c = fs_chunk_ptr (fs->h, c->next)))
1029     {
1030       nc = fsh_try_alloc_chunk (fs->h, fss, c->length);
1031       pc->next = fs_chunk_sptr (fs->h, nc);
1032       pc = nc;
1033     }
1034
1035   nf->shr->slice_index = slice_index;
1036   *f = nf;
1037 }
1038
1039 uword
1040 fifo_segment_fifo_offset (svm_fifo_t *f)
1041 {
1042   return (u8 *) f->shr - (u8 *) f->fs_hdr;
1043 }
1044
1045 svm_fifo_chunk_t *
1046 fifo_segment_alloc_chunk_w_slice (fifo_segment_t *fs, u32 slice_index,
1047                                   u32 chunk_size)
1048 {
1049   fifo_segment_header_t *fsh = fs->h;
1050   fifo_segment_slice_t *fss;
1051
1052   fss = fsh_slice_get (fsh, slice_index);
1053   return fsh_try_alloc_chunk (fsh, fss, chunk_size);
1054 }
1055
1056 void
1057 fifo_segment_collect_chunk (fifo_segment_t *fs, u32 slice_index,
1058                             svm_fifo_chunk_t *c)
1059 {
1060   fsh_collect_chunks (fs->h, slice_index, c);
1061 }
1062
1063 uword
1064 fifo_segment_chunk_offset (fifo_segment_t *fs, svm_fifo_chunk_t *c)
1065 {
1066   return (u8 *) c - (u8 *) fs->h;
1067 }
1068
1069 svm_msg_q_t *
1070 fifo_segment_msg_q_alloc (fifo_segment_t *fs, u32 mq_index,
1071                           svm_msg_q_cfg_t *cfg)
1072 {
1073   fifo_segment_header_t *fsh = fs->h;
1074   svm_msg_q_shared_t *smq;
1075   svm_msg_q_t *mq;
1076   void *base;
1077   u32 size;
1078
1079   if (!fs->mqs)
1080     {
1081       u32 n_mqs = clib_max (fs->h->n_mqs, 1);
1082       vec_validate (fs->mqs, n_mqs - 1);
1083     }
1084
1085   size = svm_msg_q_size_to_alloc (cfg);
1086   base = fsh_alloc_aligned (fsh, size, 8);
1087   fsh->n_reserved_bytes += size;
1088
1089   smq = svm_msg_q_init (base, cfg);
1090   mq = vec_elt_at_index (fs->mqs, mq_index);
1091   svm_msg_q_attach (mq, smq);
1092
1093   return mq;
1094 }
1095
1096 svm_msg_q_t *
1097 fifo_segment_msg_q_attach (fifo_segment_t *fs, uword offset, u32 mq_index)
1098 {
1099   svm_msg_q_t *mq;
1100
1101   if (!fs->mqs)
1102     {
1103       u32 n_mqs = clib_max (fs->h->n_mqs, 1);
1104       vec_validate (fs->mqs, n_mqs - 1);
1105     }
1106
1107   mq = vec_elt_at_index (fs->mqs, mq_index);
1108
1109   if (!mq->q.shr)
1110     {
1111       svm_msg_q_shared_t *smq;
1112       smq = (svm_msg_q_shared_t *) ((u8 *) fs->h + offset);
1113       svm_msg_q_attach (mq, smq);
1114     }
1115
1116   ASSERT (fifo_segment_msg_q_offset (fs, mq_index) == offset);
1117
1118   return mq;
1119 }
1120
1121 void
1122 fifo_segment_msg_qs_discover (fifo_segment_t *fs, int *fds, u32 n_fds)
1123 {
1124   svm_msg_q_shared_t *smq;
1125   u32 n_mqs, size, i;
1126   uword offset = 0, n_alloced;
1127   svm_msg_q_t *mq;
1128
1129   n_mqs = fs->h->n_mqs;
1130   if (n_fds && n_mqs != n_fds)
1131     {
1132       clib_warning ("expected %u fds got %u", n_mqs, n_fds);
1133       return;
1134     }
1135
1136   vec_validate (fs->mqs, n_mqs - 1);
1137   n_alloced = fs->h->n_reserved_bytes - fs->h->start_byte_index;
1138   ASSERT (n_alloced % n_mqs == 0);
1139   size = n_alloced / n_mqs;
1140
1141   offset = fs->h->start_byte_index;
1142   for (i = 0; i < n_mqs; i++)
1143     {
1144       mq = vec_elt_at_index (fs->mqs, i);
1145       smq = (svm_msg_q_shared_t *) ((u8 *) fs->h + offset);
1146       svm_msg_q_attach (mq, smq);
1147       if (n_fds)
1148         svm_msg_q_set_eventfd (mq, fds[i]);
1149       offset += size;
1150     }
1151 }
1152
1153 uword
1154 fifo_segment_msg_q_offset (fifo_segment_t *fs, u32 mq_index)
1155 {
1156   svm_msg_q_t *mq = vec_elt_at_index (fs->mqs, mq_index);
1157
1158   if (mq->q.shr == 0)
1159     return ~0ULL;
1160
1161   return (uword) ((u8 *) mq->q.shr - (u8 *) fs->h) -
1162          sizeof (svm_msg_q_shared_t);
1163 }
1164
1165 int
1166 fifo_segment_prealloc_fifo_hdrs (fifo_segment_t * fs, u32 slice_index,
1167                                  u32 batch_size)
1168 {
1169   fifo_segment_header_t *fsh = fs->h;
1170   fifo_segment_slice_t *fss;
1171
1172   fss = fsh_slice_get (fsh, slice_index);
1173   return fsh_try_alloc_fifo_hdr_batch (fsh, fss, batch_size);
1174 }
1175
1176 int
1177 fifo_segment_prealloc_fifo_chunks (fifo_segment_t * fs, u32 slice_index,
1178                                    u32 chunk_size, u32 batch_size)
1179 {
1180   fifo_segment_header_t *fsh = fs->h;
1181   fifo_segment_slice_t *fss;
1182   u32 fl_index;
1183
1184   if (!fs_chunk_size_is_valid (fsh, chunk_size))
1185     {
1186       clib_warning ("chunk size out of range %d", chunk_size);
1187       return -1;
1188     }
1189
1190   fl_index = fs_freelist_for_size (chunk_size);
1191   fss = fsh_slice_get (fsh, slice_index);
1192
1193   return fsh_try_alloc_chunk_batch (fsh, fss, fl_index, batch_size);
1194 }
1195
1196 /**
1197  * Pre-allocates fifo pairs in fifo segment
1198  */
1199 void
1200 fifo_segment_preallocate_fifo_pairs (fifo_segment_t * fs,
1201                                      u32 rx_fifo_size, u32 tx_fifo_size,
1202                                      u32 * n_fifo_pairs)
1203 {
1204   u32 rx_rounded_data_size, tx_rounded_data_size, pair_size, pairs_to_alloc;
1205   u32 hdrs, pairs_per_slice, alloc_now;
1206   fifo_segment_header_t *fsh = fs->h;
1207   int rx_fl_index, tx_fl_index, i;
1208   fifo_segment_slice_t *fss;
1209   uword space_available;
1210
1211   /* Parameter check */
1212   if (rx_fifo_size == 0 || tx_fifo_size == 0 || *n_fifo_pairs == 0)
1213     return;
1214
1215   if (!fs_chunk_size_is_valid (fsh, rx_fifo_size))
1216     {
1217       clib_warning ("rx fifo_size out of range %d", rx_fifo_size);
1218       return;
1219     }
1220
1221   if (!fs_chunk_size_is_valid (fsh, tx_fifo_size))
1222     {
1223       clib_warning ("tx fifo_size out of range %d", tx_fifo_size);
1224       return;
1225     }
1226
1227   rx_rounded_data_size = (1 << (max_log2 (rx_fifo_size)));
1228   rx_fl_index = fs_freelist_for_size (rx_fifo_size);
1229   tx_rounded_data_size = (1 << (max_log2 (tx_fifo_size)));
1230   tx_fl_index = fs_freelist_for_size (tx_fifo_size);
1231
1232   hdrs = sizeof (svm_fifo_t) + sizeof (svm_fifo_chunk_t);
1233
1234   /* Calculate space requirements */
1235   pair_size = 2 * hdrs + rx_rounded_data_size + tx_rounded_data_size;
1236   space_available = fsh_n_free_bytes (fsh);
1237   pairs_to_alloc = space_available / pair_size;
1238   pairs_to_alloc = clib_min (pairs_to_alloc, *n_fifo_pairs);
1239   pairs_per_slice = pairs_to_alloc / fs->n_slices;
1240   pairs_per_slice += pairs_to_alloc % fs->n_slices ? 1 : 0;
1241
1242   if (!pairs_per_slice)
1243     return;
1244
1245   for (i = 0; i < fs->n_slices; i++)
1246     {
1247       alloc_now = clib_min (pairs_per_slice, *n_fifo_pairs);
1248       if (0 == alloc_now)
1249         break;
1250
1251       fss = fsh_slice_get (fsh, i);
1252       if (fs_try_alloc_fifo_batch (fsh, fss, rx_fl_index, alloc_now))
1253         clib_warning ("rx prealloc failed: pairs %u", alloc_now);
1254       if (fs_try_alloc_fifo_batch (fsh, fss, tx_fl_index, alloc_now))
1255         clib_warning ("tx prealloc failed: pairs %u", alloc_now);
1256
1257       /* Account for the pairs allocated */
1258       *n_fifo_pairs -= alloc_now;
1259     }
1260 }
1261
1262 /**
1263  * Get number of active fifos
1264  */
1265 u32
1266 fifo_segment_num_fifos (fifo_segment_t * fs)
1267 {
1268   return fsh_n_active_fifos (fs->h);
1269 }
1270
1271 static u32
1272 fs_slice_num_free_fifos (fifo_segment_header_t *fsh, fifo_segment_slice_t *fss)
1273 {
1274   svm_fifo_shared_t *f;
1275   u32 count = 0;
1276
1277   f = fs_ptr (fsh, fss->free_fifos);
1278   if (f == 0)
1279     return 0;
1280
1281   while (f)
1282     {
1283       f = fs_ptr (fsh, f->next);
1284       count++;
1285     }
1286   return count;
1287 }
1288
1289 u32
1290 fifo_segment_num_free_fifos (fifo_segment_t * fs)
1291 {
1292   fifo_segment_header_t *fsh = fs->h;
1293   fifo_segment_slice_t *fss;
1294   int slice_index;
1295   u32 count = 0;
1296
1297   for (slice_index = 0; slice_index < fs->n_slices; slice_index++)
1298     {
1299       fss = fsh_slice_get (fsh, slice_index);
1300       count += fs_slice_num_free_fifos (fsh, fss);
1301     }
1302   return count;
1303 }
1304
1305 static u32
1306 fs_slice_num_free_chunks (fifo_segment_header_t *fsh,
1307                           fifo_segment_slice_t *fss, u32 size)
1308 {
1309   u32 count = 0, rounded_size, fl_index;
1310   svm_fifo_chunk_t *c;
1311   int i;
1312
1313   /* Count all free chunks? */
1314   if (size == ~0)
1315     {
1316       for (i = 0; i < FS_CHUNK_VEC_LEN; i++)
1317         {
1318           c = fss_chunk_free_list_head (fsh, fss, i);
1319           if (c == 0)
1320             continue;
1321
1322           while (c)
1323             {
1324               c = fs_chunk_ptr (fsh, c->next);
1325               count++;
1326             }
1327         }
1328       return count;
1329     }
1330
1331   rounded_size = (1 << (max_log2 (size)));
1332   fl_index = fs_freelist_for_size (rounded_size);
1333
1334   if (fl_index >= FS_CHUNK_VEC_LEN)
1335     return 0;
1336
1337   c = fss_chunk_free_list_head (fsh, fss, fl_index);
1338   if (c == 0)
1339     return 0;
1340
1341   while (c)
1342     {
1343       c = fs_chunk_ptr (fsh, c->next);
1344       count++;
1345     }
1346   return count;
1347 }
1348
1349 u32
1350 fifo_segment_num_free_chunks (fifo_segment_t * fs, u32 size)
1351 {
1352   fifo_segment_header_t *fsh = fs->h;
1353   fifo_segment_slice_t *fss;
1354   int slice_index;
1355   u32 count = 0;
1356
1357   for (slice_index = 0; slice_index < fs->n_slices; slice_index++)
1358     {
1359       fss = fsh_slice_get (fsh, slice_index);
1360       count += fs_slice_num_free_chunks (fsh, fss, size);
1361     }
1362   return count;
1363 }
1364
1365 uword
1366 fifo_segment_size (fifo_segment_t * fs)
1367 {
1368   return fs->h->max_byte_index - fs->h->n_reserved_bytes;
1369 }
1370
1371 u8
1372 fsh_has_reached_mem_limit (fifo_segment_header_t * fsh)
1373 {
1374   return (fsh->flags & FIFO_SEGMENT_F_MEM_LIMIT) ? 1 : 0;
1375 }
1376
1377 void
1378 fsh_reset_mem_limit (fifo_segment_header_t * fsh)
1379 {
1380   fsh->flags &= ~FIFO_SEGMENT_F_MEM_LIMIT;
1381 }
1382
1383 void *
1384 fifo_segment_alloc (fifo_segment_t *fs, uword size)
1385 {
1386   void *rv = fsh_alloc (fs->h, size);
1387   /* Mark externally allocated bytes as reserved. This helps
1388    * @ref fifo_segment_size report bytes used only for fifos */
1389   fs->h->n_reserved_bytes += size;
1390   return rv;
1391 }
1392
1393 uword
1394 fifo_segment_free_bytes (fifo_segment_t * fs)
1395 {
1396   return fsh_n_free_bytes (fs->h);
1397 }
1398
1399 uword
1400 fifo_segment_cached_bytes (fifo_segment_t * fs)
1401 {
1402   return fsh_n_cached_bytes (fs->h);
1403 }
1404
1405 uword
1406 fifo_segment_available_bytes (fifo_segment_t * fs)
1407 {
1408   return fsh_n_free_bytes (fs->h) + fsh_n_cached_bytes (fs->h);
1409 }
1410
1411 uword
1412 fifo_segment_fl_chunk_bytes (fifo_segment_t * fs)
1413 {
1414   fifo_segment_header_t *fsh = fs->h;
1415   fifo_segment_slice_t *fss;
1416   uword n_bytes = 0;
1417   int slice_index;
1418
1419   for (slice_index = 0; slice_index < fs->n_slices; slice_index++)
1420     {
1421       fss = fsh_slice_get (fsh, slice_index);
1422       n_bytes += fss_fl_chunk_bytes (fss);
1423     }
1424
1425   return n_bytes;
1426 }
1427
1428 u8
1429 fifo_segment_has_fifos (fifo_segment_t * fs)
1430 {
1431   return (fsh_n_active_fifos (fs->h) != 0);
1432 }
1433
1434 svm_fifo_t *
1435 fifo_segment_get_slice_fifo_list (fifo_segment_t * fs, u32 slice_index)
1436 {
1437   fifo_slice_private_t *pfss;
1438
1439   pfss = fs_slice_private_get (fs, slice_index);
1440   return pfss->active_fifos;
1441 }
1442
1443 u8
1444 fifo_segment_get_mem_usage (fifo_segment_t * fs)
1445 {
1446   uword size, in_use;
1447
1448   size = fifo_segment_size (fs);
1449   in_use =
1450     size - fifo_segment_free_bytes (fs) - fifo_segment_cached_bytes (fs);
1451   return (in_use * 100) / size;
1452 }
1453
1454 fifo_segment_mem_status_t
1455 fifo_segment_determine_status (fifo_segment_header_t * fsh, u8 usage)
1456 {
1457   if (!fsh->high_watermark || !fsh->low_watermark)
1458     return MEMORY_PRESSURE_NO_PRESSURE;
1459
1460   /* once the no-memory is detected, the status continues
1461    * until memory usage gets below the high watermark
1462    */
1463   if (fsh_has_reached_mem_limit (fsh))
1464     {
1465       if (usage >= fsh->high_watermark)
1466         return MEMORY_PRESSURE_NO_MEMORY;
1467       else
1468         fsh_reset_mem_limit (fsh);
1469     }
1470
1471   if (usage >= fsh->high_watermark)
1472     return MEMORY_PRESSURE_HIGH_PRESSURE;
1473
1474   else if (usage >= fsh->low_watermark)
1475     return MEMORY_PRESSURE_LOW_PRESSURE;
1476
1477   return MEMORY_PRESSURE_NO_PRESSURE;
1478 }
1479
1480 fifo_segment_mem_status_t
1481 fifo_segment_get_mem_status (fifo_segment_t * fs)
1482 {
1483   fifo_segment_header_t *fsh = fs->h;
1484   u8 usage = fifo_segment_get_mem_usage (fs);
1485
1486   return fifo_segment_determine_status (fsh, usage);
1487 }
1488
1489 u8 *
1490 format_fifo_segment_type (u8 * s, va_list * args)
1491 {
1492   fifo_segment_t *sp;
1493   sp = va_arg (*args, fifo_segment_t *);
1494   ssvm_segment_type_t st = ssvm_type (&sp->ssvm);
1495
1496   if (st == SSVM_SEGMENT_PRIVATE)
1497     s = format (s, "%s", "private");
1498   else if (st == SSVM_SEGMENT_MEMFD)
1499     s = format (s, "%s", "memfd");
1500   else if (st == SSVM_SEGMENT_SHM)
1501     s = format (s, "%s", "shm");
1502   else
1503     s = format (s, "%s", "unknown");
1504   return s;
1505 }
1506
1507 /**
1508  * Segment format function
1509  */
1510 u8 *
1511 format_fifo_segment (u8 * s, va_list * args)
1512 {
1513   u32 count, indent, active_fifos, free_fifos;
1514   fifo_segment_t *fs = va_arg (*args, fifo_segment_t *);
1515   int verbose __attribute__ ((unused)) = va_arg (*args, int);
1516   uword est_chunk_bytes, est_free_seg_bytes, free_chunks;
1517   uword chunk_bytes = 0, free_seg_bytes, chunk_size;
1518   uword tracked_cached_bytes;
1519   uword fifo_hdr = 0, reserved;
1520   fifo_segment_header_t *fsh;
1521   fifo_segment_slice_t *fss;
1522   svm_fifo_chunk_t *c;
1523   u32 slice_index;
1524   char *address;
1525   size_t size;
1526   int i;
1527   uword allocated, in_use, virt;
1528   f64 usage;
1529   fifo_segment_mem_status_t mem_st;
1530
1531   indent = format_get_indent (s) + 2;
1532
1533   if (fs == 0)
1534     {
1535       s = format (s, "%-20s%10s%15s%15s%15s%15s", "Name", "Type",
1536                   "HeapSize (M)", "ActiveFifos", "FreeFifos", "Address");
1537       return s;
1538     }
1539
1540   fifo_segment_info (fs, &address, &size);
1541   active_fifos = fifo_segment_num_fifos (fs);
1542   free_fifos = fifo_segment_num_free_fifos (fs);
1543
1544   s = format (s, "%-20v%10U%15llu%15u%15u%15llx", ssvm_name (&fs->ssvm),
1545               format_fifo_segment_type, fs, size >> 20ULL, active_fifos,
1546               free_fifos, address);
1547
1548   if (!verbose)
1549     return s;
1550
1551   fsh = fs->h;
1552
1553   free_chunks = fifo_segment_num_free_chunks (fs, ~0);
1554   if (free_chunks)
1555     s =
1556       format (s, "\n\n%UFree/Allocated chunks by size:\n", format_white_space,
1557               indent + 2);
1558   else
1559     s = format (s, "\n");
1560
1561   for (slice_index = 0; slice_index < fs->n_slices; slice_index++)
1562     {
1563       fss = fsh_slice_get (fsh, slice_index);
1564       for (i = 0; i < FS_CHUNK_VEC_LEN; i++)
1565         {
1566           c = fss_chunk_free_list_head (fsh, fss, i);
1567           if (c == 0 && fss->num_chunks[i] == 0)
1568             continue;
1569           count = 0;
1570           while (c)
1571             {
1572               c = fs_chunk_ptr (fsh, c->next);
1573               count++;
1574             }
1575
1576           chunk_size = fs_freelist_index_to_size (i);
1577           s = format (s, "%U%-5u kB: %u/%u\n", format_white_space, indent + 2,
1578                       chunk_size >> 10, count, fss->num_chunks[i]);
1579
1580           chunk_bytes += count * chunk_size;
1581         }
1582     }
1583
1584   fifo_hdr = free_fifos * sizeof (svm_fifo_t);
1585   est_chunk_bytes = fifo_segment_fl_chunk_bytes (fs);
1586   est_free_seg_bytes = fifo_segment_free_bytes (fs);
1587   free_seg_bytes = fifo_segment_free_bytes (fs);
1588   tracked_cached_bytes = fifo_segment_cached_bytes (fs);
1589   allocated = fifo_segment_size (fs);
1590   in_use = fifo_segment_size (fs) - est_free_seg_bytes - tracked_cached_bytes;
1591   usage = (100.0 * in_use) / allocated;
1592   mem_st = fifo_segment_get_mem_status (fs);
1593   virt = fsh_virtual_mem (fsh);
1594   reserved = fsh->n_reserved_bytes;
1595
1596   s = format (s, "\n%Useg free bytes: %U (%lu) estimated: %U (%lu) reserved:"
1597               " %U (%lu)\n", format_white_space, indent + 2,
1598               format_memory_size, free_seg_bytes, free_seg_bytes,
1599               format_memory_size, est_free_seg_bytes, est_free_seg_bytes,
1600               format_memory_size, reserved, reserved);
1601   s = format (s, "%Uchunk free bytes: %U (%lu) estimated: %U (%lu) tracked:"
1602               " %U (%lu)\n", format_white_space, indent + 2,
1603               format_memory_size, chunk_bytes, chunk_bytes,
1604               format_memory_size, est_chunk_bytes, est_chunk_bytes,
1605               format_memory_size, tracked_cached_bytes, tracked_cached_bytes);
1606   s = format (s, "%Ufifo active: %u hdr free: %u bytes: %U (%u) \n",
1607               format_white_space, indent + 2, fsh->n_active_fifos, free_fifos,
1608               format_memory_size, fifo_hdr, fifo_hdr);
1609   s = format (s, "%Usegment usage: %.2f%% (%U / %U) virt: %U status: %s\n",
1610               format_white_space, indent + 2, usage, format_memory_size,
1611               in_use, format_memory_size, allocated, format_memory_size, virt,
1612               fifo_segment_mem_status_strings[mem_st]);
1613   s = format (s, "\n");
1614
1615   return s;
1616 }
1617
1618 /*
1619  * fd.io coding-style-patch-verification: ON
1620  *
1621  * Local Variables:
1622  * eval: (c-set-style "gnu")
1623  * End:
1624  */