svm: make sure chunk search does not return tnil
[vpp.git] / src / svm / svm_fifo.c
1 /*
2  * Copyright (c) 2016-2019 Cisco and/or its affiliates.
3  * Copyright (c) 2019 Arm Limited
4  * Copyright (c) 2010-2017 Intel Corporation and/or its affiliates.
5  * Copyright (c) 2007-2009 Kip Macy kmacy@freebsd.org
6  * Inspired from DPDK rte_ring.h (SPSC only) (derived from freebsd bufring.h).
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at:
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20 #include <svm/svm_fifo.h>
21 #include <vppinfra/cpu.h>
22
23 CLIB_MARCH_FN (svm_fifo_copy_to_chunk, void, svm_fifo_t * f,
24                svm_fifo_chunk_t * c, u32 tail_idx, const u8 * src, u32 len,
25                svm_fifo_chunk_t ** last)
26 {
27   u32 n_chunk;
28
29   ASSERT (tail_idx >= c->start_byte && tail_idx < c->start_byte + c->length);
30
31   tail_idx -= c->start_byte;
32   n_chunk = c->length - tail_idx;
33   if (n_chunk <= len)
34     {
35       u32 to_copy = len;
36       clib_memcpy_fast (&c->data[tail_idx], src, n_chunk);
37       c = c->next;
38       while ((to_copy -= n_chunk))
39         {
40           n_chunk = clib_min (c->length, to_copy);
41           clib_memcpy_fast (&c->data[0], src + (len - to_copy), n_chunk);
42           c = c->length <= to_copy ? c->next : c;
43         }
44       if (*last)
45         *last = c;
46     }
47   else
48     {
49       clib_memcpy_fast (&c->data[tail_idx], src, len);
50     }
51 }
52
53 CLIB_MARCH_FN (svm_fifo_copy_from_chunk, void, svm_fifo_t * f,
54                svm_fifo_chunk_t * c, u32 head_idx, u8 * dst, u32 len,
55                svm_fifo_chunk_t ** last)
56 {
57   u32 n_chunk;
58
59   ASSERT (head_idx >= c->start_byte && head_idx < c->start_byte + c->length);
60
61   head_idx -= c->start_byte;
62   n_chunk = c->length - head_idx;
63   if (n_chunk <= len)
64     {
65       u32 to_copy = len;
66       clib_memcpy_fast (dst, &c->data[head_idx], n_chunk);
67       c = c->next;
68       while ((to_copy -= n_chunk))
69         {
70           n_chunk = clib_min (c->length, to_copy);
71           clib_memcpy_fast (dst + (len - to_copy), &c->data[0], n_chunk);
72           c = c->length <= to_copy ? c->next : c;
73         }
74       if (*last)
75         *last = c;
76     }
77   else
78     {
79       clib_memcpy_fast (dst, &c->data[head_idx], len);
80     }
81 }
82
83 #ifndef CLIB_MARCH_VARIANT
84
85 static inline void
86 svm_fifo_copy_to_chunk (svm_fifo_t * f, svm_fifo_chunk_t * c, u32 tail_idx,
87                         const u8 * src, u32 len, svm_fifo_chunk_t ** last)
88 {
89   CLIB_MARCH_FN_SELECT (svm_fifo_copy_to_chunk) (f, c, tail_idx, src, len,
90                                                  last);
91 }
92
93 static inline void
94 svm_fifo_copy_from_chunk (svm_fifo_t * f, svm_fifo_chunk_t * c, u32 head_idx,
95                           u8 * dst, u32 len, svm_fifo_chunk_t ** last)
96 {
97   CLIB_MARCH_FN_SELECT (svm_fifo_copy_from_chunk) (f, c, head_idx, dst, len,
98                                                    last);
99 }
100
101 static inline u8
102 position_lt (svm_fifo_t * f, u32 a, u32 b, u32 tail)
103 {
104   return (f_distance_to (f, a, tail) < f_distance_to (f, b, tail));
105 }
106
107 static inline u8
108 position_leq (svm_fifo_t * f, u32 a, u32 b, u32 tail)
109 {
110   return (f_distance_to (f, a, tail) <= f_distance_to (f, b, tail));
111 }
112
113 static inline u8
114 position_gt (svm_fifo_t * f, u32 a, u32 b, u32 tail)
115 {
116   return (f_distance_to (f, a, tail) > f_distance_to (f, b, tail));
117 }
118
119 static inline u32
120 position_diff (svm_fifo_t * f, u32 a, u32 b, u32 tail)
121 {
122   return f_distance_to (f, a, tail) - f_distance_to (f, b, tail);
123 }
124
125 static inline u32
126 ooo_segment_end_pos (svm_fifo_t * f, ooo_segment_t * s)
127 {
128   return (s->start + s->length) % f->size;
129 }
130
131 void
132 svm_fifo_free_ooo_data (svm_fifo_t * f)
133 {
134   pool_free (f->ooo_segments);
135 }
136
137 static inline ooo_segment_t *
138 ooo_segment_prev (svm_fifo_t * f, ooo_segment_t * s)
139 {
140   if (s->prev == OOO_SEGMENT_INVALID_INDEX)
141     return 0;
142   return pool_elt_at_index (f->ooo_segments, s->prev);
143 }
144
145 static inline ooo_segment_t *
146 ooo_segment_next (svm_fifo_t * f, ooo_segment_t * s)
147 {
148   if (s->next == OOO_SEGMENT_INVALID_INDEX)
149     return 0;
150   return pool_elt_at_index (f->ooo_segments, s->next);
151 }
152
153 static inline ooo_segment_t *
154 ooo_segment_alloc (svm_fifo_t * f, u32 start, u32 length)
155 {
156   ooo_segment_t *s;
157
158   pool_get (f->ooo_segments, s);
159
160   s->start = start;
161   s->length = length;
162   s->prev = s->next = OOO_SEGMENT_INVALID_INDEX;
163
164   return s;
165 }
166
167 static inline void
168 ooo_segment_free (svm_fifo_t * f, u32 index)
169 {
170   ooo_segment_t *cur, *prev = 0, *next = 0;
171   cur = pool_elt_at_index (f->ooo_segments, index);
172
173   if (cur->next != OOO_SEGMENT_INVALID_INDEX)
174     {
175       next = pool_elt_at_index (f->ooo_segments, cur->next);
176       next->prev = cur->prev;
177     }
178
179   if (cur->prev != OOO_SEGMENT_INVALID_INDEX)
180     {
181       prev = pool_elt_at_index (f->ooo_segments, cur->prev);
182       prev->next = cur->next;
183     }
184   else
185     {
186       f->ooos_list_head = cur->next;
187     }
188
189   pool_put (f->ooo_segments, cur);
190 }
191
192 /**
193  * Add segment to fifo's out-of-order segment list. Takes care of merging
194  * adjacent segments and removing overlapping ones.
195  */
196 static void
197 ooo_segment_add (svm_fifo_t * f, u32 offset, u32 head, u32 tail, u32 length)
198 {
199   ooo_segment_t *s, *new_s, *prev, *next, *it;
200   u32 new_index, s_end_pos, s_index;
201   u32 offset_pos, offset_end_pos;
202
203   ASSERT (offset + length <= f_distance_to (f, head, tail) || head == tail);
204
205   offset_pos = (tail + offset) % f->size;
206   offset_end_pos = (tail + offset + length) % f->size;
207
208   f->ooos_newest = OOO_SEGMENT_INVALID_INDEX;
209
210   if (f->ooos_list_head == OOO_SEGMENT_INVALID_INDEX)
211     {
212       s = ooo_segment_alloc (f, offset_pos, length);
213       f->ooos_list_head = s - f->ooo_segments;
214       f->ooos_newest = f->ooos_list_head;
215       return;
216     }
217
218   /* Find first segment that starts after new segment */
219   s = pool_elt_at_index (f->ooo_segments, f->ooos_list_head);
220   while (s->next != OOO_SEGMENT_INVALID_INDEX
221          && position_lt (f, s->start, offset_pos, tail))
222     s = pool_elt_at_index (f->ooo_segments, s->next);
223
224   /* If we have a previous and we overlap it, use it as starting point */
225   prev = ooo_segment_prev (f, s);
226   if (prev
227       && position_leq (f, offset_pos, ooo_segment_end_pos (f, prev), tail))
228     {
229       s = prev;
230       s_end_pos = ooo_segment_end_pos (f, s);
231
232       /* Since we have previous, offset start position cannot be smaller
233        * than prev->start. Check tail */
234       ASSERT (position_lt (f, s->start, offset_pos, tail));
235       goto check_tail;
236     }
237
238   s_index = s - f->ooo_segments;
239   s_end_pos = ooo_segment_end_pos (f, s);
240
241   /* No overlap, add before current segment */
242   if (position_lt (f, offset_end_pos, s->start, tail))
243     {
244       new_s = ooo_segment_alloc (f, offset_pos, length);
245       new_index = new_s - f->ooo_segments;
246
247       /* Pool might've moved, get segment again */
248       s = pool_elt_at_index (f->ooo_segments, s_index);
249       if (s->prev != OOO_SEGMENT_INVALID_INDEX)
250         {
251           new_s->prev = s->prev;
252           prev = pool_elt_at_index (f->ooo_segments, new_s->prev);
253           prev->next = new_index;
254         }
255       else
256         {
257           /* New head */
258           f->ooos_list_head = new_index;
259         }
260
261       new_s->next = s_index;
262       s->prev = new_index;
263       f->ooos_newest = new_index;
264       return;
265     }
266   /* No overlap, add after current segment */
267   else if (position_gt (f, offset_pos, s_end_pos, tail))
268     {
269       new_s = ooo_segment_alloc (f, offset_pos, length);
270       new_index = new_s - f->ooo_segments;
271
272       /* Pool might've moved, get segment again */
273       s = pool_elt_at_index (f->ooo_segments, s_index);
274
275       /* Needs to be last */
276       ASSERT (s->next == OOO_SEGMENT_INVALID_INDEX);
277
278       new_s->prev = s_index;
279       s->next = new_index;
280       f->ooos_newest = new_index;
281
282       return;
283     }
284
285   /*
286    * Merge needed
287    */
288
289   /* Merge at head */
290   if (position_lt (f, offset_pos, s->start, tail))
291     {
292       s->start = offset_pos;
293       s->length = position_diff (f, s_end_pos, s->start, tail);
294       f->ooos_newest = s - f->ooo_segments;
295     }
296
297 check_tail:
298
299   /* Overlapping tail */
300   if (position_gt (f, offset_end_pos, s_end_pos, tail))
301     {
302       s->length = position_diff (f, offset_end_pos, s->start, tail);
303
304       /* Remove the completely overlapped segments in the tail */
305       it = ooo_segment_next (f, s);
306       while (it && position_leq (f, ooo_segment_end_pos (f, it),
307                                  offset_end_pos, tail))
308         {
309           next = ooo_segment_next (f, it);
310           ooo_segment_free (f, it - f->ooo_segments);
311           it = next;
312         }
313
314       /* If partial overlap with last, merge */
315       if (it && position_leq (f, it->start, offset_end_pos, tail))
316         {
317           s->length = position_diff (f, ooo_segment_end_pos (f, it),
318                                      s->start, tail);
319           ooo_segment_free (f, it - f->ooo_segments);
320         }
321       f->ooos_newest = s - f->ooo_segments;
322     }
323 }
324
325 /**
326  * Removes segments that can now be enqueued because the fifo's tail has
327  * advanced. Returns the number of bytes added to tail.
328  */
329 static int
330 ooo_segment_try_collect (svm_fifo_t * f, u32 n_bytes_enqueued, u32 * tail)
331 {
332   u32 s_index, bytes = 0;
333   ooo_segment_t *s;
334   i32 diff;
335
336   s = pool_elt_at_index (f->ooo_segments, f->ooos_list_head);
337   diff = f_distance_from (f, s->start, *tail);
338
339   ASSERT (diff != n_bytes_enqueued);
340
341   if (diff > n_bytes_enqueued)
342     return 0;
343
344   /* If last tail update overlaps one/multiple ooo segments, remove them */
345   while (0 <= diff && diff < n_bytes_enqueued)
346     {
347       s_index = s - f->ooo_segments;
348
349       /* Segment end is beyond the tail. Advance tail and remove segment */
350       if (s->length > diff)
351         {
352           bytes = s->length - diff;
353           *tail = (*tail + bytes) % f->size;
354           ooo_segment_free (f, s_index);
355           break;
356         }
357
358       /* If we have next go on */
359       if (s->next != OOO_SEGMENT_INVALID_INDEX)
360         {
361           s = pool_elt_at_index (f->ooo_segments, s->next);
362           diff = f_distance_from (f, s->start, *tail);
363           ooo_segment_free (f, s_index);
364         }
365       /* End of search */
366       else
367         {
368           ooo_segment_free (f, s_index);
369           break;
370         }
371     }
372
373   ASSERT (bytes <= f->nitems);
374   return bytes;
375 }
376
377 static ooo_segment_t *
378 ooo_segment_last (svm_fifo_t * f)
379 {
380   ooo_segment_t *s;
381
382   if (f->ooos_list_head == OOO_SEGMENT_INVALID_INDEX)
383     return 0;
384
385   s = svm_fifo_first_ooo_segment (f);
386   while (s->next != OOO_SEGMENT_INVALID_INDEX)
387     s = pool_elt_at_index (f->ooo_segments, s->next);
388   return s;
389 }
390
391 void
392 svm_fifo_init (svm_fifo_t * f, u32 size)
393 {
394   f->size = size;
395   /*
396    * usable size of the fifo set to rounded_data_size - 1
397    * to differentiate between free fifo and empty fifo.
398    */
399   f->nitems = f->size - 1;
400   f->ooos_list_head = OOO_SEGMENT_INVALID_INDEX;
401   f->segment_index = SVM_FIFO_INVALID_INDEX;
402   f->refcnt = 1;
403   f->flags = 0;
404   f->head_chunk = f->tail_chunk = f->ooo_enq = f->ooo_deq = f->start_chunk;
405 }
406
407 /**
408  * Creates a fifo in the current heap. Fails vs blow up the process
409  */
410 svm_fifo_t *
411 svm_fifo_create (u32 data_size_in_bytes)
412 {
413   u32 rounded_data_size;
414   svm_fifo_chunk_t *c;
415   svm_fifo_t *f;
416
417   f = clib_mem_alloc_aligned_or_null (sizeof (*f), CLIB_CACHE_LINE_BYTES);
418   if (f == 0)
419     return 0;
420
421   clib_memset (f, 0, sizeof (*f));
422
423   /* always round fifo data size to the next highest power-of-two */
424   rounded_data_size = (1 << (max_log2 (data_size_in_bytes)));
425   c = clib_mem_alloc_aligned_or_null (sizeof (*c) + rounded_data_size,
426                                       CLIB_CACHE_LINE_BYTES);
427   if (!c)
428     {
429       clib_mem_free (f);
430       return 0;
431     }
432
433   c->next = c;
434   c->start_byte = 0;
435   c->length = data_size_in_bytes;
436   f->start_chunk = f->end_chunk = c;
437
438   svm_fifo_init (f, data_size_in_bytes);
439   return f;
440 }
441
442 /**
443  * Creates a fifo chunk in the current heap
444  */
445 svm_fifo_chunk_t *
446 svm_fifo_chunk_alloc (u32 size)
447 {
448   svm_fifo_chunk_t *c;
449   u32 rounded_size;
450
451   /* round chunk size to the next highest power-of-two */
452   rounded_size = (1 << (max_log2 (size)));
453   c = clib_mem_alloc_aligned_or_null (sizeof (*c) + rounded_size,
454                                       CLIB_CACHE_LINE_BYTES);
455   if (c == 0)
456     return 0;
457
458   clib_memset (c, 0, sizeof (*c));
459   c->length = rounded_size;
460   return c;
461 }
462
463 static inline u8
464 svm_fifo_chunk_includes_pos (svm_fifo_chunk_t * c, u32 pos)
465 {
466   return (pos >= c->start_byte && pos < c->start_byte + c->length);
467 }
468
469 /**
470  * Find chunk for given byte position
471  *
472  * @param f     fifo
473  * @param pos   normalized position in fifo
474  *
475  * @return chunk that includes given position or 0
476  */
477 static svm_fifo_chunk_t *
478 svm_fifo_find_chunk (svm_fifo_t * f, u32 pos)
479 {
480   rb_tree_t *rt = &f->chunk_lookup;
481   rb_node_t *cur, *prev;
482   svm_fifo_chunk_t *c;
483
484   cur = rb_node (rt, rt->root);
485   while (pos != cur->key)
486     {
487       prev = cur;
488       if (pos < cur->key)
489         cur = rb_node_left (rt, cur);
490       else
491         cur = rb_node_right (rt, cur);
492
493       if (rb_node_is_tnil (rt, cur))
494         {
495           /* Hit tnil as a left child. Find predecessor */
496           if (pos < prev->key)
497             {
498               cur = rb_tree_predecessor (rt, prev);
499               if (rb_node_is_tnil (rt, cur))
500                 return 0;
501               c = uword_to_pointer (cur->opaque, svm_fifo_chunk_t *);
502               if (svm_fifo_chunk_includes_pos (c, pos))
503                 return c;
504               return 0;
505             }
506           /* Hit tnil as a right child. Check if this is the one */
507           c = uword_to_pointer (prev->opaque, svm_fifo_chunk_t *);
508           if (svm_fifo_chunk_includes_pos (c, pos))
509             return c;
510
511           return 0;
512         }
513     }
514
515   if (!rb_node_is_tnil (rt, cur))
516     return uword_to_pointer (cur->opaque, svm_fifo_chunk_t *);
517   return 0;
518 }
519
520 static inline void
521 svm_fifo_grow (svm_fifo_t * f, svm_fifo_chunk_t * c)
522 {
523   svm_fifo_chunk_t *prev;
524   u32 add_bytes = 0;
525
526   if (!c)
527     return;
528
529   f->end_chunk->next = c;
530   while (c)
531     {
532       add_bytes += c->length;
533       prev = c;
534       c = c->next;
535     }
536   f->end_chunk = prev;
537   prev->next = f->start_chunk;
538   f->size += add_bytes;
539   f->nitems = f->size - 1;
540   f->new_chunks = 0;
541 }
542
543 static void
544 svm_fifo_try_grow (svm_fifo_t * f, u32 new_head)
545 {
546   if (new_head > f->tail)
547     return;
548
549   svm_fifo_grow (f, f->new_chunks);
550   f->flags &= ~SVM_FIFO_F_GROW;
551 }
552
553 void
554 svm_fifo_add_chunk (svm_fifo_t * f, svm_fifo_chunk_t * c)
555 {
556   svm_fifo_chunk_t *cur, *prev;
557
558   /* Initialize rbtree if needed and add default chunk to it. Expectation is
559    * that this is called with the heap where the rbtree's pool is pushed. */
560   if (!(f->flags & SVM_FIFO_F_MULTI_CHUNK))
561     {
562       rb_tree_init (&f->chunk_lookup);
563       rb_tree_add2 (&f->chunk_lookup, 0, pointer_to_uword (f->start_chunk));
564       f->flags |= SVM_FIFO_F_MULTI_CHUNK;
565     }
566
567   /* Initialize chunks and add to lookup rbtree */
568   cur = c;
569   if (f->new_chunks)
570     {
571       prev = f->new_chunks;
572       while (prev->next)
573         prev = prev->next;
574       prev->next = c;
575     }
576   else
577     prev = f->end_chunk;
578
579   while (cur)
580     {
581       cur->start_byte = prev->start_byte + prev->length;
582       rb_tree_add2 (&f->chunk_lookup, cur->start_byte,
583                     pointer_to_uword (cur));
584       prev = cur;
585       cur = cur->next;
586     }
587
588   /* If fifo is not wrapped, update the size now */
589   if (!svm_fifo_is_wrapped (f))
590     {
591       ASSERT (!f->new_chunks);
592       svm_fifo_grow (f, c);
593       return;
594     }
595
596   /* Postpone size update */
597   if (!f->new_chunks)
598     {
599       f->new_chunks = c;
600       f->flags |= SVM_FIFO_F_GROW;
601     }
602 }
603
604 /**
605  * Removes chunks that are after fifo end byte
606  */
607 svm_fifo_chunk_t *
608 svm_fifo_collect_chunks (svm_fifo_t * f)
609 {
610   svm_fifo_chunk_t *list, *cur;
611
612   f->flags &= ~SVM_FIFO_F_COLLECT_CHUNKS;
613
614   list = f->new_chunks;
615   f->new_chunks = 0;
616   cur = list;
617   while (cur)
618     {
619       rb_tree_del (&f->chunk_lookup, cur->start_byte);
620       cur = cur->next;
621     }
622
623   return list;
624 }
625
626 void
627 svm_fifo_try_shrink (svm_fifo_t * f, u32 head, u32 tail)
628 {
629   u32 len_to_shrink = 0, tail_pos, len;
630   svm_fifo_chunk_t *cur, *prev, *next, *start;
631
632   tail_pos = tail;
633   if (f->ooos_list_head != OOO_SEGMENT_INVALID_INDEX)
634     {
635       ooo_segment_t *last = ooo_segment_last (f);
636       tail_pos = ooo_segment_end_pos (f, last);
637     }
638
639   if (f->size_decrement)
640     {
641       /* Figure out available free space considering that there may be
642        * ooo segments */
643       len = clib_min (f->size_decrement, f_free_count (f, head, tail_pos));
644       f->nitems -= len;
645       f->size_decrement -= len;
646     }
647
648   /* Remove tail chunks if the following hold:
649    * - not wrapped
650    * - last used byte less than start of last chunk
651    */
652   if (tail_pos >= head && tail_pos <= f->end_chunk->start_byte)
653     {
654       /* Lookup the last position not to be removed. Since size still needs
655        * to be nitems + 1, nitems must fall within the usable space */
656       tail_pos = tail_pos > 0 ? tail_pos - 1 : tail_pos;
657       prev = svm_fifo_find_chunk (f, clib_max (f->nitems, tail_pos));
658       next = prev->next;
659       while (next != f->start_chunk)
660         {
661           cur = next;
662           next = cur->next;
663           len_to_shrink += cur->length;
664         }
665       if (len_to_shrink)
666         {
667           f->size -= len_to_shrink;
668           start = prev->next;
669           prev->next = f->start_chunk;
670           f->end_chunk = prev;
671           cur->next = f->new_chunks;
672           f->new_chunks = start;
673         }
674     }
675
676   if (!f->size_decrement && f->size == f->nitems + 1)
677     {
678       f->flags &= ~SVM_FIFO_F_SHRINK;
679       f->flags |= SVM_FIFO_F_COLLECT_CHUNKS;
680       if (f->start_chunk == f->start_chunk->next)
681         f->flags &= ~SVM_FIFO_F_MULTI_CHUNK;
682     }
683 }
684
685 /**
686  * Request to reduce fifo size by amount of bytes
687  */
688 int
689 svm_fifo_reduce_size (svm_fifo_t * f, u32 len, u8 try_shrink)
690 {
691   svm_fifo_chunk_t *cur;
692   u32 actual_len = 0;
693
694   /* Abort if trying to reduce by more than fifo size or if
695    * fifo is undergoing resizing already */
696   if (len >= f->size || f->size > f->nitems + 1
697       || (f->flags & SVM_FIFO_F_SHRINK) || (f->flags & SVM_FIFO_F_GROW))
698     return 0;
699
700   /* last chunk that will not be removed */
701   cur = svm_fifo_find_chunk (f, f->nitems - len);
702
703   /* sum length of chunks that will be removed */
704   cur = cur->next;
705   while (cur != f->start_chunk)
706     {
707       actual_len += cur->length;
708       cur = cur->next;
709     }
710
711   ASSERT (actual_len <= len);
712   if (!actual_len)
713     return 0;
714
715   f->size_decrement = actual_len;
716   f->flags |= SVM_FIFO_F_SHRINK;
717
718   if (try_shrink)
719     {
720       u32 head, tail;
721       f_load_head_tail_prod (f, &head, &tail);
722       svm_fifo_try_shrink (f, head, tail);
723     }
724
725   return actual_len;
726 }
727
728 void
729 svm_fifo_free_chunk_lookup (svm_fifo_t * f)
730 {
731   rb_tree_free_nodes (&f->chunk_lookup);
732 }
733
734 void
735 svm_fifo_free (svm_fifo_t * f)
736 {
737   ASSERT (f->refcnt > 0);
738
739   if (--f->refcnt == 0)
740     {
741       /* ooo data is not allocated on segment heap */
742       svm_fifo_free_chunk_lookup (f);
743       clib_mem_free (f);
744     }
745 }
746
747 void
748 svm_fifo_overwrite_head (svm_fifo_t * f, u8 * src, u32 len)
749 {
750   u32 n_chunk;
751   u32 head, tail, head_idx;
752   svm_fifo_chunk_t *c;
753
754   ASSERT (len <= f->nitems);
755
756   f_load_head_tail_cons (f, &head, &tail);
757   c = f->head_chunk;
758   head_idx = head - c->start_byte;
759   n_chunk = c->length - head_idx;
760   if (len <= n_chunk)
761     clib_memcpy_fast (&c->data[head_idx], src, len);
762   else
763     {
764       clib_memcpy_fast (&c->data[head_idx], src, n_chunk);
765       clib_memcpy_fast (&c->next->data[0], src + n_chunk, len - n_chunk);
766     }
767 }
768
769 int
770 svm_fifo_enqueue (svm_fifo_t * f, u32 len, const u8 * src)
771 {
772   u32 tail, head, free_count;
773
774   f_load_head_tail_prod (f, &head, &tail);
775
776   /* free space in fifo can only increase during enqueue: SPSC */
777   free_count = f_free_count (f, head, tail);
778
779   f->ooos_newest = OOO_SEGMENT_INVALID_INDEX;
780
781   if (PREDICT_FALSE (free_count == 0))
782     return SVM_FIFO_EFULL;
783
784   /* number of bytes we're going to copy */
785   len = clib_min (free_count, len);
786   svm_fifo_copy_to_chunk (f, f->tail_chunk, tail, src, len, &f->tail_chunk);
787   tail = (tail + len) % f->size;
788
789   svm_fifo_trace_add (f, head, len, 2);
790
791   /* collect out-of-order segments */
792   if (PREDICT_FALSE (f->ooos_list_head != OOO_SEGMENT_INVALID_INDEX))
793     len += ooo_segment_try_collect (f, len, &tail);
794
795   /* store-rel: producer owned index (paired with load-acq in consumer) */
796   clib_atomic_store_rel_n (&f->tail, tail);
797
798   return len;
799 }
800
801 /**
802  * Enqueue a future segment.
803  *
804  * Two choices: either copies the entire segment, or copies nothing
805  * Returns 0 of the entire segment was copied
806  * Returns -1 if none of the segment was copied due to lack of space
807  */
808 int
809 svm_fifo_enqueue_with_offset (svm_fifo_t * f, u32 offset, u32 len, u8 * src)
810 {
811   u32 tail, head, free_count, tail_idx;
812
813   f_load_head_tail_prod (f, &head, &tail);
814
815   if (PREDICT_FALSE (f->flags & SVM_FIFO_F_SHRINK))
816     svm_fifo_try_shrink (f, head, tail);
817
818   /* free space in fifo can only increase during enqueue: SPSC */
819   free_count = f_free_count (f, head, tail);
820
821   /* will this request fit? */
822   if ((len + offset) > free_count)
823     return SVM_FIFO_EFULL;
824
825   f->ooos_newest = OOO_SEGMENT_INVALID_INDEX;
826   svm_fifo_trace_add (f, offset, len, 1);
827   ooo_segment_add (f, offset, head, tail, len);
828   tail_idx = (tail + offset) % f->size;
829
830   if (!svm_fifo_chunk_includes_pos (f->ooo_enq, tail_idx))
831     f->ooo_enq = svm_fifo_find_chunk (f, tail_idx);
832
833   svm_fifo_copy_to_chunk (f, f->ooo_enq, tail_idx, src, len, &f->ooo_enq);
834
835   return 0;
836 }
837
838 /**
839  * Advance tail
840  */
841 void
842 svm_fifo_enqueue_nocopy (svm_fifo_t * f, u32 len)
843 {
844   u32 tail;
845
846   ASSERT (len <= svm_fifo_max_enqueue_prod (f));
847   /* load-relaxed: producer owned index */
848   tail = f->tail;
849   tail = (tail + len) % f->size;
850   /* store-rel: producer owned index (paired with load-acq in consumer) */
851   clib_atomic_store_rel_n (&f->tail, tail);
852 }
853
854 int
855 svm_fifo_dequeue (svm_fifo_t * f, u32 len, u8 * dst)
856 {
857   u32 tail, head, cursize;
858
859   f_load_head_tail_cons (f, &head, &tail);
860
861   /* current size of fifo can only increase during dequeue: SPSC */
862   cursize = f_cursize (f, head, tail);
863
864   if (PREDICT_FALSE (cursize == 0))
865     return SVM_FIFO_EEMPTY;
866
867   len = clib_min (cursize, len);
868   svm_fifo_copy_from_chunk (f, f->head_chunk, head, dst, len, &f->head_chunk);
869   head = (head + len) % f->size;
870
871   if (PREDICT_FALSE (f->flags & SVM_FIFO_F_GROW))
872     svm_fifo_try_grow (f, head);
873
874   /* store-rel: consumer owned index (paired with load-acq in producer) */
875   clib_atomic_store_rel_n (&f->head, head);
876
877   return len;
878 }
879
880 int
881 svm_fifo_peek (svm_fifo_t * f, u32 offset, u32 len, u8 * dst)
882 {
883   u32 tail, head, cursize, head_idx;
884
885   f_load_head_tail_cons (f, &head, &tail);
886
887   /* current size of fifo can only increase during peek: SPSC */
888   cursize = f_cursize (f, head, tail);
889
890   if (PREDICT_FALSE (cursize < offset))
891     return SVM_FIFO_EEMPTY;
892
893   len = clib_min (cursize - offset, len);
894   head_idx = (head + offset) % f->size;
895   if (!svm_fifo_chunk_includes_pos (f->ooo_deq, head_idx))
896     f->ooo_deq = svm_fifo_find_chunk (f, head_idx);
897
898   svm_fifo_copy_from_chunk (f, f->ooo_deq, head_idx, dst, len, &f->ooo_deq);
899   return len;
900 }
901
902 int
903 svm_fifo_dequeue_drop (svm_fifo_t * f, u32 len)
904 {
905   u32 total_drop_bytes, tail, head, cursize;
906
907   f_load_head_tail_cons (f, &head, &tail);
908
909   /* number of bytes available */
910   cursize = f_cursize (f, head, tail);
911   if (PREDICT_FALSE (cursize == 0))
912     return SVM_FIFO_EEMPTY;
913
914   /* number of bytes we're going to drop */
915   total_drop_bytes = clib_min (cursize, len);
916
917   svm_fifo_trace_add (f, tail, total_drop_bytes, 3);
918
919   /* move head */
920   head = (head + total_drop_bytes) % f->size;
921
922   /* store-rel: consumer owned index (paired with load-acq in producer) */
923   clib_atomic_store_rel_n (&f->head, head);
924
925   return total_drop_bytes;
926 }
927
928 void
929 svm_fifo_dequeue_drop_all (svm_fifo_t * f)
930 {
931   /* consumer foreign index */
932   u32 tail = clib_atomic_load_acq_n (&f->tail);
933   /* store-rel: consumer owned index (paired with load-acq in producer) */
934   clib_atomic_store_rel_n (&f->head, tail);
935 }
936
937 int
938 svm_fifo_segments (svm_fifo_t * f, svm_fifo_seg_t * fs)
939 {
940   u32 cursize, head, tail, head_idx;
941
942   f_load_head_tail_cons (f, &head, &tail);
943
944   /* consumer function, cursize can only increase while we're working */
945   cursize = f_cursize (f, head, tail);
946
947   if (PREDICT_FALSE (cursize == 0))
948     return SVM_FIFO_EEMPTY;
949
950   head_idx = head;
951
952   if (tail < head)
953     {
954       fs[0].len = f->size - head_idx;
955       fs[0].data = f->head_chunk->data + head_idx;
956       fs[1].len = cursize - fs[0].len;
957       fs[1].data = f->head_chunk->data;
958     }
959   else
960     {
961       fs[0].len = cursize;
962       fs[0].data = f->head_chunk->data + head_idx;
963       fs[1].len = 0;
964       fs[1].data = 0;
965     }
966   return cursize;
967 }
968
969 void
970 svm_fifo_segments_free (svm_fifo_t * f, svm_fifo_seg_t * fs)
971 {
972   u32 head;
973
974   /* consumer owned index */
975   head = f->head;
976
977   ASSERT (fs[0].data == f->head_chunk->data + head);
978   head = (head + fs[0].len + fs[1].len) % f->size;
979   /* store-rel: consumer owned index (paired with load-acq in producer) */
980   clib_atomic_store_rel_n (&f->head, head);
981 }
982
983 /**
984  * Clones fifo
985  *
986  * Assumptions:
987  * - no prod and cons are accessing either dest or src fifo
988  * - fifo is not multi chunk
989  */
990 void
991 svm_fifo_clone (svm_fifo_t * df, svm_fifo_t * sf)
992 {
993   u32 head, tail;
994   clib_memcpy_fast (df->head_chunk->data, sf->head_chunk->data, sf->size);
995
996   f_load_head_tail_all_acq (sf, &head, &tail);
997   clib_atomic_store_rel_n (&df->head, head);
998   clib_atomic_store_rel_n (&df->tail, tail);
999 }
1000
1001 u32
1002 svm_fifo_n_ooo_segments (svm_fifo_t * f)
1003 {
1004   return pool_elts (f->ooo_segments);
1005 }
1006
1007 ooo_segment_t *
1008 svm_fifo_first_ooo_segment (svm_fifo_t * f)
1009 {
1010   return pool_elt_at_index (f->ooo_segments, f->ooos_list_head);
1011 }
1012
1013 /**
1014  * Set fifo pointers to requested offset
1015  */
1016 void
1017 svm_fifo_init_pointers (svm_fifo_t * f, u32 head, u32 tail)
1018 {
1019   head = head % f->size;
1020   tail = tail % f->size;
1021   clib_atomic_store_rel_n (&f->head, head);
1022   clib_atomic_store_rel_n (&f->tail, tail);
1023   if (f->flags & SVM_FIFO_F_MULTI_CHUNK)
1024     {
1025       svm_fifo_chunk_t *c;
1026       c = svm_fifo_find_chunk (f, head);
1027       ASSERT (c != 0);
1028       f->head_chunk = f->ooo_deq = c;
1029       c = svm_fifo_find_chunk (f, tail);
1030       ASSERT (c != 0);
1031       f->tail_chunk = f->ooo_enq = c;
1032     }
1033 }
1034
1035 void
1036 svm_fifo_add_subscriber (svm_fifo_t * f, u8 subscriber)
1037 {
1038   if (f->n_subscribers >= SVM_FIFO_MAX_EVT_SUBSCRIBERS)
1039     return;
1040   f->subscribers[f->n_subscribers++] = subscriber;
1041 }
1042
1043 void
1044 svm_fifo_del_subscriber (svm_fifo_t * f, u8 subscriber)
1045 {
1046   int i;
1047
1048   for (i = 0; i < f->n_subscribers; i++)
1049     {
1050       if (f->subscribers[i] != subscriber)
1051         continue;
1052       f->subscribers[i] = f->subscribers[f->n_subscribers - 1];
1053       f->n_subscribers--;
1054       break;
1055     }
1056 }
1057
1058 u8 *
1059 format_ooo_segment (u8 * s, va_list * args)
1060 {
1061   svm_fifo_t *f = va_arg (*args, svm_fifo_t *);
1062   ooo_segment_t *seg = va_arg (*args, ooo_segment_t *);
1063   u32 normalized_start = (seg->start + f->nitems - f->tail) % f->size;
1064   s = format (s, "[%u, %u], len %u, next %d, prev %d", normalized_start,
1065               (normalized_start + seg->length) % f->size, seg->length,
1066               seg->next, seg->prev);
1067   return s;
1068 }
1069
1070 u8 *
1071 svm_fifo_dump_trace (u8 * s, svm_fifo_t * f)
1072 {
1073 #if SVM_FIFO_TRACE
1074   svm_fifo_trace_elem_t *seg = 0;
1075   int i = 0;
1076
1077   if (f->trace)
1078     {
1079       vec_foreach (seg, f->trace)
1080       {
1081         s = format (s, "{%u, %u, %u}, ", seg->offset, seg->len, seg->action);
1082         i++;
1083         if (i % 5 == 0)
1084           s = format (s, "\n");
1085       }
1086       s = format (s, "\n");
1087     }
1088   return s;
1089 #else
1090   return 0;
1091 #endif
1092 }
1093
1094 u8 *
1095 svm_fifo_replay (u8 * s, svm_fifo_t * f, u8 no_read, u8 verbose)
1096 {
1097   int i, trace_len;
1098   u8 *data = 0;
1099   svm_fifo_trace_elem_t *trace;
1100   u32 offset;
1101   svm_fifo_t *dummy_fifo;
1102
1103   if (!f)
1104     return s;
1105
1106 #if SVM_FIFO_TRACE
1107   trace = f->trace;
1108   trace_len = vec_len (trace);
1109 #else
1110   trace = 0;
1111   trace_len = 0;
1112 #endif
1113
1114   dummy_fifo = svm_fifo_create (f->size);
1115   clib_memset (f->head_chunk->data, 0xFF, f->nitems);
1116   vec_validate (data, f->nitems);
1117   for (i = 0; i < vec_len (data); i++)
1118     data[i] = i;
1119
1120   for (i = 0; i < trace_len; i++)
1121     {
1122       offset = trace[i].offset;
1123       if (trace[i].action == 1)
1124         {
1125           if (verbose)
1126             s = format (s, "adding [%u, %u]:", trace[i].offset,
1127                         (trace[i].offset + trace[i].len) % dummy_fifo->size);
1128           svm_fifo_enqueue_with_offset (dummy_fifo, trace[i].offset,
1129                                         trace[i].len, &data[offset]);
1130         }
1131       else if (trace[i].action == 2)
1132         {
1133           if (verbose)
1134             s = format (s, "adding [%u, %u]:", 0, trace[i].len);
1135           svm_fifo_enqueue (dummy_fifo, trace[i].len, &data[offset]);
1136         }
1137       else if (!no_read)
1138         {
1139           if (verbose)
1140             s = format (s, "read: %u", trace[i].len);
1141           svm_fifo_dequeue_drop (dummy_fifo, trace[i].len);
1142         }
1143       if (verbose)
1144         s = format (s, "%U", format_svm_fifo, dummy_fifo, 1);
1145     }
1146
1147   s = format (s, "result: %U", format_svm_fifo, dummy_fifo, 1);
1148
1149   return s;
1150 }
1151
1152 u8 *
1153 format_ooo_list (u8 * s, va_list * args)
1154 {
1155   svm_fifo_t *f = va_arg (*args, svm_fifo_t *);
1156   u32 indent = va_arg (*args, u32);
1157   u32 ooo_segment_index = f->ooos_list_head;
1158   ooo_segment_t *seg;
1159
1160   while (ooo_segment_index != OOO_SEGMENT_INVALID_INDEX)
1161     {
1162       seg = pool_elt_at_index (f->ooo_segments, ooo_segment_index);
1163       s = format (s, "%U%U\n", format_white_space, indent, format_ooo_segment,
1164                   f, seg);
1165       ooo_segment_index = seg->next;
1166     }
1167
1168   return s;
1169 }
1170
1171 u8 *
1172 format_svm_fifo (u8 * s, va_list * args)
1173 {
1174   svm_fifo_t *f = va_arg (*args, svm_fifo_t *);
1175   int verbose = va_arg (*args, int);
1176   u32 indent;
1177
1178   if (!s)
1179     return s;
1180
1181   indent = format_get_indent (s);
1182   s = format (s, "cursize %u nitems %u has_event %d\n",
1183               svm_fifo_max_dequeue (f), f->nitems, f->has_event);
1184   s = format (s, "%Uhead %u tail %u segment manager %u\n", format_white_space,
1185               indent, (f->head % f->size), (f->tail % f->size),
1186               f->segment_manager);
1187
1188   if (verbose > 1)
1189     s = format (s, "%Uvpp session %d thread %d app session %d thread %d\n",
1190                 format_white_space, indent, f->master_session_index,
1191                 f->master_thread_index, f->client_session_index,
1192                 f->client_thread_index);
1193
1194   if (verbose)
1195     {
1196       s = format (s, "%Uooo pool %d active elts newest %u\n",
1197                   format_white_space, indent, pool_elts (f->ooo_segments),
1198                   f->ooos_newest);
1199       if (svm_fifo_has_ooo_data (f))
1200         s = format (s, " %U", format_ooo_list, f, indent, verbose);
1201     }
1202   return s;
1203 }
1204
1205 #endif
1206 /*
1207  * fd.io coding-style-patch-verification: ON
1208  *
1209  * Local Variables:
1210  * eval: (c-set-style "gnu")
1211  * End:
1212  */