mempool: allocate in several memory chunks by default
[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 static void
131 mempool_add_elem(struct rte_mempool *mp, void *obj, phys_addr_t physaddr)
132 {
133         struct rte_mempool_objhdr *hdr;
134         struct rte_mempool_objtlr *tlr __rte_unused;
135
136         /* set mempool ptr in header */
137         hdr = RTE_PTR_SUB(obj, sizeof(*hdr));
138         hdr->mp = mp;
139         hdr->physaddr = physaddr;
140         STAILQ_INSERT_TAIL(&mp->elt_list, hdr, next);
141         mp->populated_size++;
142
143 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
144         hdr->cookie = RTE_MEMPOOL_HEADER_COOKIE2;
145         tlr = __mempool_get_trailer(obj);
146         tlr->cookie = RTE_MEMPOOL_TRAILER_COOKIE;
147 #endif
148
149         /* enqueue in ring */
150         rte_ring_sp_enqueue(mp->ring, obj);
151 }
152
153 /* call obj_cb() for each mempool element */
154 uint32_t
155 rte_mempool_obj_iter(struct rte_mempool *mp,
156         rte_mempool_obj_cb_t *obj_cb, void *obj_cb_arg)
157 {
158         struct rte_mempool_objhdr *hdr;
159         void *obj;
160         unsigned n = 0;
161
162         STAILQ_FOREACH(hdr, &mp->elt_list, next) {
163                 obj = (char *)hdr + sizeof(*hdr);
164                 obj_cb(mp, obj_cb_arg, obj, n);
165                 n++;
166         }
167
168         return n;
169 }
170
171 /* call mem_cb() for each mempool memory chunk */
172 uint32_t
173 rte_mempool_mem_iter(struct rte_mempool *mp,
174         rte_mempool_mem_cb_t *mem_cb, void *mem_cb_arg)
175 {
176         struct rte_mempool_memhdr *hdr;
177         unsigned n = 0;
178
179         STAILQ_FOREACH(hdr, &mp->mem_list, next) {
180                 mem_cb(mp, mem_cb_arg, hdr, n);
181                 n++;
182         }
183
184         return n;
185 }
186
187 /* get the header, trailer and total size of a mempool element. */
188 uint32_t
189 rte_mempool_calc_obj_size(uint32_t elt_size, uint32_t flags,
190         struct rte_mempool_objsz *sz)
191 {
192         struct rte_mempool_objsz lsz;
193
194         sz = (sz != NULL) ? sz : &lsz;
195
196         sz->header_size = sizeof(struct rte_mempool_objhdr);
197         if ((flags & MEMPOOL_F_NO_CACHE_ALIGN) == 0)
198                 sz->header_size = RTE_ALIGN_CEIL(sz->header_size,
199                         RTE_MEMPOOL_ALIGN);
200
201         sz->trailer_size = sizeof(struct rte_mempool_objtlr);
202
203         /* element size is 8 bytes-aligned at least */
204         sz->elt_size = RTE_ALIGN_CEIL(elt_size, sizeof(uint64_t));
205
206         /* expand trailer to next cache line */
207         if ((flags & MEMPOOL_F_NO_CACHE_ALIGN) == 0) {
208                 sz->total_size = sz->header_size + sz->elt_size +
209                         sz->trailer_size;
210                 sz->trailer_size += ((RTE_MEMPOOL_ALIGN -
211                                   (sz->total_size & RTE_MEMPOOL_ALIGN_MASK)) &
212                                  RTE_MEMPOOL_ALIGN_MASK);
213         }
214
215         /*
216          * increase trailer to add padding between objects in order to
217          * spread them across memory channels/ranks
218          */
219         if ((flags & MEMPOOL_F_NO_SPREAD) == 0) {
220                 unsigned new_size;
221                 new_size = optimize_object_size(sz->header_size + sz->elt_size +
222                         sz->trailer_size);
223                 sz->trailer_size = new_size - sz->header_size - sz->elt_size;
224         }
225
226         if (! rte_eal_has_hugepages()) {
227                 /*
228                  * compute trailer size so that pool elements fit exactly in
229                  * a standard page
230                  */
231                 int page_size = getpagesize();
232                 int new_size = page_size - sz->header_size - sz->elt_size;
233                 if (new_size < 0 || (unsigned int)new_size < sz->trailer_size) {
234                         printf("When hugepages are disabled, pool objects "
235                                "can't exceed PAGE_SIZE: %d + %d + %d > %d\n",
236                                sz->header_size, sz->elt_size, sz->trailer_size,
237                                page_size);
238                         return 0;
239                 }
240                 sz->trailer_size = new_size;
241         }
242
243         /* this is the size of an object, including header and trailer */
244         sz->total_size = sz->header_size + sz->elt_size + sz->trailer_size;
245
246         return sz->total_size;
247 }
248
249
250 /*
251  * Calculate maximum amount of memory required to store given number of objects.
252  */
253 size_t
254 rte_mempool_xmem_size(uint32_t elt_num, size_t total_elt_sz, uint32_t pg_shift)
255 {
256         size_t obj_per_page, pg_num, pg_sz;
257
258         if (pg_shift == 0)
259                 return total_elt_sz * elt_num;
260
261         pg_sz = (size_t)1 << pg_shift;
262         obj_per_page = pg_sz / total_elt_sz;
263         if (obj_per_page == 0)
264                 return RTE_ALIGN_CEIL(total_elt_sz, pg_sz) * elt_num;
265
266         pg_num = (elt_num + obj_per_page - 1) / obj_per_page;
267         return pg_num << pg_shift;
268 }
269
270 /*
271  * Calculate how much memory would be actually required with the
272  * given memory footprint to store required number of elements.
273  */
274 ssize_t
275 rte_mempool_xmem_usage(__rte_unused void *vaddr, uint32_t elt_num,
276         size_t total_elt_sz, const phys_addr_t paddr[], uint32_t pg_num,
277         uint32_t pg_shift)
278 {
279         uint32_t elt_cnt = 0;
280         phys_addr_t start, end;
281         uint32_t paddr_idx;
282         size_t pg_sz = (size_t)1 << pg_shift;
283
284         /* if paddr is NULL, assume contiguous memory */
285         if (paddr == NULL) {
286                 start = 0;
287                 end = pg_sz * pg_num;
288                 paddr_idx = pg_num;
289         } else {
290                 start = paddr[0];
291                 end = paddr[0] + pg_sz;
292                 paddr_idx = 1;
293         }
294         while (elt_cnt < elt_num) {
295
296                 if (end - start >= total_elt_sz) {
297                         /* enough contiguous memory, add an object */
298                         start += total_elt_sz;
299                         elt_cnt++;
300                 } else if (paddr_idx < pg_num) {
301                         /* no room to store one obj, add a page */
302                         if (end == paddr[paddr_idx]) {
303                                 end += pg_sz;
304                         } else {
305                                 start = paddr[paddr_idx];
306                                 end = paddr[paddr_idx] + pg_sz;
307                         }
308                         paddr_idx++;
309
310                 } else {
311                         /* no more page, return how many elements fit */
312                         return -(size_t)elt_cnt;
313                 }
314         }
315
316         return (size_t)paddr_idx << pg_shift;
317 }
318
319 #ifndef RTE_LIBRTE_XEN_DOM0
320 /* stub if DOM0 support not configured */
321 struct rte_mempool *
322 rte_dom0_mempool_create(const char *name __rte_unused,
323                         unsigned n __rte_unused,
324                         unsigned elt_size __rte_unused,
325                         unsigned cache_size __rte_unused,
326                         unsigned private_data_size __rte_unused,
327                         rte_mempool_ctor_t *mp_init __rte_unused,
328                         void *mp_init_arg __rte_unused,
329                         rte_mempool_obj_ctor_t *obj_init __rte_unused,
330                         void *obj_init_arg __rte_unused,
331                         int socket_id __rte_unused,
332                         unsigned flags __rte_unused)
333 {
334         rte_errno = EINVAL;
335         return NULL;
336 }
337 #endif
338
339 /* create the mempool */
340 struct rte_mempool *
341 rte_mempool_create(const char *name, unsigned n, unsigned elt_size,
342                    unsigned cache_size, unsigned private_data_size,
343                    rte_mempool_ctor_t *mp_init, void *mp_init_arg,
344                    rte_mempool_obj_ctor_t *obj_init, void *obj_init_arg,
345                    int socket_id, unsigned flags)
346 {
347         if (rte_xen_dom0_supported())
348                 return rte_dom0_mempool_create(name, n, elt_size,
349                                                cache_size, private_data_size,
350                                                mp_init, mp_init_arg,
351                                                obj_init, obj_init_arg,
352                                                socket_id, flags);
353         else
354                 return rte_mempool_xmem_create(name, n, elt_size,
355                                                cache_size, private_data_size,
356                                                mp_init, mp_init_arg,
357                                                obj_init, obj_init_arg,
358                                                socket_id, flags,
359                                                NULL, NULL, MEMPOOL_PG_NUM_DEFAULT,
360                                                MEMPOOL_PG_SHIFT_MAX);
361 }
362
363 /* create the internal ring */
364 static int
365 rte_mempool_ring_create(struct rte_mempool *mp)
366 {
367         int rg_flags = 0;
368         char rg_name[RTE_RING_NAMESIZE];
369         struct rte_ring *r;
370
371         snprintf(rg_name, sizeof(rg_name), RTE_MEMPOOL_MZ_FORMAT, mp->name);
372
373         /* ring flags */
374         if (mp->flags & MEMPOOL_F_SP_PUT)
375                 rg_flags |= RING_F_SP_ENQ;
376         if (mp->flags & MEMPOOL_F_SC_GET)
377                 rg_flags |= RING_F_SC_DEQ;
378
379         /* Allocate the ring that will be used to store objects.
380          * Ring functions will return appropriate errors if we are
381          * running as a secondary process etc., so no checks made
382          * in this function for that condition.
383          */
384         r = rte_ring_create(rg_name, rte_align32pow2(mp->size + 1),
385                 mp->socket_id, rg_flags);
386         if (r == NULL)
387                 return -rte_errno;
388
389         mp->ring = r;
390         return 0;
391 }
392
393 /* free a memchunk allocated with rte_memzone_reserve() */
394 static void
395 rte_mempool_memchunk_mz_free(__rte_unused struct rte_mempool_memhdr *memhdr,
396         void *opaque)
397 {
398         const struct rte_memzone *mz = opaque;
399         rte_memzone_free(mz);
400 }
401
402 /* Free memory chunks used by a mempool. Objects must be in pool */
403 static void
404 rte_mempool_free_memchunks(struct rte_mempool *mp)
405 {
406         struct rte_mempool_memhdr *memhdr;
407         void *elt;
408
409         while (!STAILQ_EMPTY(&mp->elt_list)) {
410                 rte_ring_sc_dequeue(mp->ring, &elt);
411                 (void)elt;
412                 STAILQ_REMOVE_HEAD(&mp->elt_list, next);
413                 mp->populated_size--;
414         }
415
416         while (!STAILQ_EMPTY(&mp->mem_list)) {
417                 memhdr = STAILQ_FIRST(&mp->mem_list);
418                 STAILQ_REMOVE_HEAD(&mp->mem_list, next);
419                 if (memhdr->free_cb != NULL)
420                         memhdr->free_cb(memhdr, memhdr->opaque);
421                 rte_free(memhdr);
422                 mp->nb_mem_chunks--;
423         }
424 }
425
426 /* Add objects in the pool, using a physically contiguous memory
427  * zone. Return the number of objects added, or a negative value
428  * on error.
429  */
430 static int
431 rte_mempool_populate_phys(struct rte_mempool *mp, char *vaddr,
432         phys_addr_t paddr, size_t len, rte_mempool_memchunk_free_cb_t *free_cb,
433         void *opaque)
434 {
435         unsigned total_elt_sz;
436         unsigned i = 0;
437         size_t off;
438         struct rte_mempool_memhdr *memhdr;
439
440         /* mempool is already populated */
441         if (mp->populated_size >= mp->size)
442                 return -ENOSPC;
443
444         total_elt_sz = mp->header_size + mp->elt_size + mp->trailer_size;
445
446         memhdr = rte_zmalloc("MEMPOOL_MEMHDR", sizeof(*memhdr), 0);
447         if (memhdr == NULL)
448                 return -ENOMEM;
449
450         memhdr->mp = mp;
451         memhdr->addr = vaddr;
452         memhdr->phys_addr = paddr;
453         memhdr->len = len;
454         memhdr->free_cb = free_cb;
455         memhdr->opaque = opaque;
456
457         if (mp->flags & MEMPOOL_F_NO_CACHE_ALIGN)
458                 off = RTE_PTR_ALIGN_CEIL(vaddr, 8) - vaddr;
459         else
460                 off = RTE_PTR_ALIGN_CEIL(vaddr, RTE_CACHE_LINE_SIZE) - vaddr;
461
462         while (off + total_elt_sz <= len && mp->populated_size < mp->size) {
463                 off += mp->header_size;
464                 mempool_add_elem(mp, (char *)vaddr + off, paddr + off);
465                 off += mp->elt_size + mp->trailer_size;
466                 i++;
467         }
468
469         /* not enough room to store one object */
470         if (i == 0)
471                 return -EINVAL;
472
473         STAILQ_INSERT_TAIL(&mp->mem_list, memhdr, next);
474         mp->nb_mem_chunks++;
475         return i;
476 }
477
478 /* Add objects in the pool, using a table of physical pages. Return the
479  * number of objects added, or a negative value on error.
480  */
481 static int
482 rte_mempool_populate_phys_tab(struct rte_mempool *mp, char *vaddr,
483         const phys_addr_t paddr[], uint32_t pg_num, uint32_t pg_shift,
484         rte_mempool_memchunk_free_cb_t *free_cb, void *opaque)
485 {
486         uint32_t i, n;
487         int ret, cnt = 0;
488         size_t pg_sz = (size_t)1 << pg_shift;
489
490         /* mempool must not be populated */
491         if (mp->nb_mem_chunks != 0)
492                 return -EEXIST;
493
494         for (i = 0; i < pg_num && mp->populated_size < mp->size; i += n) {
495
496                 /* populate with the largest group of contiguous pages */
497                 for (n = 1; (i + n) < pg_num &&
498                              paddr[i] + pg_sz == paddr[i+n]; n++)
499                         ;
500
501                 ret = rte_mempool_populate_phys(mp, vaddr + i * pg_sz,
502                         paddr[i], n * pg_sz, free_cb, opaque);
503                 if (ret < 0) {
504                         rte_mempool_free_memchunks(mp);
505                         return ret;
506                 }
507                 /* no need to call the free callback for next chunks */
508                 free_cb = NULL;
509                 cnt += ret;
510         }
511         return cnt;
512 }
513
514 /* Default function to populate the mempool: allocate memory in mezones,
515  * and populate them. Return the number of objects added, or a negative
516  * value on error.
517  */
518 static int rte_mempool_populate_default(struct rte_mempool *mp)
519 {
520         int mz_flags = RTE_MEMZONE_1GB|RTE_MEMZONE_SIZE_HINT_ONLY;
521         char mz_name[RTE_MEMZONE_NAMESIZE];
522         const struct rte_memzone *mz;
523         size_t size, total_elt_sz, align;
524         unsigned mz_id, n;
525         int ret;
526
527         /* mempool must not be populated */
528         if (mp->nb_mem_chunks != 0)
529                 return -EEXIST;
530
531         align = RTE_CACHE_LINE_SIZE;
532         total_elt_sz = mp->header_size + mp->elt_size + mp->trailer_size;
533         for (mz_id = 0, n = mp->size; n > 0; mz_id++, n -= ret) {
534                 size = rte_mempool_xmem_size(n, total_elt_sz, 0);
535
536                 ret = snprintf(mz_name, sizeof(mz_name),
537                         RTE_MEMPOOL_MZ_FORMAT "_%d", mp->name, mz_id);
538                 if (ret < 0 || ret >= (int)sizeof(mz_name)) {
539                         ret = -ENAMETOOLONG;
540                         goto fail;
541                 }
542
543                 mz = rte_memzone_reserve_aligned(mz_name, size,
544                         mp->socket_id, mz_flags, align);
545                 /* not enough memory, retry with the biggest zone we have */
546                 if (mz == NULL)
547                         mz = rte_memzone_reserve_aligned(mz_name, 0,
548                                 mp->socket_id, mz_flags, align);
549                 if (mz == NULL) {
550                         ret = -rte_errno;
551                         goto fail;
552                 }
553
554                 ret = rte_mempool_populate_phys(mp, mz->addr, mz->phys_addr,
555                         mz->len, rte_mempool_memchunk_mz_free,
556                         (void *)(uintptr_t)mz);
557                 if (ret < 0)
558                         goto fail;
559         }
560
561         return mp->size;
562
563  fail:
564         rte_mempool_free_memchunks(mp);
565         return ret;
566 }
567
568 /*
569  * Create the mempool over already allocated chunk of memory.
570  * That external memory buffer can consists of physically disjoint pages.
571  * Setting vaddr to NULL, makes mempool to fallback to original behaviour
572  * and allocate space for mempool and it's elements as one big chunk of
573  * physically continuos memory.
574  * */
575 struct rte_mempool *
576 rte_mempool_xmem_create(const char *name, unsigned n, unsigned elt_size,
577                 unsigned cache_size, unsigned private_data_size,
578                 rte_mempool_ctor_t *mp_init, void *mp_init_arg,
579                 rte_mempool_obj_cb_t *obj_init, void *obj_init_arg,
580                 int socket_id, unsigned flags, void *vaddr,
581                 const phys_addr_t paddr[], uint32_t pg_num, uint32_t pg_shift)
582 {
583         char mz_name[RTE_MEMZONE_NAMESIZE];
584         struct rte_mempool_list *mempool_list;
585         struct rte_mempool *mp = NULL;
586         struct rte_tailq_entry *te = NULL;
587         const struct rte_memzone *mz = NULL;
588         size_t mempool_size;
589         int mz_flags = RTE_MEMZONE_1GB|RTE_MEMZONE_SIZE_HINT_ONLY;
590         struct rte_mempool_objsz objsz;
591         int ret;
592
593         /* compilation-time checks */
594         RTE_BUILD_BUG_ON((sizeof(struct rte_mempool) &
595                           RTE_CACHE_LINE_MASK) != 0);
596         RTE_BUILD_BUG_ON((sizeof(struct rte_mempool_cache) &
597                           RTE_CACHE_LINE_MASK) != 0);
598 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
599         RTE_BUILD_BUG_ON((sizeof(struct rte_mempool_debug_stats) &
600                           RTE_CACHE_LINE_MASK) != 0);
601         RTE_BUILD_BUG_ON((offsetof(struct rte_mempool, stats) &
602                           RTE_CACHE_LINE_MASK) != 0);
603 #endif
604
605         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
606
607         /* asked cache too big */
608         if (cache_size > RTE_MEMPOOL_CACHE_MAX_SIZE ||
609             CALC_CACHE_FLUSHTHRESH(cache_size) > n) {
610                 rte_errno = EINVAL;
611                 return NULL;
612         }
613
614         /* check that we have both VA and PA */
615         if (vaddr != NULL && paddr == NULL) {
616                 rte_errno = EINVAL;
617                 return NULL;
618         }
619
620         /* Check that pg_num and pg_shift parameters are valid. */
621         if (pg_num == 0 || pg_shift > MEMPOOL_PG_SHIFT_MAX) {
622                 rte_errno = EINVAL;
623                 return NULL;
624         }
625
626         /* "no cache align" imply "no spread" */
627         if (flags & MEMPOOL_F_NO_CACHE_ALIGN)
628                 flags |= MEMPOOL_F_NO_SPREAD;
629
630         /* calculate mempool object sizes. */
631         if (!rte_mempool_calc_obj_size(elt_size, flags, &objsz)) {
632                 rte_errno = EINVAL;
633                 return NULL;
634         }
635
636         rte_rwlock_write_lock(RTE_EAL_MEMPOOL_RWLOCK);
637
638         /*
639          * reserve a memory zone for this mempool: private data is
640          * cache-aligned
641          */
642         private_data_size = (private_data_size +
643                              RTE_MEMPOOL_ALIGN_MASK) & (~RTE_MEMPOOL_ALIGN_MASK);
644
645
646         /* try to allocate tailq entry */
647         te = rte_zmalloc("MEMPOOL_TAILQ_ENTRY", sizeof(*te), 0);
648         if (te == NULL) {
649                 RTE_LOG(ERR, MEMPOOL, "Cannot allocate tailq entry!\n");
650                 goto exit_unlock;
651         }
652
653         /*
654          * If user provided an external memory buffer, then use it to
655          * store mempool objects. Otherwise reserve a memzone that is large
656          * enough to hold mempool header and metadata plus mempool objects.
657          */
658         mempool_size = MEMPOOL_HEADER_SIZE(mp, cache_size);
659         mempool_size += private_data_size;
660         mempool_size = RTE_ALIGN_CEIL(mempool_size, RTE_MEMPOOL_ALIGN);
661
662         snprintf(mz_name, sizeof(mz_name), RTE_MEMPOOL_MZ_FORMAT, name);
663
664         mz = rte_memzone_reserve(mz_name, mempool_size, socket_id, mz_flags);
665         if (mz == NULL)
666                 goto exit_unlock;
667
668         /* init the mempool structure */
669         memset(mp, 0, sizeof(*mp));
670         snprintf(mp->name, sizeof(mp->name), "%s", name);
671         mp->phys_addr = mz->phys_addr;
672         mp->socket_id = socket_id;
673         mp->size = n;
674         mp->flags = flags;
675         mp->elt_size = objsz.elt_size;
676         mp->header_size = objsz.header_size;
677         mp->trailer_size = objsz.trailer_size;
678         mp->cache_size = cache_size;
679         mp->cache_flushthresh = CALC_CACHE_FLUSHTHRESH(cache_size);
680         mp->private_data_size = private_data_size;
681         STAILQ_INIT(&mp->elt_list);
682         STAILQ_INIT(&mp->mem_list);
683
684         if (rte_mempool_ring_create(mp) < 0)
685                 goto exit_unlock;
686
687         /*
688          * local_cache pointer is set even if cache_size is zero.
689          * The local_cache points to just past the elt_pa[] array.
690          */
691         mp->local_cache = (struct rte_mempool_cache *)
692                 RTE_PTR_ADD(mp, MEMPOOL_HEADER_SIZE(mp, 0));
693
694         /* call the initializer */
695         if (mp_init)
696                 mp_init(mp, mp_init_arg);
697
698         /* mempool elements allocated together with mempool */
699         if (vaddr == NULL)
700                 ret = rte_mempool_populate_default(mp);
701         else
702                 ret = rte_mempool_populate_phys_tab(mp, vaddr,
703                         paddr, pg_num, pg_shift, NULL, NULL);
704         if (ret < 0) {
705                 rte_errno = -ret;
706                 goto exit_unlock;
707         } else if (ret != (int)mp->size) {
708                 rte_errno = EINVAL;
709                 goto exit_unlock;
710         }
711
712         /* call the initializer */
713         if (obj_init)
714                 rte_mempool_obj_iter(mp, obj_init, obj_init_arg);
715
716         te->data = (void *) mp;
717
718         rte_rwlock_write_lock(RTE_EAL_TAILQ_RWLOCK);
719         TAILQ_INSERT_TAIL(mempool_list, te, next);
720         rte_rwlock_write_unlock(RTE_EAL_TAILQ_RWLOCK);
721         rte_rwlock_write_unlock(RTE_EAL_MEMPOOL_RWLOCK);
722
723         return mp;
724
725 exit_unlock:
726         rte_rwlock_write_unlock(RTE_EAL_MEMPOOL_RWLOCK);
727         if (mp != NULL) {
728                 rte_mempool_free_memchunks(mp);
729                 rte_ring_free(mp->ring);
730         }
731         rte_free(te);
732         if (mz != NULL)
733                 rte_memzone_free(mz);
734
735         return NULL;
736 }
737
738 /* Return the number of entries in the mempool */
739 unsigned
740 rte_mempool_count(const struct rte_mempool *mp)
741 {
742         unsigned count;
743         unsigned lcore_id;
744
745         count = rte_ring_count(mp->ring);
746
747         if (mp->cache_size == 0)
748                 return count;
749
750         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++)
751                 count += mp->local_cache[lcore_id].len;
752
753         /*
754          * due to race condition (access to len is not locked), the
755          * total can be greater than size... so fix the result
756          */
757         if (count > mp->size)
758                 return mp->size;
759         return count;
760 }
761
762 /* dump the cache status */
763 static unsigned
764 rte_mempool_dump_cache(FILE *f, const struct rte_mempool *mp)
765 {
766         unsigned lcore_id;
767         unsigned count = 0;
768         unsigned cache_count;
769
770         fprintf(f, "  cache infos:\n");
771         fprintf(f, "    cache_size=%"PRIu32"\n", mp->cache_size);
772
773         if (mp->cache_size == 0)
774                 return count;
775
776         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
777                 cache_count = mp->local_cache[lcore_id].len;
778                 fprintf(f, "    cache_count[%u]=%u\n", lcore_id, cache_count);
779                 count += cache_count;
780         }
781         fprintf(f, "    total_cache_count=%u\n", count);
782         return count;
783 }
784
785 #ifndef __INTEL_COMPILER
786 #pragma GCC diagnostic ignored "-Wcast-qual"
787 #endif
788
789 /* check and update cookies or panic (internal) */
790 void rte_mempool_check_cookies(const struct rte_mempool *mp,
791         void * const *obj_table_const, unsigned n, int free)
792 {
793 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
794         struct rte_mempool_objhdr *hdr;
795         struct rte_mempool_objtlr *tlr;
796         uint64_t cookie;
797         void *tmp;
798         void *obj;
799         void **obj_table;
800
801         /* Force to drop the "const" attribute. This is done only when
802          * DEBUG is enabled */
803         tmp = (void *) obj_table_const;
804         obj_table = (void **) tmp;
805
806         while (n--) {
807                 obj = obj_table[n];
808
809                 if (rte_mempool_from_obj(obj) != mp)
810                         rte_panic("MEMPOOL: object is owned by another "
811                                   "mempool\n");
812
813                 hdr = __mempool_get_header(obj);
814                 cookie = hdr->cookie;
815
816                 if (free == 0) {
817                         if (cookie != RTE_MEMPOOL_HEADER_COOKIE1) {
818                                 rte_log_set_history(0);
819                                 RTE_LOG(CRIT, MEMPOOL,
820                                         "obj=%p, mempool=%p, cookie=%" PRIx64 "\n",
821                                         obj, (const void *) mp, cookie);
822                                 rte_panic("MEMPOOL: bad header cookie (put)\n");
823                         }
824                         hdr->cookie = RTE_MEMPOOL_HEADER_COOKIE2;
825                 } else if (free == 1) {
826                         if (cookie != RTE_MEMPOOL_HEADER_COOKIE2) {
827                                 rte_log_set_history(0);
828                                 RTE_LOG(CRIT, MEMPOOL,
829                                         "obj=%p, mempool=%p, cookie=%" PRIx64 "\n",
830                                         obj, (const void *) mp, cookie);
831                                 rte_panic("MEMPOOL: bad header cookie (get)\n");
832                         }
833                         hdr->cookie = RTE_MEMPOOL_HEADER_COOKIE1;
834                 } else if (free == 2) {
835                         if (cookie != RTE_MEMPOOL_HEADER_COOKIE1 &&
836                             cookie != RTE_MEMPOOL_HEADER_COOKIE2) {
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 (audit)\n");
842                         }
843                 }
844                 tlr = __mempool_get_trailer(obj);
845                 cookie = tlr->cookie;
846                 if (cookie != RTE_MEMPOOL_TRAILER_COOKIE) {
847                         rte_log_set_history(0);
848                         RTE_LOG(CRIT, MEMPOOL,
849                                 "obj=%p, mempool=%p, cookie=%" PRIx64 "\n",
850                                 obj, (const void *) mp, cookie);
851                         rte_panic("MEMPOOL: bad trailer cookie\n");
852                 }
853         }
854 #else
855         RTE_SET_USED(mp);
856         RTE_SET_USED(obj_table_const);
857         RTE_SET_USED(n);
858         RTE_SET_USED(free);
859 #endif
860 }
861
862 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
863 static void
864 mempool_obj_audit(struct rte_mempool *mp, __rte_unused void *opaque,
865         void *obj, __rte_unused unsigned idx)
866 {
867         __mempool_check_cookies(mp, &obj, 1, 2);
868 }
869
870 static void
871 mempool_audit_cookies(struct rte_mempool *mp)
872 {
873         unsigned num;
874
875         num = rte_mempool_obj_iter(mp, mempool_obj_audit, NULL);
876         if (num != mp->size) {
877                 rte_panic("rte_mempool_obj_iter(mempool=%p, size=%u) "
878                         "iterated only over %u elements\n",
879                         mp, mp->size, num);
880         }
881 }
882 #else
883 #define mempool_audit_cookies(mp) do {} while(0)
884 #endif
885
886 #ifndef __INTEL_COMPILER
887 #pragma GCC diagnostic error "-Wcast-qual"
888 #endif
889
890 /* check cookies before and after objects */
891 static void
892 mempool_audit_cache(const struct rte_mempool *mp)
893 {
894         /* check cache size consistency */
895         unsigned lcore_id;
896
897         if (mp->cache_size == 0)
898                 return;
899
900         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
901                 if (mp->local_cache[lcore_id].len > mp->cache_flushthresh) {
902                         RTE_LOG(CRIT, MEMPOOL, "badness on cache[%u]\n",
903                                 lcore_id);
904                         rte_panic("MEMPOOL: invalid cache len\n");
905                 }
906         }
907 }
908
909 /* check the consistency of mempool (size, cookies, ...) */
910 void
911 rte_mempool_audit(struct rte_mempool *mp)
912 {
913         mempool_audit_cache(mp);
914         mempool_audit_cookies(mp);
915
916         /* For case where mempool DEBUG is not set, and cache size is 0 */
917         RTE_SET_USED(mp);
918 }
919
920 /* dump the status of the mempool on the console */
921 void
922 rte_mempool_dump(FILE *f, struct rte_mempool *mp)
923 {
924 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
925         struct rte_mempool_debug_stats sum;
926         unsigned lcore_id;
927 #endif
928         struct rte_mempool_memhdr *memhdr;
929         unsigned common_count;
930         unsigned cache_count;
931         size_t mem_len = 0;
932
933         RTE_ASSERT(f != NULL);
934         RTE_ASSERT(mp != NULL);
935
936         fprintf(f, "mempool <%s>@%p\n", mp->name, mp);
937         fprintf(f, "  flags=%x\n", mp->flags);
938         fprintf(f, "  ring=<%s>@%p\n", mp->ring->name, mp->ring);
939         fprintf(f, "  phys_addr=0x%" PRIx64 "\n", mp->phys_addr);
940         fprintf(f, "  nb_mem_chunks=%u\n", mp->nb_mem_chunks);
941         fprintf(f, "  size=%"PRIu32"\n", mp->size);
942         fprintf(f, "  populated_size=%"PRIu32"\n", mp->populated_size);
943         fprintf(f, "  header_size=%"PRIu32"\n", mp->header_size);
944         fprintf(f, "  elt_size=%"PRIu32"\n", mp->elt_size);
945         fprintf(f, "  trailer_size=%"PRIu32"\n", mp->trailer_size);
946         fprintf(f, "  total_obj_size=%"PRIu32"\n",
947                mp->header_size + mp->elt_size + mp->trailer_size);
948
949         fprintf(f, "  private_data_size=%"PRIu32"\n", mp->private_data_size);
950
951         STAILQ_FOREACH(memhdr, &mp->mem_list, next)
952                 mem_len += memhdr->len;
953         if (mem_len != 0) {
954                 fprintf(f, "  avg bytes/object=%#Lf\n",
955                         (long double)mem_len / mp->size);
956         }
957
958         cache_count = rte_mempool_dump_cache(f, mp);
959         common_count = rte_ring_count(mp->ring);
960         if ((cache_count + common_count) > mp->size)
961                 common_count = mp->size - cache_count;
962         fprintf(f, "  common_pool_count=%u\n", common_count);
963
964         /* sum and dump statistics */
965 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
966         memset(&sum, 0, sizeof(sum));
967         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
968                 sum.put_bulk += mp->stats[lcore_id].put_bulk;
969                 sum.put_objs += mp->stats[lcore_id].put_objs;
970                 sum.get_success_bulk += mp->stats[lcore_id].get_success_bulk;
971                 sum.get_success_objs += mp->stats[lcore_id].get_success_objs;
972                 sum.get_fail_bulk += mp->stats[lcore_id].get_fail_bulk;
973                 sum.get_fail_objs += mp->stats[lcore_id].get_fail_objs;
974         }
975         fprintf(f, "  stats:\n");
976         fprintf(f, "    put_bulk=%"PRIu64"\n", sum.put_bulk);
977         fprintf(f, "    put_objs=%"PRIu64"\n", sum.put_objs);
978         fprintf(f, "    get_success_bulk=%"PRIu64"\n", sum.get_success_bulk);
979         fprintf(f, "    get_success_objs=%"PRIu64"\n", sum.get_success_objs);
980         fprintf(f, "    get_fail_bulk=%"PRIu64"\n", sum.get_fail_bulk);
981         fprintf(f, "    get_fail_objs=%"PRIu64"\n", sum.get_fail_objs);
982 #else
983         fprintf(f, "  no statistics available\n");
984 #endif
985
986         rte_mempool_audit(mp);
987 }
988
989 /* dump the status of all mempools on the console */
990 void
991 rte_mempool_list_dump(FILE *f)
992 {
993         struct rte_mempool *mp = NULL;
994         struct rte_tailq_entry *te;
995         struct rte_mempool_list *mempool_list;
996
997         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
998
999         rte_rwlock_read_lock(RTE_EAL_MEMPOOL_RWLOCK);
1000
1001         TAILQ_FOREACH(te, mempool_list, next) {
1002                 mp = (struct rte_mempool *) te->data;
1003                 rte_mempool_dump(f, mp);
1004         }
1005
1006         rte_rwlock_read_unlock(RTE_EAL_MEMPOOL_RWLOCK);
1007 }
1008
1009 /* search a mempool from its name */
1010 struct rte_mempool *
1011 rte_mempool_lookup(const char *name)
1012 {
1013         struct rte_mempool *mp = NULL;
1014         struct rte_tailq_entry *te;
1015         struct rte_mempool_list *mempool_list;
1016
1017         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
1018
1019         rte_rwlock_read_lock(RTE_EAL_MEMPOOL_RWLOCK);
1020
1021         TAILQ_FOREACH(te, mempool_list, next) {
1022                 mp = (struct rte_mempool *) te->data;
1023                 if (strncmp(name, mp->name, RTE_MEMPOOL_NAMESIZE) == 0)
1024                         break;
1025         }
1026
1027         rte_rwlock_read_unlock(RTE_EAL_MEMPOOL_RWLOCK);
1028
1029         if (te == NULL) {
1030                 rte_errno = ENOENT;
1031                 return NULL;
1032         }
1033
1034         return mp;
1035 }
1036
1037 void rte_mempool_walk(void (*func)(struct rte_mempool *, void *),
1038                       void *arg)
1039 {
1040         struct rte_tailq_entry *te = NULL;
1041         struct rte_mempool_list *mempool_list;
1042
1043         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
1044
1045         rte_rwlock_read_lock(RTE_EAL_MEMPOOL_RWLOCK);
1046
1047         TAILQ_FOREACH(te, mempool_list, next) {
1048                 (*func)((struct rte_mempool *) te->data, arg);
1049         }
1050
1051         rte_rwlock_read_unlock(RTE_EAL_MEMPOOL_RWLOCK);
1052 }