ring: add optional yield to avoid spin forever
[dpdk.git] / lib / librte_ring / rte_ring.h
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 /*
35  * Derived from FreeBSD's bufring.h
36  *
37  **************************************************************************
38  *
39  * Copyright (c) 2007-2009 Kip Macy kmacy@freebsd.org
40  * All rights reserved.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions are met:
44  *
45  * 1. Redistributions of source code must retain the above copyright notice,
46  *    this list of conditions and the following disclaimer.
47  *
48  * 2. The name of Kip Macy nor the names of other
49  *    contributors may be used to endorse or promote products derived from
50  *    this software without specific prior written permission.
51  *
52  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
53  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
55  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
56  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
57  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
58  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
59  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
60  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
61  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
62  * POSSIBILITY OF SUCH DAMAGE.
63  *
64  ***************************************************************************/
65
66 #ifndef _RTE_RING_H_
67 #define _RTE_RING_H_
68
69 /**
70  * @file
71  * RTE Ring
72  *
73  * The Ring Manager is a fixed-size queue, implemented as a table of
74  * pointers. Head and tail pointers are modified atomically, allowing
75  * concurrent access to it. It has the following features:
76  *
77  * - FIFO (First In First Out)
78  * - Maximum size is fixed; the pointers are stored in a table.
79  * - Lockless implementation.
80  * - Multi- or single-consumer dequeue.
81  * - Multi- or single-producer enqueue.
82  * - Bulk dequeue.
83  * - Bulk enqueue.
84  *
85  * Note: the ring implementation is not preemptable. A lcore must not
86  * be interrupted by another task that uses the same ring.
87  *
88  */
89
90 #ifdef __cplusplus
91 extern "C" {
92 #endif
93
94 #include <stdio.h>
95 #include <stdint.h>
96 #include <sys/queue.h>
97 #include <errno.h>
98 #include <rte_common.h>
99 #include <rte_memory.h>
100 #include <rte_lcore.h>
101 #include <rte_atomic.h>
102 #include <rte_branch_prediction.h>
103
104 enum rte_ring_queue_behavior {
105         RTE_RING_QUEUE_FIXED = 0, /* Enq/Deq a fixed number of items from a ring */
106         RTE_RING_QUEUE_VARIABLE   /* Enq/Deq as many items a possible from ring */
107 };
108
109 #ifdef RTE_LIBRTE_RING_DEBUG
110 /**
111  * A structure that stores the ring statistics (per-lcore).
112  */
113 struct rte_ring_debug_stats {
114         uint64_t enq_success_bulk; /**< Successful enqueues number. */
115         uint64_t enq_success_objs; /**< Objects successfully enqueued. */
116         uint64_t enq_quota_bulk;   /**< Successful enqueues above watermark. */
117         uint64_t enq_quota_objs;   /**< Objects enqueued above watermark. */
118         uint64_t enq_fail_bulk;    /**< Failed enqueues number. */
119         uint64_t enq_fail_objs;    /**< Objects that failed to be enqueued. */
120         uint64_t deq_success_bulk; /**< Successful dequeues number. */
121         uint64_t deq_success_objs; /**< Objects successfully dequeued. */
122         uint64_t deq_fail_bulk;    /**< Failed dequeues number. */
123         uint64_t deq_fail_objs;    /**< Objects that failed to be dequeued. */
124 } __rte_cache_aligned;
125 #endif
126
127 #define RTE_RING_NAMESIZE 32 /**< The maximum length of a ring name. */
128 #define RTE_RING_MZ_PREFIX "RG_"
129
130 #ifndef RTE_RING_PAUSE_REP_COUNT
131 #define RTE_RING_PAUSE_REP_COUNT 0 /**< Yield after pause num of times, no yield
132                                     *   if RTE_RING_PAUSE_REP not defined. */
133 #endif
134
135 /**
136  * An RTE ring structure.
137  *
138  * The producer and the consumer have a head and a tail index. The particularity
139  * of these index is that they are not between 0 and size(ring). These indexes
140  * are between 0 and 2^32, and we mask their value when we access the ring[]
141  * field. Thanks to this assumption, we can do subtractions between 2 index
142  * values in a modulo-32bit base: that's why the overflow of the indexes is not
143  * a problem.
144  */
145 struct rte_ring {
146         char name[RTE_RING_NAMESIZE];    /**< Name of the ring. */
147         int flags;                       /**< Flags supplied at creation. */
148
149         /** Ring producer status. */
150         struct prod {
151                 uint32_t watermark;      /**< Maximum items before EDQUOT. */
152                 uint32_t sp_enqueue;     /**< True, if single producer. */
153                 uint32_t size;           /**< Size of ring. */
154                 uint32_t mask;           /**< Mask (size-1) of ring. */
155                 volatile uint32_t head;  /**< Producer head. */
156                 volatile uint32_t tail;  /**< Producer tail. */
157         } prod __rte_cache_aligned;
158
159         /** Ring consumer status. */
160         struct cons {
161                 uint32_t sc_dequeue;     /**< True, if single consumer. */
162                 uint32_t size;           /**< Size of the ring. */
163                 uint32_t mask;           /**< Mask (size-1) of ring. */
164                 volatile uint32_t head;  /**< Consumer head. */
165                 volatile uint32_t tail;  /**< Consumer tail. */
166 #ifdef RTE_RING_SPLIT_PROD_CONS
167         } cons __rte_cache_aligned;
168 #else
169         } cons;
170 #endif
171
172 #ifdef RTE_LIBRTE_RING_DEBUG
173         struct rte_ring_debug_stats stats[RTE_MAX_LCORE];
174 #endif
175
176         void * ring[0] __rte_cache_aligned; /**< Memory space of ring starts here.
177                                              * not volatile so need to be careful
178                                              * about compiler re-ordering */
179 };
180
181 #define RING_F_SP_ENQ 0x0001 /**< The default enqueue is "single-producer". */
182 #define RING_F_SC_DEQ 0x0002 /**< The default dequeue is "single-consumer". */
183 #define RTE_RING_QUOT_EXCEED (1 << 31)  /**< Quota exceed for burst ops */
184 #define RTE_RING_SZ_MASK  (unsigned)(0x0fffffff) /**< Ring size mask */
185
186 /**
187  * @internal When debug is enabled, store ring statistics.
188  * @param r
189  *   A pointer to the ring.
190  * @param name
191  *   The name of the statistics field to increment in the ring.
192  * @param n
193  *   The number to add to the object-oriented statistics.
194  */
195 #ifdef RTE_LIBRTE_RING_DEBUG
196 #define __RING_STAT_ADD(r, name, n) do {                        \
197                 unsigned __lcore_id = rte_lcore_id();           \
198                 if (__lcore_id < RTE_MAX_LCORE) {               \
199                         r->stats[__lcore_id].name##_objs += n;  \
200                         r->stats[__lcore_id].name##_bulk += 1;  \
201                 }                                               \
202         } while(0)
203 #else
204 #define __RING_STAT_ADD(r, name, n) do {} while(0)
205 #endif
206
207 /**
208  * Calculate the memory size needed for a ring
209  *
210  * This function returns the number of bytes needed for a ring, given
211  * the number of elements in it. This value is the sum of the size of
212  * the structure rte_ring and the size of the memory needed by the
213  * objects pointers. The value is aligned to a cache line size.
214  *
215  * @param count
216  *   The number of elements in the ring (must be a power of 2).
217  * @return
218  *   - The memory size needed for the ring on success.
219  *   - -EINVAL if count is not a power of 2.
220  */
221 ssize_t rte_ring_get_memsize(unsigned count);
222
223 /**
224  * Initialize a ring structure.
225  *
226  * Initialize a ring structure in memory pointed by "r". The size of the
227  * memory area must be large enough to store the ring structure and the
228  * object table. It is advised to use rte_ring_get_memsize() to get the
229  * appropriate size.
230  *
231  * The ring size is set to *count*, which must be a power of two. Water
232  * marking is disabled by default. The real usable ring size is
233  * *count-1* instead of *count* to differentiate a free ring from an
234  * empty ring.
235  *
236  * The ring is not added in RTE_TAILQ_RING global list. Indeed, the
237  * memory given by the caller may not be shareable among dpdk
238  * processes.
239  *
240  * @param r
241  *   The pointer to the ring structure followed by the objects table.
242  * @param name
243  *   The name of the ring.
244  * @param count
245  *   The number of elements in the ring (must be a power of 2).
246  * @param flags
247  *   An OR of the following:
248  *    - RING_F_SP_ENQ: If this flag is set, the default behavior when
249  *      using ``rte_ring_enqueue()`` or ``rte_ring_enqueue_bulk()``
250  *      is "single-producer". Otherwise, it is "multi-producers".
251  *    - RING_F_SC_DEQ: If this flag is set, the default behavior when
252  *      using ``rte_ring_dequeue()`` or ``rte_ring_dequeue_bulk()``
253  *      is "single-consumer". Otherwise, it is "multi-consumers".
254  * @return
255  *   0 on success, or a negative value on error.
256  */
257 int rte_ring_init(struct rte_ring *r, const char *name, unsigned count,
258         unsigned flags);
259
260 /**
261  * Create a new ring named *name* in memory.
262  *
263  * This function uses ``memzone_reserve()`` to allocate memory. Then it
264  * calls rte_ring_init() to initialize an empty ring.
265  *
266  * The new ring size is set to *count*, which must be a power of
267  * two. Water marking is disabled by default. The real usable ring size
268  * is *count-1* instead of *count* to differentiate a free ring from an
269  * empty ring.
270  *
271  * The ring is added in RTE_TAILQ_RING list.
272  *
273  * @param name
274  *   The name of the ring.
275  * @param count
276  *   The size of the ring (must be a power of 2).
277  * @param socket_id
278  *   The *socket_id* argument is the socket identifier in case of
279  *   NUMA. The value can be *SOCKET_ID_ANY* if there is no NUMA
280  *   constraint for the reserved zone.
281  * @param flags
282  *   An OR of the following:
283  *    - RING_F_SP_ENQ: If this flag is set, the default behavior when
284  *      using ``rte_ring_enqueue()`` or ``rte_ring_enqueue_bulk()``
285  *      is "single-producer". Otherwise, it is "multi-producers".
286  *    - RING_F_SC_DEQ: If this flag is set, the default behavior when
287  *      using ``rte_ring_dequeue()`` or ``rte_ring_dequeue_bulk()``
288  *      is "single-consumer". Otherwise, it is "multi-consumers".
289  * @return
290  *   On success, the pointer to the new allocated ring. NULL on error with
291  *    rte_errno set appropriately. Possible errno values include:
292  *    - E_RTE_NO_CONFIG - function could not get pointer to rte_config structure
293  *    - E_RTE_SECONDARY - function was called from a secondary process instance
294  *    - E_RTE_NO_TAILQ - no tailq list could be got for the ring list
295  *    - EINVAL - count provided is not a power of 2
296  *    - ENOSPC - the maximum number of memzones has already been allocated
297  *    - EEXIST - a memzone with the same name already exists
298  *    - ENOMEM - no appropriate memory area found in which to create memzone
299  */
300 struct rte_ring *rte_ring_create(const char *name, unsigned count,
301                                  int socket_id, unsigned flags);
302
303 /**
304  * Change the high water mark.
305  *
306  * If *count* is 0, water marking is disabled. Otherwise, it is set to the
307  * *count* value. The *count* value must be greater than 0 and less
308  * than the ring size.
309  *
310  * This function can be called at any time (not necessarily at
311  * initialization).
312  *
313  * @param r
314  *   A pointer to the ring structure.
315  * @param count
316  *   The new water mark value.
317  * @return
318  *   - 0: Success; water mark changed.
319  *   - -EINVAL: Invalid water mark value.
320  */
321 int rte_ring_set_water_mark(struct rte_ring *r, unsigned count);
322
323 /**
324  * Dump the status of the ring to the console.
325  *
326  * @param f
327  *   A pointer to a file for output
328  * @param r
329  *   A pointer to the ring structure.
330  */
331 void rte_ring_dump(FILE *f, const struct rte_ring *r);
332
333 /* the actual enqueue of pointers on the ring.
334  * Placed here since identical code needed in both
335  * single and multi producer enqueue functions */
336 #define ENQUEUE_PTRS() do { \
337         const uint32_t size = r->prod.size; \
338         uint32_t idx = prod_head & mask; \
339         if (likely(idx + n < size)) { \
340                 for (i = 0; i < (n & ((~(unsigned)0x3))); i+=4, idx+=4) { \
341                         r->ring[idx] = obj_table[i]; \
342                         r->ring[idx+1] = obj_table[i+1]; \
343                         r->ring[idx+2] = obj_table[i+2]; \
344                         r->ring[idx+3] = obj_table[i+3]; \
345                 } \
346                 switch (n & 0x3) { \
347                         case 3: r->ring[idx++] = obj_table[i++]; \
348                         case 2: r->ring[idx++] = obj_table[i++]; \
349                         case 1: r->ring[idx++] = obj_table[i++]; \
350                 } \
351         } else { \
352                 for (i = 0; idx < size; i++, idx++)\
353                         r->ring[idx] = obj_table[i]; \
354                 for (idx = 0; i < n; i++, idx++) \
355                         r->ring[idx] = obj_table[i]; \
356         } \
357 } while(0)
358
359 /* the actual copy of pointers on the ring to obj_table.
360  * Placed here since identical code needed in both
361  * single and multi consumer dequeue functions */
362 #define DEQUEUE_PTRS() do { \
363         uint32_t idx = cons_head & mask; \
364         const uint32_t size = r->cons.size; \
365         if (likely(idx + n < size)) { \
366                 for (i = 0; i < (n & (~(unsigned)0x3)); i+=4, idx+=4) {\
367                         obj_table[i] = r->ring[idx]; \
368                         obj_table[i+1] = r->ring[idx+1]; \
369                         obj_table[i+2] = r->ring[idx+2]; \
370                         obj_table[i+3] = r->ring[idx+3]; \
371                 } \
372                 switch (n & 0x3) { \
373                         case 3: obj_table[i++] = r->ring[idx++]; \
374                         case 2: obj_table[i++] = r->ring[idx++]; \
375                         case 1: obj_table[i++] = r->ring[idx++]; \
376                 } \
377         } else { \
378                 for (i = 0; idx < size; i++, idx++) \
379                         obj_table[i] = r->ring[idx]; \
380                 for (idx = 0; i < n; i++, idx++) \
381                         obj_table[i] = r->ring[idx]; \
382         } \
383 } while (0)
384
385 /**
386  * @internal Enqueue several objects on the ring (multi-producers safe).
387  *
388  * This function uses a "compare and set" instruction to move the
389  * producer index atomically.
390  *
391  * @param r
392  *   A pointer to the ring structure.
393  * @param obj_table
394  *   A pointer to a table of void * pointers (objects).
395  * @param n
396  *   The number of objects to add in the ring from the obj_table.
397  * @param behavior
398  *   RTE_RING_QUEUE_FIXED:    Enqueue a fixed number of items from a ring
399  *   RTE_RING_QUEUE_VARIABLE: Enqueue as many items a possible from ring
400  * @return
401  *   Depend on the behavior value
402  *   if behavior = RTE_RING_QUEUE_FIXED
403  *   - 0: Success; objects enqueue.
404  *   - -EDQUOT: Quota exceeded. The objects have been enqueued, but the
405  *     high water mark is exceeded.
406  *   - -ENOBUFS: Not enough room in the ring to enqueue, no object is enqueued.
407  *   if behavior = RTE_RING_QUEUE_VARIABLE
408  *   - n: Actual number of objects enqueued.
409  */
410 static inline int __attribute__((always_inline))
411 __rte_ring_mp_do_enqueue(struct rte_ring *r, void * const *obj_table,
412                          unsigned n, enum rte_ring_queue_behavior behavior)
413 {
414         uint32_t prod_head, prod_next;
415         uint32_t cons_tail, free_entries;
416         const unsigned max = n;
417         int success;
418         unsigned i, rep = 0;
419         uint32_t mask = r->prod.mask;
420         int ret;
421
422         /* move prod.head atomically */
423         do {
424                 /* Reset n to the initial burst count */
425                 n = max;
426
427                 prod_head = r->prod.head;
428                 cons_tail = r->cons.tail;
429                 /* The subtraction is done between two unsigned 32bits value
430                  * (the result is always modulo 32 bits even if we have
431                  * prod_head > cons_tail). So 'free_entries' is always between 0
432                  * and size(ring)-1. */
433                 free_entries = (mask + cons_tail - prod_head);
434
435                 /* check that we have enough room in ring */
436                 if (unlikely(n > free_entries)) {
437                         if (behavior == RTE_RING_QUEUE_FIXED) {
438                                 __RING_STAT_ADD(r, enq_fail, n);
439                                 return -ENOBUFS;
440                         }
441                         else {
442                                 /* No free entry available */
443                                 if (unlikely(free_entries == 0)) {
444                                         __RING_STAT_ADD(r, enq_fail, n);
445                                         return 0;
446                                 }
447
448                                 n = free_entries;
449                         }
450                 }
451
452                 prod_next = prod_head + n;
453                 success = rte_atomic32_cmpset(&r->prod.head, prod_head,
454                                               prod_next);
455         } while (unlikely(success == 0));
456
457         /* write entries in ring */
458         ENQUEUE_PTRS();
459         rte_compiler_barrier();
460
461         /* if we exceed the watermark */
462         if (unlikely(((mask + 1) - free_entries + n) > r->prod.watermark)) {
463                 ret = (behavior == RTE_RING_QUEUE_FIXED) ? -EDQUOT :
464                                 (int)(n | RTE_RING_QUOT_EXCEED);
465                 __RING_STAT_ADD(r, enq_quota, n);
466         }
467         else {
468                 ret = (behavior == RTE_RING_QUEUE_FIXED) ? 0 : n;
469                 __RING_STAT_ADD(r, enq_success, n);
470         }
471
472         /*
473          * If there are other enqueues in progress that preceded us,
474          * we need to wait for them to complete
475          */
476         while (unlikely(r->prod.tail != prod_head)) {
477                 rte_pause();
478
479                 /* Set RTE_RING_PAUSE_REP_COUNT to avoid spin too long waiting
480                  * for other thread finish. It gives pre-empted thread a chance
481                  * to proceed and finish with ring dequeue operation. */
482                 if (RTE_RING_PAUSE_REP_COUNT &&
483                     ++rep == RTE_RING_PAUSE_REP_COUNT) {
484                         rep = 0;
485                         sched_yield();
486                 }
487         }
488         r->prod.tail = prod_next;
489         return ret;
490 }
491
492 /**
493  * @internal Enqueue several objects on a ring (NOT multi-producers safe).
494  *
495  * @param r
496  *   A pointer to the ring structure.
497  * @param obj_table
498  *   A pointer to a table of void * pointers (objects).
499  * @param n
500  *   The number of objects to add in the ring from the obj_table.
501  * @param behavior
502  *   RTE_RING_QUEUE_FIXED:    Enqueue a fixed number of items from a ring
503  *   RTE_RING_QUEUE_VARIABLE: Enqueue as many items a possible from ring
504  * @return
505  *   Depend on the behavior value
506  *   if behavior = RTE_RING_QUEUE_FIXED
507  *   - 0: Success; objects enqueue.
508  *   - -EDQUOT: Quota exceeded. The objects have been enqueued, but the
509  *     high water mark is exceeded.
510  *   - -ENOBUFS: Not enough room in the ring to enqueue, no object is enqueued.
511  *   if behavior = RTE_RING_QUEUE_VARIABLE
512  *   - n: Actual number of objects enqueued.
513  */
514 static inline int __attribute__((always_inline))
515 __rte_ring_sp_do_enqueue(struct rte_ring *r, void * const *obj_table,
516                          unsigned n, enum rte_ring_queue_behavior behavior)
517 {
518         uint32_t prod_head, cons_tail;
519         uint32_t prod_next, free_entries;
520         unsigned i;
521         uint32_t mask = r->prod.mask;
522         int ret;
523
524         prod_head = r->prod.head;
525         cons_tail = r->cons.tail;
526         /* The subtraction is done between two unsigned 32bits value
527          * (the result is always modulo 32 bits even if we have
528          * prod_head > cons_tail). So 'free_entries' is always between 0
529          * and size(ring)-1. */
530         free_entries = mask + cons_tail - prod_head;
531
532         /* check that we have enough room in ring */
533         if (unlikely(n > free_entries)) {
534                 if (behavior == RTE_RING_QUEUE_FIXED) {
535                         __RING_STAT_ADD(r, enq_fail, n);
536                         return -ENOBUFS;
537                 }
538                 else {
539                         /* No free entry available */
540                         if (unlikely(free_entries == 0)) {
541                                 __RING_STAT_ADD(r, enq_fail, n);
542                                 return 0;
543                         }
544
545                         n = free_entries;
546                 }
547         }
548
549         prod_next = prod_head + n;
550         r->prod.head = prod_next;
551
552         /* write entries in ring */
553         ENQUEUE_PTRS();
554         rte_compiler_barrier();
555
556         /* if we exceed the watermark */
557         if (unlikely(((mask + 1) - free_entries + n) > r->prod.watermark)) {
558                 ret = (behavior == RTE_RING_QUEUE_FIXED) ? -EDQUOT :
559                         (int)(n | RTE_RING_QUOT_EXCEED);
560                 __RING_STAT_ADD(r, enq_quota, n);
561         }
562         else {
563                 ret = (behavior == RTE_RING_QUEUE_FIXED) ? 0 : n;
564                 __RING_STAT_ADD(r, enq_success, n);
565         }
566
567         r->prod.tail = prod_next;
568         return ret;
569 }
570
571 /**
572  * @internal Dequeue several objects from a ring (multi-consumers safe). When
573  * the request objects are more than the available objects, only dequeue the
574  * actual number of objects
575  *
576  * This function uses a "compare and set" instruction to move the
577  * consumer index atomically.
578  *
579  * @param r
580  *   A pointer to the ring structure.
581  * @param obj_table
582  *   A pointer to a table of void * pointers (objects) that will be filled.
583  * @param n
584  *   The number of objects to dequeue from the ring to the obj_table.
585  * @param behavior
586  *   RTE_RING_QUEUE_FIXED:    Dequeue a fixed number of items from a ring
587  *   RTE_RING_QUEUE_VARIABLE: Dequeue as many items a possible from ring
588  * @return
589  *   Depend on the behavior value
590  *   if behavior = RTE_RING_QUEUE_FIXED
591  *   - 0: Success; objects dequeued.
592  *   - -ENOENT: Not enough entries in the ring to dequeue; no object is
593  *     dequeued.
594  *   if behavior = RTE_RING_QUEUE_VARIABLE
595  *   - n: Actual number of objects dequeued.
596  */
597
598 static inline int __attribute__((always_inline))
599 __rte_ring_mc_do_dequeue(struct rte_ring *r, void **obj_table,
600                  unsigned n, enum rte_ring_queue_behavior behavior)
601 {
602         uint32_t cons_head, prod_tail;
603         uint32_t cons_next, entries;
604         const unsigned max = n;
605         int success;
606         unsigned i, rep = 0;
607         uint32_t mask = r->prod.mask;
608
609         /* move cons.head atomically */
610         do {
611                 /* Restore n as it may change every loop */
612                 n = max;
613
614                 cons_head = r->cons.head;
615                 prod_tail = r->prod.tail;
616                 /* The subtraction is done between two unsigned 32bits value
617                  * (the result is always modulo 32 bits even if we have
618                  * cons_head > prod_tail). So 'entries' is always between 0
619                  * and size(ring)-1. */
620                 entries = (prod_tail - cons_head);
621
622                 /* Set the actual entries for dequeue */
623                 if (n > entries) {
624                         if (behavior == RTE_RING_QUEUE_FIXED) {
625                                 __RING_STAT_ADD(r, deq_fail, n);
626                                 return -ENOENT;
627                         }
628                         else {
629                                 if (unlikely(entries == 0)){
630                                         __RING_STAT_ADD(r, deq_fail, n);
631                                         return 0;
632                                 }
633
634                                 n = entries;
635                         }
636                 }
637
638                 cons_next = cons_head + n;
639                 success = rte_atomic32_cmpset(&r->cons.head, cons_head,
640                                               cons_next);
641         } while (unlikely(success == 0));
642
643         /* copy in table */
644         DEQUEUE_PTRS();
645         rte_compiler_barrier();
646
647         /*
648          * If there are other dequeues in progress that preceded us,
649          * we need to wait for them to complete
650          */
651         while (unlikely(r->cons.tail != cons_head)) {
652                 rte_pause();
653
654                 /* Set RTE_RING_PAUSE_REP_COUNT to avoid spin too long waiting
655                  * for other thread finish. It gives pre-empted thread a chance
656                  * to proceed and finish with ring dequeue operation. */
657                 if (RTE_RING_PAUSE_REP_COUNT &&
658                     ++rep == RTE_RING_PAUSE_REP_COUNT) {
659                         rep = 0;
660                         sched_yield();
661                 }
662         }
663         __RING_STAT_ADD(r, deq_success, n);
664         r->cons.tail = cons_next;
665
666         return behavior == RTE_RING_QUEUE_FIXED ? 0 : n;
667 }
668
669 /**
670  * @internal Dequeue several objects from a ring (NOT multi-consumers safe).
671  * When the request objects are more than the available objects, only dequeue
672  * the actual number of objects
673  *
674  * @param r
675  *   A pointer to the ring structure.
676  * @param obj_table
677  *   A pointer to a table of void * pointers (objects) that will be filled.
678  * @param n
679  *   The number of objects to dequeue from the ring to the obj_table.
680  * @param behavior
681  *   RTE_RING_QUEUE_FIXED:    Dequeue a fixed number of items from a ring
682  *   RTE_RING_QUEUE_VARIABLE: Dequeue as many items a possible from ring
683  * @return
684  *   Depend on the behavior value
685  *   if behavior = RTE_RING_QUEUE_FIXED
686  *   - 0: Success; objects dequeued.
687  *   - -ENOENT: Not enough entries in the ring to dequeue; no object is
688  *     dequeued.
689  *   if behavior = RTE_RING_QUEUE_VARIABLE
690  *   - n: Actual number of objects dequeued.
691  */
692 static inline int __attribute__((always_inline))
693 __rte_ring_sc_do_dequeue(struct rte_ring *r, void **obj_table,
694                  unsigned n, enum rte_ring_queue_behavior behavior)
695 {
696         uint32_t cons_head, prod_tail;
697         uint32_t cons_next, entries;
698         unsigned i;
699         uint32_t mask = r->prod.mask;
700
701         cons_head = r->cons.head;
702         prod_tail = r->prod.tail;
703         /* The subtraction is done between two unsigned 32bits value
704          * (the result is always modulo 32 bits even if we have
705          * cons_head > prod_tail). So 'entries' is always between 0
706          * and size(ring)-1. */
707         entries = prod_tail - cons_head;
708
709         if (n > entries) {
710                 if (behavior == RTE_RING_QUEUE_FIXED) {
711                         __RING_STAT_ADD(r, deq_fail, n);
712                         return -ENOENT;
713                 }
714                 else {
715                         if (unlikely(entries == 0)){
716                                 __RING_STAT_ADD(r, deq_fail, n);
717                                 return 0;
718                         }
719
720                         n = entries;
721                 }
722         }
723
724         cons_next = cons_head + n;
725         r->cons.head = cons_next;
726
727         /* copy in table */
728         DEQUEUE_PTRS();
729         rte_compiler_barrier();
730
731         __RING_STAT_ADD(r, deq_success, n);
732         r->cons.tail = cons_next;
733         return behavior == RTE_RING_QUEUE_FIXED ? 0 : n;
734 }
735
736 /**
737  * Enqueue several objects on the ring (multi-producers safe).
738  *
739  * This function uses a "compare and set" instruction to move the
740  * producer index atomically.
741  *
742  * @param r
743  *   A pointer to the ring structure.
744  * @param obj_table
745  *   A pointer to a table of void * pointers (objects).
746  * @param n
747  *   The number of objects to add in the ring from the obj_table.
748  * @return
749  *   - 0: Success; objects enqueue.
750  *   - -EDQUOT: Quota exceeded. The objects have been enqueued, but the
751  *     high water mark is exceeded.
752  *   - -ENOBUFS: Not enough room in the ring to enqueue, no object is enqueued.
753  */
754 static inline int __attribute__((always_inline))
755 rte_ring_mp_enqueue_bulk(struct rte_ring *r, void * const *obj_table,
756                          unsigned n)
757 {
758         return __rte_ring_mp_do_enqueue(r, obj_table, n, RTE_RING_QUEUE_FIXED);
759 }
760
761 /**
762  * Enqueue several objects on a ring (NOT multi-producers safe).
763  *
764  * @param r
765  *   A pointer to the ring structure.
766  * @param obj_table
767  *   A pointer to a table of void * pointers (objects).
768  * @param n
769  *   The number of objects to add in the ring from the obj_table.
770  * @return
771  *   - 0: Success; objects enqueued.
772  *   - -EDQUOT: Quota exceeded. The objects have been enqueued, but the
773  *     high water mark is exceeded.
774  *   - -ENOBUFS: Not enough room in the ring to enqueue; no object is enqueued.
775  */
776 static inline int __attribute__((always_inline))
777 rte_ring_sp_enqueue_bulk(struct rte_ring *r, void * const *obj_table,
778                          unsigned n)
779 {
780         return __rte_ring_sp_do_enqueue(r, obj_table, n, RTE_RING_QUEUE_FIXED);
781 }
782
783 /**
784  * Enqueue several objects on a ring.
785  *
786  * This function calls the multi-producer or the single-producer
787  * version depending on the default behavior that was specified at
788  * ring creation time (see flags).
789  *
790  * @param r
791  *   A pointer to the ring structure.
792  * @param obj_table
793  *   A pointer to a table of void * pointers (objects).
794  * @param n
795  *   The number of objects to add in the ring from the obj_table.
796  * @return
797  *   - 0: Success; objects enqueued.
798  *   - -EDQUOT: Quota exceeded. The objects have been enqueued, but the
799  *     high water mark is exceeded.
800  *   - -ENOBUFS: Not enough room in the ring to enqueue; no object is enqueued.
801  */
802 static inline int __attribute__((always_inline))
803 rte_ring_enqueue_bulk(struct rte_ring *r, void * const *obj_table,
804                       unsigned n)
805 {
806         if (r->prod.sp_enqueue)
807                 return rte_ring_sp_enqueue_bulk(r, obj_table, n);
808         else
809                 return rte_ring_mp_enqueue_bulk(r, obj_table, n);
810 }
811
812 /**
813  * Enqueue one object on a ring (multi-producers safe).
814  *
815  * This function uses a "compare and set" instruction to move the
816  * producer index atomically.
817  *
818  * @param r
819  *   A pointer to the ring structure.
820  * @param obj
821  *   A pointer to the object to be added.
822  * @return
823  *   - 0: Success; objects enqueued.
824  *   - -EDQUOT: Quota exceeded. The objects have been enqueued, but the
825  *     high water mark is exceeded.
826  *   - -ENOBUFS: Not enough room in the ring to enqueue; no object is enqueued.
827  */
828 static inline int __attribute__((always_inline))
829 rte_ring_mp_enqueue(struct rte_ring *r, void *obj)
830 {
831         return rte_ring_mp_enqueue_bulk(r, &obj, 1);
832 }
833
834 /**
835  * Enqueue one object on a ring (NOT multi-producers safe).
836  *
837  * @param r
838  *   A pointer to the ring structure.
839  * @param obj
840  *   A pointer to the object to be added.
841  * @return
842  *   - 0: Success; objects enqueued.
843  *   - -EDQUOT: Quota exceeded. The objects have been enqueued, but the
844  *     high water mark is exceeded.
845  *   - -ENOBUFS: Not enough room in the ring to enqueue; no object is enqueued.
846  */
847 static inline int __attribute__((always_inline))
848 rte_ring_sp_enqueue(struct rte_ring *r, void *obj)
849 {
850         return rte_ring_sp_enqueue_bulk(r, &obj, 1);
851 }
852
853 /**
854  * Enqueue one object on a ring.
855  *
856  * This function calls the multi-producer or the single-producer
857  * version, depending on the default behaviour that was specified at
858  * ring creation time (see flags).
859  *
860  * @param r
861  *   A pointer to the ring structure.
862  * @param obj
863  *   A pointer to the object to be added.
864  * @return
865  *   - 0: Success; objects enqueued.
866  *   - -EDQUOT: Quota exceeded. The objects have been enqueued, but the
867  *     high water mark is exceeded.
868  *   - -ENOBUFS: Not enough room in the ring to enqueue; no object is enqueued.
869  */
870 static inline int __attribute__((always_inline))
871 rte_ring_enqueue(struct rte_ring *r, void *obj)
872 {
873         if (r->prod.sp_enqueue)
874                 return rte_ring_sp_enqueue(r, obj);
875         else
876                 return rte_ring_mp_enqueue(r, obj);
877 }
878
879 /**
880  * Dequeue several objects from a ring (multi-consumers safe).
881  *
882  * This function uses a "compare and set" instruction to move the
883  * consumer index atomically.
884  *
885  * @param r
886  *   A pointer to the ring structure.
887  * @param obj_table
888  *   A pointer to a table of void * pointers (objects) that will be filled.
889  * @param n
890  *   The number of objects to dequeue from the ring to the obj_table.
891  * @return
892  *   - 0: Success; objects dequeued.
893  *   - -ENOENT: Not enough entries in the ring to dequeue; no object is
894  *     dequeued.
895  */
896 static inline int __attribute__((always_inline))
897 rte_ring_mc_dequeue_bulk(struct rte_ring *r, void **obj_table, unsigned n)
898 {
899         return __rte_ring_mc_do_dequeue(r, obj_table, n, RTE_RING_QUEUE_FIXED);
900 }
901
902 /**
903  * Dequeue several objects from a ring (NOT multi-consumers safe).
904  *
905  * @param r
906  *   A pointer to the ring structure.
907  * @param obj_table
908  *   A pointer to a table of void * pointers (objects) that will be filled.
909  * @param n
910  *   The number of objects to dequeue from the ring to the obj_table,
911  *   must be strictly positive.
912  * @return
913  *   - 0: Success; objects dequeued.
914  *   - -ENOENT: Not enough entries in the ring to dequeue; no object is
915  *     dequeued.
916  */
917 static inline int __attribute__((always_inline))
918 rte_ring_sc_dequeue_bulk(struct rte_ring *r, void **obj_table, unsigned n)
919 {
920         return __rte_ring_sc_do_dequeue(r, obj_table, n, RTE_RING_QUEUE_FIXED);
921 }
922
923 /**
924  * Dequeue several objects from a ring.
925  *
926  * This function calls the multi-consumers or the single-consumer
927  * version, depending on the default behaviour that was specified at
928  * ring creation time (see flags).
929  *
930  * @param r
931  *   A pointer to the ring structure.
932  * @param obj_table
933  *   A pointer to a table of void * pointers (objects) that will be filled.
934  * @param n
935  *   The number of objects to dequeue from the ring to the obj_table.
936  * @return
937  *   - 0: Success; objects dequeued.
938  *   - -ENOENT: Not enough entries in the ring to dequeue, no object is
939  *     dequeued.
940  */
941 static inline int __attribute__((always_inline))
942 rte_ring_dequeue_bulk(struct rte_ring *r, void **obj_table, unsigned n)
943 {
944         if (r->cons.sc_dequeue)
945                 return rte_ring_sc_dequeue_bulk(r, obj_table, n);
946         else
947                 return rte_ring_mc_dequeue_bulk(r, obj_table, n);
948 }
949
950 /**
951  * Dequeue one object from a ring (multi-consumers safe).
952  *
953  * This function uses a "compare and set" instruction to move the
954  * consumer index atomically.
955  *
956  * @param r
957  *   A pointer to the ring structure.
958  * @param obj_p
959  *   A pointer to a void * pointer (object) that will be filled.
960  * @return
961  *   - 0: Success; objects dequeued.
962  *   - -ENOENT: Not enough entries in the ring to dequeue; no object is
963  *     dequeued.
964  */
965 static inline int __attribute__((always_inline))
966 rte_ring_mc_dequeue(struct rte_ring *r, void **obj_p)
967 {
968         return rte_ring_mc_dequeue_bulk(r, obj_p, 1);
969 }
970
971 /**
972  * Dequeue one object from a ring (NOT multi-consumers safe).
973  *
974  * @param r
975  *   A pointer to the ring structure.
976  * @param obj_p
977  *   A pointer to a void * pointer (object) that will be filled.
978  * @return
979  *   - 0: Success; objects dequeued.
980  *   - -ENOENT: Not enough entries in the ring to dequeue, no object is
981  *     dequeued.
982  */
983 static inline int __attribute__((always_inline))
984 rte_ring_sc_dequeue(struct rte_ring *r, void **obj_p)
985 {
986         return rte_ring_sc_dequeue_bulk(r, obj_p, 1);
987 }
988
989 /**
990  * Dequeue one object from a ring.
991  *
992  * This function calls the multi-consumers or the single-consumer
993  * version depending on the default behaviour that was specified at
994  * ring creation time (see flags).
995  *
996  * @param r
997  *   A pointer to the ring structure.
998  * @param obj_p
999  *   A pointer to a void * pointer (object) that will be filled.
1000  * @return
1001  *   - 0: Success, objects dequeued.
1002  *   - -ENOENT: Not enough entries in the ring to dequeue, no object is
1003  *     dequeued.
1004  */
1005 static inline int __attribute__((always_inline))
1006 rte_ring_dequeue(struct rte_ring *r, void **obj_p)
1007 {
1008         if (r->cons.sc_dequeue)
1009                 return rte_ring_sc_dequeue(r, obj_p);
1010         else
1011                 return rte_ring_mc_dequeue(r, obj_p);
1012 }
1013
1014 /**
1015  * Test if a ring is full.
1016  *
1017  * @param r
1018  *   A pointer to the ring structure.
1019  * @return
1020  *   - 1: The ring is full.
1021  *   - 0: The ring is not full.
1022  */
1023 static inline int
1024 rte_ring_full(const struct rte_ring *r)
1025 {
1026         uint32_t prod_tail = r->prod.tail;
1027         uint32_t cons_tail = r->cons.tail;
1028         return (((cons_tail - prod_tail - 1) & r->prod.mask) == 0);
1029 }
1030
1031 /**
1032  * Test if a ring is empty.
1033  *
1034  * @param r
1035  *   A pointer to the ring structure.
1036  * @return
1037  *   - 1: The ring is empty.
1038  *   - 0: The ring is not empty.
1039  */
1040 static inline int
1041 rte_ring_empty(const struct rte_ring *r)
1042 {
1043         uint32_t prod_tail = r->prod.tail;
1044         uint32_t cons_tail = r->cons.tail;
1045         return !!(cons_tail == prod_tail);
1046 }
1047
1048 /**
1049  * Return the number of entries in a ring.
1050  *
1051  * @param r
1052  *   A pointer to the ring structure.
1053  * @return
1054  *   The number of entries in the ring.
1055  */
1056 static inline unsigned
1057 rte_ring_count(const struct rte_ring *r)
1058 {
1059         uint32_t prod_tail = r->prod.tail;
1060         uint32_t cons_tail = r->cons.tail;
1061         return ((prod_tail - cons_tail) & r->prod.mask);
1062 }
1063
1064 /**
1065  * Return the number of free entries in a ring.
1066  *
1067  * @param r
1068  *   A pointer to the ring structure.
1069  * @return
1070  *   The number of free entries in the ring.
1071  */
1072 static inline unsigned
1073 rte_ring_free_count(const struct rte_ring *r)
1074 {
1075         uint32_t prod_tail = r->prod.tail;
1076         uint32_t cons_tail = r->cons.tail;
1077         return ((cons_tail - prod_tail - 1) & r->prod.mask);
1078 }
1079
1080 /**
1081  * Dump the status of all rings on the console
1082  *
1083  * @param f
1084  *   A pointer to a file for output
1085  */
1086 void rte_ring_list_dump(FILE *f);
1087
1088 /**
1089  * Search a ring from its name
1090  *
1091  * @param name
1092  *   The name of the ring.
1093  * @return
1094  *   The pointer to the ring matching the name, or NULL if not found,
1095  *   with rte_errno set appropriately. Possible rte_errno values include:
1096  *    - ENOENT - required entry not available to return.
1097  */
1098 struct rte_ring *rte_ring_lookup(const char *name);
1099
1100 /**
1101  * Enqueue several objects on the ring (multi-producers safe).
1102  *
1103  * This function uses a "compare and set" instruction to move the
1104  * producer index atomically.
1105  *
1106  * @param r
1107  *   A pointer to the ring structure.
1108  * @param obj_table
1109  *   A pointer to a table of void * pointers (objects).
1110  * @param n
1111  *   The number of objects to add in the ring from the obj_table.
1112  * @return
1113  *   - n: Actual number of objects enqueued.
1114  */
1115 static inline unsigned __attribute__((always_inline))
1116 rte_ring_mp_enqueue_burst(struct rte_ring *r, void * const *obj_table,
1117                          unsigned n)
1118 {
1119         return __rte_ring_mp_do_enqueue(r, obj_table, n, RTE_RING_QUEUE_VARIABLE);
1120 }
1121
1122 /**
1123  * Enqueue several objects on a ring (NOT multi-producers safe).
1124  *
1125  * @param r
1126  *   A pointer to the ring structure.
1127  * @param obj_table
1128  *   A pointer to a table of void * pointers (objects).
1129  * @param n
1130  *   The number of objects to add in the ring from the obj_table.
1131  * @return
1132  *   - n: Actual number of objects enqueued.
1133  */
1134 static inline unsigned __attribute__((always_inline))
1135 rte_ring_sp_enqueue_burst(struct rte_ring *r, void * const *obj_table,
1136                          unsigned n)
1137 {
1138         return __rte_ring_sp_do_enqueue(r, obj_table, n, RTE_RING_QUEUE_VARIABLE);
1139 }
1140
1141 /**
1142  * Enqueue several objects on a ring.
1143  *
1144  * This function calls the multi-producer or the single-producer
1145  * version depending on the default behavior that was specified at
1146  * ring creation time (see flags).
1147  *
1148  * @param r
1149  *   A pointer to the ring structure.
1150  * @param obj_table
1151  *   A pointer to a table of void * pointers (objects).
1152  * @param n
1153  *   The number of objects to add in the ring from the obj_table.
1154  * @return
1155  *   - n: Actual number of objects enqueued.
1156  */
1157 static inline unsigned __attribute__((always_inline))
1158 rte_ring_enqueue_burst(struct rte_ring *r, void * const *obj_table,
1159                       unsigned n)
1160 {
1161         if (r->prod.sp_enqueue)
1162                 return rte_ring_sp_enqueue_burst(r, obj_table, n);
1163         else
1164                 return rte_ring_mp_enqueue_burst(r, obj_table, n);
1165 }
1166
1167 /**
1168  * Dequeue several objects from a ring (multi-consumers safe). When the request
1169  * objects are more than the available objects, only dequeue the actual number
1170  * of objects
1171  *
1172  * This function uses a "compare and set" instruction to move the
1173  * consumer index atomically.
1174  *
1175  * @param r
1176  *   A pointer to the ring structure.
1177  * @param obj_table
1178  *   A pointer to a table of void * pointers (objects) that will be filled.
1179  * @param n
1180  *   The number of objects to dequeue from the ring to the obj_table.
1181  * @return
1182  *   - n: Actual number of objects dequeued, 0 if ring is empty
1183  */
1184 static inline unsigned __attribute__((always_inline))
1185 rte_ring_mc_dequeue_burst(struct rte_ring *r, void **obj_table, unsigned n)
1186 {
1187         return __rte_ring_mc_do_dequeue(r, obj_table, n, RTE_RING_QUEUE_VARIABLE);
1188 }
1189
1190 /**
1191  * Dequeue several objects from a ring (NOT multi-consumers safe).When the
1192  * request objects are more than the available objects, only dequeue the
1193  * actual number of objects
1194  *
1195  * @param r
1196  *   A pointer to the ring structure.
1197  * @param obj_table
1198  *   A pointer to a table of void * pointers (objects) that will be filled.
1199  * @param n
1200  *   The number of objects to dequeue from the ring to the obj_table.
1201  * @return
1202  *   - n: Actual number of objects dequeued, 0 if ring is empty
1203  */
1204 static inline unsigned __attribute__((always_inline))
1205 rte_ring_sc_dequeue_burst(struct rte_ring *r, void **obj_table, unsigned n)
1206 {
1207         return __rte_ring_sc_do_dequeue(r, obj_table, n, RTE_RING_QUEUE_VARIABLE);
1208 }
1209
1210 /**
1211  * Dequeue multiple objects from a ring up to a maximum number.
1212  *
1213  * This function calls the multi-consumers or the single-consumer
1214  * version, depending on the default behaviour that was specified at
1215  * ring creation time (see flags).
1216  *
1217  * @param r
1218  *   A pointer to the ring structure.
1219  * @param obj_table
1220  *   A pointer to a table of void * pointers (objects) that will be filled.
1221  * @param n
1222  *   The number of objects to dequeue from the ring to the obj_table.
1223  * @return
1224  *   - Number of objects dequeued
1225  */
1226 static inline unsigned __attribute__((always_inline))
1227 rte_ring_dequeue_burst(struct rte_ring *r, void **obj_table, unsigned n)
1228 {
1229         if (r->cons.sc_dequeue)
1230                 return rte_ring_sc_dequeue_burst(r, obj_table, n);
1231         else
1232                 return rte_ring_mc_dequeue_burst(r, obj_table, n);
1233 }
1234
1235 #ifdef __cplusplus
1236 }
1237 #endif
1238
1239 #endif /* _RTE_RING_H_ */