926031896e1e64e5ff97172f7222e072be8bf9d9
[dpdk.git] / lib / librte_mempool / rte_mempool.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
5  *   Copyright(c) 2016 6WIND S.A.
6  *   All rights reserved.
7  *
8  *   Redistribution and use in source and binary forms, with or without
9  *   modification, are permitted provided that the following conditions
10  *   are met:
11  *
12  *     * Redistributions of source code must retain the above copyright
13  *       notice, this list of conditions and the following disclaimer.
14  *     * Redistributions in binary form must reproduce the above copyright
15  *       notice, this list of conditions and the following disclaimer in
16  *       the documentation and/or other materials provided with the
17  *       distribution.
18  *     * Neither the name of Intel Corporation nor the names of its
19  *       contributors may be used to endorse or promote products derived
20  *       from this software without specific prior written permission.
21  *
22  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34
35 #include <stdio.h>
36 #include <string.h>
37 #include <stdint.h>
38 #include <stdarg.h>
39 #include <unistd.h>
40 #include <inttypes.h>
41 #include <errno.h>
42 #include <sys/queue.h>
43
44 #include <rte_common.h>
45 #include <rte_log.h>
46 #include <rte_debug.h>
47 #include <rte_memory.h>
48 #include <rte_memzone.h>
49 #include <rte_malloc.h>
50 #include <rte_atomic.h>
51 #include <rte_launch.h>
52 #include <rte_eal.h>
53 #include <rte_eal_memconfig.h>
54 #include <rte_per_lcore.h>
55 #include <rte_lcore.h>
56 #include <rte_branch_prediction.h>
57 #include <rte_ring.h>
58 #include <rte_errno.h>
59 #include <rte_string_fns.h>
60 #include <rte_spinlock.h>
61
62 #include "rte_mempool.h"
63
64 TAILQ_HEAD(rte_mempool_list, rte_tailq_entry);
65
66 static struct rte_tailq_elem rte_mempool_tailq = {
67         .name = "RTE_MEMPOOL",
68 };
69 EAL_REGISTER_TAILQ(rte_mempool_tailq)
70
71 #define CACHE_FLUSHTHRESH_MULTIPLIER 1.5
72 #define CALC_CACHE_FLUSHTHRESH(c)       \
73         ((typeof(c))((c) * CACHE_FLUSHTHRESH_MULTIPLIER))
74
75 /*
76  * return the greatest common divisor between a and b (fast algorithm)
77  *
78  */
79 static unsigned get_gcd(unsigned a, unsigned b)
80 {
81         unsigned c;
82
83         if (0 == a)
84                 return b;
85         if (0 == b)
86                 return a;
87
88         if (a < b) {
89                 c = a;
90                 a = b;
91                 b = c;
92         }
93
94         while (b != 0) {
95                 c = a % b;
96                 a = b;
97                 b = c;
98         }
99
100         return a;
101 }
102
103 /*
104  * Depending on memory configuration, objects addresses are spread
105  * between channels and ranks in RAM: the pool allocator will add
106  * padding between objects. This function return the new size of the
107  * object.
108  */
109 static unsigned optimize_object_size(unsigned obj_size)
110 {
111         unsigned nrank, nchan;
112         unsigned new_obj_size;
113
114         /* get number of channels */
115         nchan = rte_memory_get_nchannel();
116         if (nchan == 0)
117                 nchan = 4;
118
119         nrank = rte_memory_get_nrank();
120         if (nrank == 0)
121                 nrank = 1;
122
123         /* process new object size */
124         new_obj_size = (obj_size + RTE_MEMPOOL_ALIGN_MASK) / RTE_MEMPOOL_ALIGN;
125         while (get_gcd(new_obj_size, nrank * nchan) != 1)
126                 new_obj_size++;
127         return new_obj_size * RTE_MEMPOOL_ALIGN;
128 }
129
130 /**
131  * A mempool object iterator callback function.
132  */
133 typedef void (*rte_mempool_obj_iter_t)(void * /*obj_iter_arg*/,
134         void * /*obj_start*/,
135         void * /*obj_end*/,
136         uint32_t /*obj_index */,
137         phys_addr_t /*physaddr*/);
138
139 static void
140 mempool_add_elem(struct rte_mempool *mp, void *obj, phys_addr_t physaddr)
141 {
142         struct rte_mempool_objhdr *hdr;
143         struct rte_mempool_objtlr *tlr __rte_unused;
144
145         /* set mempool ptr in header */
146         hdr = RTE_PTR_SUB(obj, sizeof(*hdr));
147         hdr->mp = mp;
148         hdr->physaddr = physaddr;
149         STAILQ_INSERT_TAIL(&mp->elt_list, hdr, next);
150         mp->populated_size++;
151
152 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
153         hdr->cookie = RTE_MEMPOOL_HEADER_COOKIE2;
154         tlr = __mempool_get_trailer(obj);
155         tlr->cookie = RTE_MEMPOOL_TRAILER_COOKIE;
156 #endif
157
158         /* enqueue in ring */
159         rte_ring_sp_enqueue(mp->ring, obj);
160 }
161
162 /* Iterate through objects at the given address
163  *
164  * Given the pointer to the memory, and its topology in physical memory
165  * (the physical addresses table), iterate through the "elt_num" objects
166  * of size "elt_sz" aligned at "align". For each object in this memory
167  * chunk, invoke a callback. It returns the effective number of objects
168  * in this memory.
169  */
170 static uint32_t
171 rte_mempool_obj_mem_iter(void *vaddr, uint32_t elt_num, size_t total_elt_sz,
172         size_t align, const phys_addr_t paddr[], uint32_t pg_num,
173         uint32_t pg_shift, rte_mempool_obj_iter_t obj_iter, void *obj_iter_arg)
174 {
175         uint32_t i, j, k;
176         uint32_t pgn, pgf;
177         uintptr_t end, start, va;
178         uintptr_t pg_sz;
179         phys_addr_t physaddr;
180
181         pg_sz = (uintptr_t)1 << pg_shift;
182         va = (uintptr_t)vaddr;
183
184         i = 0;
185         j = 0;
186
187         while (i != elt_num && j != pg_num) {
188
189                 start = RTE_ALIGN_CEIL(va, align);
190                 end = start + total_elt_sz;
191
192                 /* index of the first page for the next element. */
193                 pgf = (end >> pg_shift) - (start >> pg_shift);
194
195                 /* index of the last page for the current element. */
196                 pgn = ((end - 1) >> pg_shift) - (start >> pg_shift);
197                 pgn += j;
198
199                 /* do we have enough space left for the element. */
200                 if (pgn >= pg_num)
201                         break;
202
203                 for (k = j;
204                                 k != pgn &&
205                                 paddr[k] + pg_sz == paddr[k + 1];
206                                 k++)
207                         ;
208
209                 /*
210                  * if next pgn chunks of memory physically continuous,
211                  * use it to create next element.
212                  * otherwise, just skip that chunk unused.
213                  */
214                 if (k == pgn) {
215                         physaddr = paddr[k] + (start & (pg_sz - 1));
216                         if (obj_iter != NULL)
217                                 obj_iter(obj_iter_arg, (void *)start,
218                                         (void *)end, i, physaddr);
219                         va = end;
220                         j += pgf;
221                         i++;
222                 } else {
223                         va = RTE_ALIGN_CEIL((va + 1), pg_sz);
224                         j++;
225                 }
226         }
227
228         return i;
229 }
230
231 /* call obj_cb() for each mempool element */
232 uint32_t
233 rte_mempool_obj_iter(struct rte_mempool *mp,
234         rte_mempool_obj_cb_t *obj_cb, void *obj_cb_arg)
235 {
236         struct rte_mempool_objhdr *hdr;
237         void *obj;
238         unsigned n = 0;
239
240         STAILQ_FOREACH(hdr, &mp->elt_list, next) {
241                 obj = (char *)hdr + sizeof(*hdr);
242                 obj_cb(mp, obj_cb_arg, obj, n);
243                 n++;
244         }
245
246         return n;
247 }
248
249 /* get the header, trailer and total size of a mempool element. */
250 uint32_t
251 rte_mempool_calc_obj_size(uint32_t elt_size, uint32_t flags,
252         struct rte_mempool_objsz *sz)
253 {
254         struct rte_mempool_objsz lsz;
255
256         sz = (sz != NULL) ? sz : &lsz;
257
258         sz->header_size = sizeof(struct rte_mempool_objhdr);
259         if ((flags & MEMPOOL_F_NO_CACHE_ALIGN) == 0)
260                 sz->header_size = RTE_ALIGN_CEIL(sz->header_size,
261                         RTE_MEMPOOL_ALIGN);
262
263         sz->trailer_size = sizeof(struct rte_mempool_objtlr);
264
265         /* element size is 8 bytes-aligned at least */
266         sz->elt_size = RTE_ALIGN_CEIL(elt_size, sizeof(uint64_t));
267
268         /* expand trailer to next cache line */
269         if ((flags & MEMPOOL_F_NO_CACHE_ALIGN) == 0) {
270                 sz->total_size = sz->header_size + sz->elt_size +
271                         sz->trailer_size;
272                 sz->trailer_size += ((RTE_MEMPOOL_ALIGN -
273                                   (sz->total_size & RTE_MEMPOOL_ALIGN_MASK)) &
274                                  RTE_MEMPOOL_ALIGN_MASK);
275         }
276
277         /*
278          * increase trailer to add padding between objects in order to
279          * spread them across memory channels/ranks
280          */
281         if ((flags & MEMPOOL_F_NO_SPREAD) == 0) {
282                 unsigned new_size;
283                 new_size = optimize_object_size(sz->header_size + sz->elt_size +
284                         sz->trailer_size);
285                 sz->trailer_size = new_size - sz->header_size - sz->elt_size;
286         }
287
288         if (! rte_eal_has_hugepages()) {
289                 /*
290                  * compute trailer size so that pool elements fit exactly in
291                  * a standard page
292                  */
293                 int page_size = getpagesize();
294                 int new_size = page_size - sz->header_size - sz->elt_size;
295                 if (new_size < 0 || (unsigned int)new_size < sz->trailer_size) {
296                         printf("When hugepages are disabled, pool objects "
297                                "can't exceed PAGE_SIZE: %d + %d + %d > %d\n",
298                                sz->header_size, sz->elt_size, sz->trailer_size,
299                                page_size);
300                         return 0;
301                 }
302                 sz->trailer_size = new_size;
303         }
304
305         /* this is the size of an object, including header and trailer */
306         sz->total_size = sz->header_size + sz->elt_size + sz->trailer_size;
307
308         return sz->total_size;
309 }
310
311
312 /*
313  * Calculate maximum amount of memory required to store given number of objects.
314  */
315 size_t
316 rte_mempool_xmem_size(uint32_t elt_num, size_t total_elt_sz, uint32_t pg_shift)
317 {
318         size_t n, pg_num, pg_sz, sz;
319
320         pg_sz = (size_t)1 << pg_shift;
321
322         if ((n = pg_sz / total_elt_sz) > 0) {
323                 pg_num = (elt_num + n - 1) / n;
324                 sz = pg_num << pg_shift;
325         } else {
326                 sz = RTE_ALIGN_CEIL(total_elt_sz, pg_sz) * elt_num;
327         }
328
329         return sz;
330 }
331
332 /* Callback used by rte_mempool_xmem_usage(): it sets the opaque
333  * argument to the end of the object.
334  */
335 static void
336 mempool_lelem_iter(void *arg, __rte_unused void *start, void *end,
337         __rte_unused uint32_t idx, __rte_unused phys_addr_t physaddr)
338 {
339         *(uintptr_t *)arg = (uintptr_t)end;
340 }
341
342 /*
343  * Calculate how much memory would be actually required with the
344  * given memory footprint to store required number of elements.
345  */
346 ssize_t
347 rte_mempool_xmem_usage(void *vaddr, uint32_t elt_num, size_t total_elt_sz,
348         const phys_addr_t paddr[], uint32_t pg_num, uint32_t pg_shift)
349 {
350         uint32_t n;
351         uintptr_t va, uv;
352         size_t pg_sz, usz;
353
354         pg_sz = (size_t)1 << pg_shift;
355         va = (uintptr_t)vaddr;
356         uv = va;
357
358         if ((n = rte_mempool_obj_mem_iter(vaddr, elt_num, total_elt_sz, 1,
359                         paddr, pg_num, pg_shift, mempool_lelem_iter,
360                         &uv)) != elt_num) {
361                 return -(ssize_t)n;
362         }
363
364         uv = RTE_ALIGN_CEIL(uv, pg_sz);
365         usz = uv - va;
366         return usz;
367 }
368
369 #ifndef RTE_LIBRTE_XEN_DOM0
370 /* stub if DOM0 support not configured */
371 struct rte_mempool *
372 rte_dom0_mempool_create(const char *name __rte_unused,
373                         unsigned n __rte_unused,
374                         unsigned elt_size __rte_unused,
375                         unsigned cache_size __rte_unused,
376                         unsigned private_data_size __rte_unused,
377                         rte_mempool_ctor_t *mp_init __rte_unused,
378                         void *mp_init_arg __rte_unused,
379                         rte_mempool_obj_ctor_t *obj_init __rte_unused,
380                         void *obj_init_arg __rte_unused,
381                         int socket_id __rte_unused,
382                         unsigned flags __rte_unused)
383 {
384         rte_errno = EINVAL;
385         return NULL;
386 }
387 #endif
388
389 /* create the mempool */
390 struct rte_mempool *
391 rte_mempool_create(const char *name, unsigned n, unsigned elt_size,
392                    unsigned cache_size, unsigned private_data_size,
393                    rte_mempool_ctor_t *mp_init, void *mp_init_arg,
394                    rte_mempool_obj_ctor_t *obj_init, void *obj_init_arg,
395                    int socket_id, unsigned flags)
396 {
397         if (rte_xen_dom0_supported())
398                 return rte_dom0_mempool_create(name, n, elt_size,
399                                                cache_size, private_data_size,
400                                                mp_init, mp_init_arg,
401                                                obj_init, obj_init_arg,
402                                                socket_id, flags);
403         else
404                 return rte_mempool_xmem_create(name, n, elt_size,
405                                                cache_size, private_data_size,
406                                                mp_init, mp_init_arg,
407                                                obj_init, obj_init_arg,
408                                                socket_id, flags,
409                                                NULL, NULL, MEMPOOL_PG_NUM_DEFAULT,
410                                                MEMPOOL_PG_SHIFT_MAX);
411 }
412
413 /* create the internal ring */
414 static int
415 rte_mempool_ring_create(struct rte_mempool *mp)
416 {
417         int rg_flags = 0;
418         char rg_name[RTE_RING_NAMESIZE];
419         struct rte_ring *r;
420
421         snprintf(rg_name, sizeof(rg_name), RTE_MEMPOOL_MZ_FORMAT, mp->name);
422
423         /* ring flags */
424         if (mp->flags & MEMPOOL_F_SP_PUT)
425                 rg_flags |= RING_F_SP_ENQ;
426         if (mp->flags & MEMPOOL_F_SC_GET)
427                 rg_flags |= RING_F_SC_DEQ;
428
429         /* Allocate the ring that will be used to store objects.
430          * Ring functions will return appropriate errors if we are
431          * running as a secondary process etc., so no checks made
432          * in this function for that condition.
433          */
434         r = rte_ring_create(rg_name, rte_align32pow2(mp->size + 1),
435                 mp->socket_id, rg_flags);
436         if (r == NULL)
437                 return -rte_errno;
438
439         mp->ring = r;
440         return 0;
441 }
442
443 /* Free memory chunks used by a mempool. Objects must be in pool */
444 static void
445 rte_mempool_free_memchunks(struct rte_mempool *mp)
446 {
447         struct rte_mempool_memhdr *memhdr;
448         void *elt;
449
450         while (!STAILQ_EMPTY(&mp->elt_list)) {
451                 rte_ring_sc_dequeue(mp->ring, &elt);
452                 (void)elt;
453                 STAILQ_REMOVE_HEAD(&mp->elt_list, next);
454                 mp->populated_size--;
455         }
456
457         while (!STAILQ_EMPTY(&mp->mem_list)) {
458                 memhdr = STAILQ_FIRST(&mp->mem_list);
459                 STAILQ_REMOVE_HEAD(&mp->mem_list, next);
460                 rte_free(memhdr);
461                 mp->nb_mem_chunks--;
462         }
463 }
464
465 /* Add objects in the pool, using a physically contiguous memory
466  * zone. Return the number of objects added, or a negative value
467  * on error.
468  */
469 static int
470 rte_mempool_populate_phys(struct rte_mempool *mp, char *vaddr,
471         phys_addr_t paddr, size_t len)
472 {
473         unsigned total_elt_sz;
474         unsigned i = 0;
475         size_t off;
476         struct rte_mempool_memhdr *memhdr;
477
478         /* mempool is already populated */
479         if (mp->populated_size >= mp->size)
480                 return -ENOSPC;
481
482         total_elt_sz = mp->header_size + mp->elt_size + mp->trailer_size;
483
484         memhdr = rte_zmalloc("MEMPOOL_MEMHDR", sizeof(*memhdr), 0);
485         if (memhdr == NULL)
486                 return -ENOMEM;
487
488         memhdr->mp = mp;
489         memhdr->addr = vaddr;
490         memhdr->phys_addr = paddr;
491         memhdr->len = len;
492
493         if (mp->flags & MEMPOOL_F_NO_CACHE_ALIGN)
494                 off = RTE_PTR_ALIGN_CEIL(vaddr, 8) - vaddr;
495         else
496                 off = RTE_PTR_ALIGN_CEIL(vaddr, RTE_CACHE_LINE_SIZE) - vaddr;
497
498         while (off + total_elt_sz <= len && mp->populated_size < mp->size) {
499                 off += mp->header_size;
500                 mempool_add_elem(mp, (char *)vaddr + off, paddr + off);
501                 off += mp->elt_size + mp->trailer_size;
502                 i++;
503         }
504
505         /* not enough room to store one object */
506         if (i == 0)
507                 return -EINVAL;
508
509         STAILQ_INSERT_TAIL(&mp->mem_list, memhdr, next);
510         mp->nb_mem_chunks++;
511         return i;
512 }
513
514 /* Add objects in the pool, using a table of physical pages. Return the
515  * number of objects added, or a negative value on error.
516  */
517 static int
518 rte_mempool_populate_phys_tab(struct rte_mempool *mp, char *vaddr,
519         const phys_addr_t paddr[], uint32_t pg_num, uint32_t pg_shift)
520 {
521         uint32_t i, n;
522         int ret, cnt = 0;
523         size_t pg_sz = (size_t)1 << pg_shift;
524
525         /* mempool must not be populated */
526         if (mp->nb_mem_chunks != 0)
527                 return -EEXIST;
528
529         for (i = 0; i < pg_num && mp->populated_size < mp->size; i += n) {
530
531                 /* populate with the largest group of contiguous pages */
532                 for (n = 1; (i + n) < pg_num &&
533                              paddr[i] + pg_sz == paddr[i+n]; n++)
534                         ;
535
536                 ret = rte_mempool_populate_phys(mp, vaddr + i * pg_sz,
537                         paddr[i], n * pg_sz);
538                 if (ret < 0) {
539                         rte_mempool_free_memchunks(mp);
540                         return ret;
541                 }
542                 cnt += ret;
543         }
544         return cnt;
545 }
546
547 /*
548  * Create the mempool over already allocated chunk of memory.
549  * That external memory buffer can consists of physically disjoint pages.
550  * Setting vaddr to NULL, makes mempool to fallback to original behaviour
551  * and allocate space for mempool and it's elements as one big chunk of
552  * physically continuos memory.
553  * */
554 struct rte_mempool *
555 rte_mempool_xmem_create(const char *name, unsigned n, unsigned elt_size,
556                 unsigned cache_size, unsigned private_data_size,
557                 rte_mempool_ctor_t *mp_init, void *mp_init_arg,
558                 rte_mempool_obj_cb_t *obj_init, void *obj_init_arg,
559                 int socket_id, unsigned flags, void *vaddr,
560                 const phys_addr_t paddr[], uint32_t pg_num, uint32_t pg_shift)
561 {
562         char mz_name[RTE_MEMZONE_NAMESIZE];
563         struct rte_mempool_list *mempool_list;
564         struct rte_mempool *mp = NULL;
565         struct rte_tailq_entry *te = NULL;
566         const struct rte_memzone *mz;
567         size_t mempool_size;
568         int mz_flags = RTE_MEMZONE_1GB|RTE_MEMZONE_SIZE_HINT_ONLY;
569         void *obj;
570         struct rte_mempool_objsz objsz;
571         void *startaddr;
572         int page_size = getpagesize();
573         int ret;
574
575         /* compilation-time checks */
576         RTE_BUILD_BUG_ON((sizeof(struct rte_mempool) &
577                           RTE_CACHE_LINE_MASK) != 0);
578         RTE_BUILD_BUG_ON((sizeof(struct rte_mempool_cache) &
579                           RTE_CACHE_LINE_MASK) != 0);
580 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
581         RTE_BUILD_BUG_ON((sizeof(struct rte_mempool_debug_stats) &
582                           RTE_CACHE_LINE_MASK) != 0);
583         RTE_BUILD_BUG_ON((offsetof(struct rte_mempool, stats) &
584                           RTE_CACHE_LINE_MASK) != 0);
585 #endif
586
587         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
588
589         /* asked cache too big */
590         if (cache_size > RTE_MEMPOOL_CACHE_MAX_SIZE ||
591             CALC_CACHE_FLUSHTHRESH(cache_size) > n) {
592                 rte_errno = EINVAL;
593                 return NULL;
594         }
595
596         /* check that we have both VA and PA */
597         if (vaddr != NULL && paddr == NULL) {
598                 rte_errno = EINVAL;
599                 return NULL;
600         }
601
602         /* Check that pg_num and pg_shift parameters are valid. */
603         if (pg_num == 0 || pg_shift > MEMPOOL_PG_SHIFT_MAX) {
604                 rte_errno = EINVAL;
605                 return NULL;
606         }
607
608         /* "no cache align" imply "no spread" */
609         if (flags & MEMPOOL_F_NO_CACHE_ALIGN)
610                 flags |= MEMPOOL_F_NO_SPREAD;
611
612         /* calculate mempool object sizes. */
613         if (!rte_mempool_calc_obj_size(elt_size, flags, &objsz)) {
614                 rte_errno = EINVAL;
615                 return NULL;
616         }
617
618         rte_rwlock_write_lock(RTE_EAL_MEMPOOL_RWLOCK);
619
620         /*
621          * reserve a memory zone for this mempool: private data is
622          * cache-aligned
623          */
624         private_data_size = (private_data_size +
625                              RTE_MEMPOOL_ALIGN_MASK) & (~RTE_MEMPOOL_ALIGN_MASK);
626
627         if (! rte_eal_has_hugepages()) {
628                 /*
629                  * expand private data size to a whole page, so that the
630                  * first pool element will start on a new standard page
631                  */
632                 int head = sizeof(struct rte_mempool);
633                 int new_size = (private_data_size + head) % page_size;
634                 if (new_size)
635                         private_data_size += page_size - new_size;
636         }
637
638         /* try to allocate tailq entry */
639         te = rte_zmalloc("MEMPOOL_TAILQ_ENTRY", sizeof(*te), 0);
640         if (te == NULL) {
641                 RTE_LOG(ERR, MEMPOOL, "Cannot allocate tailq entry!\n");
642                 goto exit_unlock;
643         }
644
645         /*
646          * If user provided an external memory buffer, then use it to
647          * store mempool objects. Otherwise reserve a memzone that is large
648          * enough to hold mempool header and metadata plus mempool objects.
649          */
650         mempool_size = MEMPOOL_HEADER_SIZE(mp, cache_size);
651         mempool_size += private_data_size;
652         mempool_size = RTE_ALIGN_CEIL(mempool_size, RTE_MEMPOOL_ALIGN);
653         if (vaddr == NULL)
654                 mempool_size += (size_t)objsz.total_size * n;
655
656         if (! rte_eal_has_hugepages()) {
657                 /*
658                  * we want the memory pool to start on a page boundary,
659                  * because pool elements crossing page boundaries would
660                  * result in discontiguous physical addresses
661                  */
662                 mempool_size += page_size;
663         }
664
665         snprintf(mz_name, sizeof(mz_name), RTE_MEMPOOL_MZ_FORMAT, name);
666
667         mz = rte_memzone_reserve(mz_name, mempool_size, socket_id, mz_flags);
668         if (mz == NULL)
669                 goto exit_unlock;
670
671         if (rte_eal_has_hugepages()) {
672                 startaddr = (void*)mz->addr;
673         } else {
674                 /* align memory pool start address on a page boundary */
675                 unsigned long addr = (unsigned long)mz->addr;
676                 if (addr & (page_size - 1)) {
677                         addr += page_size;
678                         addr &= ~(page_size - 1);
679                 }
680                 startaddr = (void*)addr;
681         }
682
683         /* init the mempool structure */
684         mp = startaddr;
685         memset(mp, 0, sizeof(*mp));
686         snprintf(mp->name, sizeof(mp->name), "%s", name);
687         mp->phys_addr = mz->phys_addr;
688         mp->socket_id = socket_id;
689         mp->size = n;
690         mp->flags = flags;
691         mp->elt_size = objsz.elt_size;
692         mp->header_size = objsz.header_size;
693         mp->trailer_size = objsz.trailer_size;
694         mp->cache_size = cache_size;
695         mp->cache_flushthresh = CALC_CACHE_FLUSHTHRESH(cache_size);
696         mp->private_data_size = private_data_size;
697         STAILQ_INIT(&mp->elt_list);
698         STAILQ_INIT(&mp->mem_list);
699
700         if (rte_mempool_ring_create(mp) < 0)
701                 goto exit_unlock;
702
703         /*
704          * local_cache pointer is set even if cache_size is zero.
705          * The local_cache points to just past the elt_pa[] array.
706          */
707         mp->local_cache = (struct rte_mempool_cache *)
708                 RTE_PTR_ADD(mp, MEMPOOL_HEADER_SIZE(mp, 0));
709
710         /* call the initializer */
711         if (mp_init)
712                 mp_init(mp, mp_init_arg);
713
714         /* mempool elements allocated together with mempool */
715         if (vaddr == NULL) {
716                 /* calculate address of the first elt for continuous mempool. */
717                 obj = (char *)mp + MEMPOOL_HEADER_SIZE(mp, cache_size) +
718                         private_data_size;
719                 obj = RTE_PTR_ALIGN_CEIL(obj, RTE_MEMPOOL_ALIGN);
720
721                 ret = rte_mempool_populate_phys(mp, obj,
722                         mp->phys_addr + ((char *)obj - (char *)mp),
723                         objsz.total_size * n);
724                 if (ret != (int)mp->size)
725                         goto exit_unlock;
726         } else {
727                 ret = rte_mempool_populate_phys_tab(mp, vaddr,
728                         paddr, pg_num, pg_shift);
729                 if (ret != (int)mp->size)
730                         goto exit_unlock;
731         }
732
733         /* call the initializer */
734         if (obj_init)
735                 rte_mempool_obj_iter(mp, obj_init, obj_init_arg);
736
737         te->data = (void *) mp;
738
739         rte_rwlock_write_lock(RTE_EAL_TAILQ_RWLOCK);
740         TAILQ_INSERT_TAIL(mempool_list, te, next);
741         rte_rwlock_write_unlock(RTE_EAL_TAILQ_RWLOCK);
742         rte_rwlock_write_unlock(RTE_EAL_MEMPOOL_RWLOCK);
743
744         return mp;
745
746 exit_unlock:
747         rte_rwlock_write_unlock(RTE_EAL_MEMPOOL_RWLOCK);
748         if (mp != NULL) {
749                 rte_mempool_free_memchunks(mp);
750                 rte_ring_free(mp->ring);
751         }
752         rte_free(te);
753
754         return NULL;
755 }
756
757 /* Return the number of entries in the mempool */
758 unsigned
759 rte_mempool_count(const struct rte_mempool *mp)
760 {
761         unsigned count;
762         unsigned lcore_id;
763
764         count = rte_ring_count(mp->ring);
765
766         if (mp->cache_size == 0)
767                 return count;
768
769         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++)
770                 count += mp->local_cache[lcore_id].len;
771
772         /*
773          * due to race condition (access to len is not locked), the
774          * total can be greater than size... so fix the result
775          */
776         if (count > mp->size)
777                 return mp->size;
778         return count;
779 }
780
781 /* dump the cache status */
782 static unsigned
783 rte_mempool_dump_cache(FILE *f, const struct rte_mempool *mp)
784 {
785         unsigned lcore_id;
786         unsigned count = 0;
787         unsigned cache_count;
788
789         fprintf(f, "  cache infos:\n");
790         fprintf(f, "    cache_size=%"PRIu32"\n", mp->cache_size);
791
792         if (mp->cache_size == 0)
793                 return count;
794
795         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
796                 cache_count = mp->local_cache[lcore_id].len;
797                 fprintf(f, "    cache_count[%u]=%u\n", lcore_id, cache_count);
798                 count += cache_count;
799         }
800         fprintf(f, "    total_cache_count=%u\n", count);
801         return count;
802 }
803
804 #ifndef __INTEL_COMPILER
805 #pragma GCC diagnostic ignored "-Wcast-qual"
806 #endif
807
808 /* check and update cookies or panic (internal) */
809 void rte_mempool_check_cookies(const struct rte_mempool *mp,
810         void * const *obj_table_const, unsigned n, int free)
811 {
812 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
813         struct rte_mempool_objhdr *hdr;
814         struct rte_mempool_objtlr *tlr;
815         uint64_t cookie;
816         void *tmp;
817         void *obj;
818         void **obj_table;
819
820         /* Force to drop the "const" attribute. This is done only when
821          * DEBUG is enabled */
822         tmp = (void *) obj_table_const;
823         obj_table = (void **) tmp;
824
825         while (n--) {
826                 obj = obj_table[n];
827
828                 if (rte_mempool_from_obj(obj) != mp)
829                         rte_panic("MEMPOOL: object is owned by another "
830                                   "mempool\n");
831
832                 hdr = __mempool_get_header(obj);
833                 cookie = hdr->cookie;
834
835                 if (free == 0) {
836                         if (cookie != RTE_MEMPOOL_HEADER_COOKIE1) {
837                                 rte_log_set_history(0);
838                                 RTE_LOG(CRIT, MEMPOOL,
839                                         "obj=%p, mempool=%p, cookie=%" PRIx64 "\n",
840                                         obj, (const void *) mp, cookie);
841                                 rte_panic("MEMPOOL: bad header cookie (put)\n");
842                         }
843                         hdr->cookie = RTE_MEMPOOL_HEADER_COOKIE2;
844                 } else if (free == 1) {
845                         if (cookie != RTE_MEMPOOL_HEADER_COOKIE2) {
846                                 rte_log_set_history(0);
847                                 RTE_LOG(CRIT, MEMPOOL,
848                                         "obj=%p, mempool=%p, cookie=%" PRIx64 "\n",
849                                         obj, (const void *) mp, cookie);
850                                 rte_panic("MEMPOOL: bad header cookie (get)\n");
851                         }
852                         hdr->cookie = RTE_MEMPOOL_HEADER_COOKIE1;
853                 } else if (free == 2) {
854                         if (cookie != RTE_MEMPOOL_HEADER_COOKIE1 &&
855                             cookie != RTE_MEMPOOL_HEADER_COOKIE2) {
856                                 rte_log_set_history(0);
857                                 RTE_LOG(CRIT, MEMPOOL,
858                                         "obj=%p, mempool=%p, cookie=%" PRIx64 "\n",
859                                         obj, (const void *) mp, cookie);
860                                 rte_panic("MEMPOOL: bad header cookie (audit)\n");
861                         }
862                 }
863                 tlr = __mempool_get_trailer(obj);
864                 cookie = tlr->cookie;
865                 if (cookie != RTE_MEMPOOL_TRAILER_COOKIE) {
866                         rte_log_set_history(0);
867                         RTE_LOG(CRIT, MEMPOOL,
868                                 "obj=%p, mempool=%p, cookie=%" PRIx64 "\n",
869                                 obj, (const void *) mp, cookie);
870                         rte_panic("MEMPOOL: bad trailer cookie\n");
871                 }
872         }
873 #else
874         RTE_SET_USED(mp);
875         RTE_SET_USED(obj_table_const);
876         RTE_SET_USED(n);
877         RTE_SET_USED(free);
878 #endif
879 }
880
881 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
882 static void
883 mempool_obj_audit(struct rte_mempool *mp, __rte_unused void *opaque,
884         void *obj, __rte_unused unsigned idx)
885 {
886         __mempool_check_cookies(mp, &obj, 1, 2);
887 }
888
889 static void
890 mempool_audit_cookies(struct rte_mempool *mp)
891 {
892         unsigned num;
893
894         num = rte_mempool_obj_iter(mp, mempool_obj_audit, NULL);
895         if (num != mp->size) {
896                 rte_panic("rte_mempool_obj_iter(mempool=%p, size=%u) "
897                         "iterated only over %u elements\n",
898                         mp, mp->size, num);
899         }
900 }
901 #else
902 #define mempool_audit_cookies(mp) do {} while(0)
903 #endif
904
905 #ifndef __INTEL_COMPILER
906 #pragma GCC diagnostic error "-Wcast-qual"
907 #endif
908
909 /* check cookies before and after objects */
910 static void
911 mempool_audit_cache(const struct rte_mempool *mp)
912 {
913         /* check cache size consistency */
914         unsigned lcore_id;
915
916         if (mp->cache_size == 0)
917                 return;
918
919         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
920                 if (mp->local_cache[lcore_id].len > mp->cache_flushthresh) {
921                         RTE_LOG(CRIT, MEMPOOL, "badness on cache[%u]\n",
922                                 lcore_id);
923                         rte_panic("MEMPOOL: invalid cache len\n");
924                 }
925         }
926 }
927
928 /* check the consistency of mempool (size, cookies, ...) */
929 void
930 rte_mempool_audit(struct rte_mempool *mp)
931 {
932         mempool_audit_cache(mp);
933         mempool_audit_cookies(mp);
934
935         /* For case where mempool DEBUG is not set, and cache size is 0 */
936         RTE_SET_USED(mp);
937 }
938
939 /* dump the status of the mempool on the console */
940 void
941 rte_mempool_dump(FILE *f, struct rte_mempool *mp)
942 {
943 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
944         struct rte_mempool_debug_stats sum;
945         unsigned lcore_id;
946 #endif
947         struct rte_mempool_memhdr *memhdr;
948         unsigned common_count;
949         unsigned cache_count;
950         size_t mem_len = 0;
951
952         RTE_ASSERT(f != NULL);
953         RTE_ASSERT(mp != NULL);
954
955         fprintf(f, "mempool <%s>@%p\n", mp->name, mp);
956         fprintf(f, "  flags=%x\n", mp->flags);
957         fprintf(f, "  ring=<%s>@%p\n", mp->ring->name, mp->ring);
958         fprintf(f, "  phys_addr=0x%" PRIx64 "\n", mp->phys_addr);
959         fprintf(f, "  nb_mem_chunks=%u\n", mp->nb_mem_chunks);
960         fprintf(f, "  size=%"PRIu32"\n", mp->size);
961         fprintf(f, "  populated_size=%"PRIu32"\n", mp->populated_size);
962         fprintf(f, "  header_size=%"PRIu32"\n", mp->header_size);
963         fprintf(f, "  elt_size=%"PRIu32"\n", mp->elt_size);
964         fprintf(f, "  trailer_size=%"PRIu32"\n", mp->trailer_size);
965         fprintf(f, "  total_obj_size=%"PRIu32"\n",
966                mp->header_size + mp->elt_size + mp->trailer_size);
967
968         fprintf(f, "  private_data_size=%"PRIu32"\n", mp->private_data_size);
969
970         STAILQ_FOREACH(memhdr, &mp->mem_list, next)
971                 mem_len += memhdr->len;
972         if (mem_len != 0) {
973                 fprintf(f, "  avg bytes/object=%#Lf\n",
974                         (long double)mem_len / mp->size);
975         }
976
977         cache_count = rte_mempool_dump_cache(f, mp);
978         common_count = rte_ring_count(mp->ring);
979         if ((cache_count + common_count) > mp->size)
980                 common_count = mp->size - cache_count;
981         fprintf(f, "  common_pool_count=%u\n", common_count);
982
983         /* sum and dump statistics */
984 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
985         memset(&sum, 0, sizeof(sum));
986         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
987                 sum.put_bulk += mp->stats[lcore_id].put_bulk;
988                 sum.put_objs += mp->stats[lcore_id].put_objs;
989                 sum.get_success_bulk += mp->stats[lcore_id].get_success_bulk;
990                 sum.get_success_objs += mp->stats[lcore_id].get_success_objs;
991                 sum.get_fail_bulk += mp->stats[lcore_id].get_fail_bulk;
992                 sum.get_fail_objs += mp->stats[lcore_id].get_fail_objs;
993         }
994         fprintf(f, "  stats:\n");
995         fprintf(f, "    put_bulk=%"PRIu64"\n", sum.put_bulk);
996         fprintf(f, "    put_objs=%"PRIu64"\n", sum.put_objs);
997         fprintf(f, "    get_success_bulk=%"PRIu64"\n", sum.get_success_bulk);
998         fprintf(f, "    get_success_objs=%"PRIu64"\n", sum.get_success_objs);
999         fprintf(f, "    get_fail_bulk=%"PRIu64"\n", sum.get_fail_bulk);
1000         fprintf(f, "    get_fail_objs=%"PRIu64"\n", sum.get_fail_objs);
1001 #else
1002         fprintf(f, "  no statistics available\n");
1003 #endif
1004
1005         rte_mempool_audit(mp);
1006 }
1007
1008 /* dump the status of all mempools on the console */
1009 void
1010 rte_mempool_list_dump(FILE *f)
1011 {
1012         struct rte_mempool *mp = NULL;
1013         struct rte_tailq_entry *te;
1014         struct rte_mempool_list *mempool_list;
1015
1016         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
1017
1018         rte_rwlock_read_lock(RTE_EAL_MEMPOOL_RWLOCK);
1019
1020         TAILQ_FOREACH(te, mempool_list, next) {
1021                 mp = (struct rte_mempool *) te->data;
1022                 rte_mempool_dump(f, mp);
1023         }
1024
1025         rte_rwlock_read_unlock(RTE_EAL_MEMPOOL_RWLOCK);
1026 }
1027
1028 /* search a mempool from its name */
1029 struct rte_mempool *
1030 rte_mempool_lookup(const char *name)
1031 {
1032         struct rte_mempool *mp = NULL;
1033         struct rte_tailq_entry *te;
1034         struct rte_mempool_list *mempool_list;
1035
1036         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
1037
1038         rte_rwlock_read_lock(RTE_EAL_MEMPOOL_RWLOCK);
1039
1040         TAILQ_FOREACH(te, mempool_list, next) {
1041                 mp = (struct rte_mempool *) te->data;
1042                 if (strncmp(name, mp->name, RTE_MEMPOOL_NAMESIZE) == 0)
1043                         break;
1044         }
1045
1046         rte_rwlock_read_unlock(RTE_EAL_MEMPOOL_RWLOCK);
1047
1048         if (te == NULL) {
1049                 rte_errno = ENOENT;
1050                 return NULL;
1051         }
1052
1053         return mp;
1054 }
1055
1056 void rte_mempool_walk(void (*func)(struct rte_mempool *, void *),
1057                       void *arg)
1058 {
1059         struct rte_tailq_entry *te = NULL;
1060         struct rte_mempool_list *mempool_list;
1061
1062         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
1063
1064         rte_rwlock_read_lock(RTE_EAL_MEMPOOL_RWLOCK);
1065
1066         TAILQ_FOREACH(te, mempool_list, next) {
1067                 (*func)((struct rte_mempool *) te->data, arg);
1068         }
1069
1070         rte_rwlock_read_unlock(RTE_EAL_MEMPOOL_RWLOCK);
1071 }