mempool: fix local cache initialization
[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 #include <sys/mman.h>
44
45 #include <rte_common.h>
46 #include <rte_log.h>
47 #include <rte_debug.h>
48 #include <rte_memory.h>
49 #include <rte_memzone.h>
50 #include <rte_malloc.h>
51 #include <rte_atomic.h>
52 #include <rte_launch.h>
53 #include <rte_eal.h>
54 #include <rte_eal_memconfig.h>
55 #include <rte_per_lcore.h>
56 #include <rte_lcore.h>
57 #include <rte_branch_prediction.h>
58 #include <rte_ring.h>
59 #include <rte_errno.h>
60 #include <rte_string_fns.h>
61 #include <rte_spinlock.h>
62
63 #include "rte_mempool.h"
64
65 TAILQ_HEAD(rte_mempool_list, rte_tailq_entry);
66
67 static struct rte_tailq_elem rte_mempool_tailq = {
68         .name = "RTE_MEMPOOL",
69 };
70 EAL_REGISTER_TAILQ(rte_mempool_tailq)
71
72 #define CACHE_FLUSHTHRESH_MULTIPLIER 1.5
73 #define CALC_CACHE_FLUSHTHRESH(c)       \
74         ((typeof(c))((c) * CACHE_FLUSHTHRESH_MULTIPLIER))
75
76 /*
77  * return the greatest common divisor between a and b (fast algorithm)
78  *
79  */
80 static unsigned get_gcd(unsigned a, unsigned b)
81 {
82         unsigned c;
83
84         if (0 == a)
85                 return b;
86         if (0 == b)
87                 return a;
88
89         if (a < b) {
90                 c = a;
91                 a = b;
92                 b = c;
93         }
94
95         while (b != 0) {
96                 c = a % b;
97                 a = b;
98                 b = c;
99         }
100
101         return a;
102 }
103
104 /*
105  * Depending on memory configuration, objects addresses are spread
106  * between channels and ranks in RAM: the pool allocator will add
107  * padding between objects. This function return the new size of the
108  * object.
109  */
110 static unsigned optimize_object_size(unsigned obj_size)
111 {
112         unsigned nrank, nchan;
113         unsigned new_obj_size;
114
115         /* get number of channels */
116         nchan = rte_memory_get_nchannel();
117         if (nchan == 0)
118                 nchan = 4;
119
120         nrank = rte_memory_get_nrank();
121         if (nrank == 0)
122                 nrank = 1;
123
124         /* process new object size */
125         new_obj_size = (obj_size + RTE_MEMPOOL_ALIGN_MASK) / RTE_MEMPOOL_ALIGN;
126         while (get_gcd(new_obj_size, nrank * nchan) != 1)
127                 new_obj_size++;
128         return new_obj_size * RTE_MEMPOOL_ALIGN;
129 }
130
131 static void
132 mempool_add_elem(struct rte_mempool *mp, void *obj, phys_addr_t physaddr)
133 {
134         struct rte_mempool_objhdr *hdr;
135         struct rte_mempool_objtlr *tlr __rte_unused;
136
137         /* set mempool ptr in header */
138         hdr = RTE_PTR_SUB(obj, sizeof(*hdr));
139         hdr->mp = mp;
140         hdr->physaddr = physaddr;
141         STAILQ_INSERT_TAIL(&mp->elt_list, hdr, next);
142         mp->populated_size++;
143
144 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
145         hdr->cookie = RTE_MEMPOOL_HEADER_COOKIE2;
146         tlr = __mempool_get_trailer(obj);
147         tlr->cookie = RTE_MEMPOOL_TRAILER_COOKIE;
148 #endif
149
150         /* enqueue in ring */
151         rte_ring_sp_enqueue(mp->ring, obj);
152 }
153
154 /* call obj_cb() for each mempool element */
155 uint32_t
156 rte_mempool_obj_iter(struct rte_mempool *mp,
157         rte_mempool_obj_cb_t *obj_cb, void *obj_cb_arg)
158 {
159         struct rte_mempool_objhdr *hdr;
160         void *obj;
161         unsigned n = 0;
162
163         STAILQ_FOREACH(hdr, &mp->elt_list, next) {
164                 obj = (char *)hdr + sizeof(*hdr);
165                 obj_cb(mp, obj_cb_arg, obj, n);
166                 n++;
167         }
168
169         return n;
170 }
171
172 /* call mem_cb() for each mempool memory chunk */
173 uint32_t
174 rte_mempool_mem_iter(struct rte_mempool *mp,
175         rte_mempool_mem_cb_t *mem_cb, void *mem_cb_arg)
176 {
177         struct rte_mempool_memhdr *hdr;
178         unsigned n = 0;
179
180         STAILQ_FOREACH(hdr, &mp->mem_list, next) {
181                 mem_cb(mp, mem_cb_arg, hdr, n);
182                 n++;
183         }
184
185         return n;
186 }
187
188 /* get the header, trailer and total size of a mempool element. */
189 uint32_t
190 rte_mempool_calc_obj_size(uint32_t elt_size, uint32_t flags,
191         struct rte_mempool_objsz *sz)
192 {
193         struct rte_mempool_objsz lsz;
194
195         sz = (sz != NULL) ? sz : &lsz;
196
197         sz->header_size = sizeof(struct rte_mempool_objhdr);
198         if ((flags & MEMPOOL_F_NO_CACHE_ALIGN) == 0)
199                 sz->header_size = RTE_ALIGN_CEIL(sz->header_size,
200                         RTE_MEMPOOL_ALIGN);
201
202         sz->trailer_size = sizeof(struct rte_mempool_objtlr);
203
204         /* element size is 8 bytes-aligned at least */
205         sz->elt_size = RTE_ALIGN_CEIL(elt_size, sizeof(uint64_t));
206
207         /* expand trailer to next cache line */
208         if ((flags & MEMPOOL_F_NO_CACHE_ALIGN) == 0) {
209                 sz->total_size = sz->header_size + sz->elt_size +
210                         sz->trailer_size;
211                 sz->trailer_size += ((RTE_MEMPOOL_ALIGN -
212                                   (sz->total_size & RTE_MEMPOOL_ALIGN_MASK)) &
213                                  RTE_MEMPOOL_ALIGN_MASK);
214         }
215
216         /*
217          * increase trailer to add padding between objects in order to
218          * spread them across memory channels/ranks
219          */
220         if ((flags & MEMPOOL_F_NO_SPREAD) == 0) {
221                 unsigned new_size;
222                 new_size = optimize_object_size(sz->header_size + sz->elt_size +
223                         sz->trailer_size);
224                 sz->trailer_size = new_size - sz->header_size - sz->elt_size;
225         }
226
227         /* this is the size of an object, including header and trailer */
228         sz->total_size = sz->header_size + sz->elt_size + sz->trailer_size;
229
230         return sz->total_size;
231 }
232
233
234 /*
235  * Calculate maximum amount of memory required to store given number of objects.
236  */
237 size_t
238 rte_mempool_xmem_size(uint32_t elt_num, size_t total_elt_sz, uint32_t pg_shift)
239 {
240         size_t obj_per_page, pg_num, pg_sz;
241
242         if (total_elt_sz == 0)
243                 return 0;
244
245         if (pg_shift == 0)
246                 return total_elt_sz * elt_num;
247
248         pg_sz = (size_t)1 << pg_shift;
249         obj_per_page = pg_sz / total_elt_sz;
250         if (obj_per_page == 0)
251                 return RTE_ALIGN_CEIL(total_elt_sz, pg_sz) * elt_num;
252
253         pg_num = (elt_num + obj_per_page - 1) / obj_per_page;
254         return pg_num << pg_shift;
255 }
256
257 /*
258  * Calculate how much memory would be actually required with the
259  * given memory footprint to store required number of elements.
260  */
261 ssize_t
262 rte_mempool_xmem_usage(__rte_unused void *vaddr, uint32_t elt_num,
263         size_t total_elt_sz, const phys_addr_t paddr[], uint32_t pg_num,
264         uint32_t pg_shift)
265 {
266         uint32_t elt_cnt = 0;
267         phys_addr_t start, end;
268         uint32_t paddr_idx;
269         size_t pg_sz = (size_t)1 << pg_shift;
270
271         /* if paddr is NULL, assume contiguous memory */
272         if (paddr == NULL) {
273                 start = 0;
274                 end = pg_sz * pg_num;
275                 paddr_idx = pg_num;
276         } else {
277                 start = paddr[0];
278                 end = paddr[0] + pg_sz;
279                 paddr_idx = 1;
280         }
281         while (elt_cnt < elt_num) {
282
283                 if (end - start >= total_elt_sz) {
284                         /* enough contiguous memory, add an object */
285                         start += total_elt_sz;
286                         elt_cnt++;
287                 } else if (paddr_idx < pg_num) {
288                         /* no room to store one obj, add a page */
289                         if (end == paddr[paddr_idx]) {
290                                 end += pg_sz;
291                         } else {
292                                 start = paddr[paddr_idx];
293                                 end = paddr[paddr_idx] + pg_sz;
294                         }
295                         paddr_idx++;
296
297                 } else {
298                         /* no more page, return how many elements fit */
299                         return -(size_t)elt_cnt;
300                 }
301         }
302
303         return (size_t)paddr_idx << pg_shift;
304 }
305
306 /* create the internal ring */
307 static int
308 rte_mempool_ring_create(struct rte_mempool *mp)
309 {
310         int rg_flags = 0, ret;
311         char rg_name[RTE_RING_NAMESIZE];
312         struct rte_ring *r;
313
314         ret = snprintf(rg_name, sizeof(rg_name),
315                 RTE_MEMPOOL_MZ_FORMAT, mp->name);
316         if (ret < 0 || ret >= (int)sizeof(rg_name))
317                 return -ENAMETOOLONG;
318
319         /* ring flags */
320         if (mp->flags & MEMPOOL_F_SP_PUT)
321                 rg_flags |= RING_F_SP_ENQ;
322         if (mp->flags & MEMPOOL_F_SC_GET)
323                 rg_flags |= RING_F_SC_DEQ;
324
325         /* Allocate the ring that will be used to store objects.
326          * Ring functions will return appropriate errors if we are
327          * running as a secondary process etc., so no checks made
328          * in this function for that condition.
329          */
330         r = rte_ring_create(rg_name, rte_align32pow2(mp->size + 1),
331                 mp->socket_id, rg_flags);
332         if (r == NULL)
333                 return -rte_errno;
334
335         mp->ring = r;
336         mp->flags |= MEMPOOL_F_RING_CREATED;
337         return 0;
338 }
339
340 /* free a memchunk allocated with rte_memzone_reserve() */
341 static void
342 rte_mempool_memchunk_mz_free(__rte_unused struct rte_mempool_memhdr *memhdr,
343         void *opaque)
344 {
345         const struct rte_memzone *mz = opaque;
346         rte_memzone_free(mz);
347 }
348
349 /* Free memory chunks used by a mempool. Objects must be in pool */
350 static void
351 rte_mempool_free_memchunks(struct rte_mempool *mp)
352 {
353         struct rte_mempool_memhdr *memhdr;
354         void *elt;
355
356         while (!STAILQ_EMPTY(&mp->elt_list)) {
357                 rte_ring_sc_dequeue(mp->ring, &elt);
358                 (void)elt;
359                 STAILQ_REMOVE_HEAD(&mp->elt_list, next);
360                 mp->populated_size--;
361         }
362
363         while (!STAILQ_EMPTY(&mp->mem_list)) {
364                 memhdr = STAILQ_FIRST(&mp->mem_list);
365                 STAILQ_REMOVE_HEAD(&mp->mem_list, next);
366                 if (memhdr->free_cb != NULL)
367                         memhdr->free_cb(memhdr, memhdr->opaque);
368                 rte_free(memhdr);
369                 mp->nb_mem_chunks--;
370         }
371 }
372
373 /* Add objects in the pool, using a physically contiguous memory
374  * zone. Return the number of objects added, or a negative value
375  * on error.
376  */
377 int
378 rte_mempool_populate_phys(struct rte_mempool *mp, char *vaddr,
379         phys_addr_t paddr, size_t len, rte_mempool_memchunk_free_cb_t *free_cb,
380         void *opaque)
381 {
382         unsigned total_elt_sz;
383         unsigned i = 0;
384         size_t off;
385         struct rte_mempool_memhdr *memhdr;
386         int ret;
387
388         /* create the internal ring if not already done */
389         if ((mp->flags & MEMPOOL_F_RING_CREATED) == 0) {
390                 ret = rte_mempool_ring_create(mp);
391                 if (ret < 0)
392                         return ret;
393         }
394
395         /* mempool is already populated */
396         if (mp->populated_size >= mp->size)
397                 return -ENOSPC;
398
399         total_elt_sz = mp->header_size + mp->elt_size + mp->trailer_size;
400
401         memhdr = rte_zmalloc("MEMPOOL_MEMHDR", sizeof(*memhdr), 0);
402         if (memhdr == NULL)
403                 return -ENOMEM;
404
405         memhdr->mp = mp;
406         memhdr->addr = vaddr;
407         memhdr->phys_addr = paddr;
408         memhdr->len = len;
409         memhdr->free_cb = free_cb;
410         memhdr->opaque = opaque;
411
412         if (mp->flags & MEMPOOL_F_NO_CACHE_ALIGN)
413                 off = RTE_PTR_ALIGN_CEIL(vaddr, 8) - vaddr;
414         else
415                 off = RTE_PTR_ALIGN_CEIL(vaddr, RTE_CACHE_LINE_SIZE) - vaddr;
416
417         while (off + total_elt_sz <= len && mp->populated_size < mp->size) {
418                 off += mp->header_size;
419                 if (paddr == RTE_BAD_PHYS_ADDR)
420                         mempool_add_elem(mp, (char *)vaddr + off,
421                                 RTE_BAD_PHYS_ADDR);
422                 else
423                         mempool_add_elem(mp, (char *)vaddr + off, paddr + off);
424                 off += mp->elt_size + mp->trailer_size;
425                 i++;
426         }
427
428         /* not enough room to store one object */
429         if (i == 0)
430                 return -EINVAL;
431
432         STAILQ_INSERT_TAIL(&mp->mem_list, memhdr, next);
433         mp->nb_mem_chunks++;
434         return i;
435 }
436
437 /* Add objects in the pool, using a table of physical pages. Return the
438  * number of objects added, or a negative value on error.
439  */
440 int
441 rte_mempool_populate_phys_tab(struct rte_mempool *mp, char *vaddr,
442         const phys_addr_t paddr[], uint32_t pg_num, uint32_t pg_shift,
443         rte_mempool_memchunk_free_cb_t *free_cb, void *opaque)
444 {
445         uint32_t i, n;
446         int ret, cnt = 0;
447         size_t pg_sz = (size_t)1 << pg_shift;
448
449         /* mempool must not be populated */
450         if (mp->nb_mem_chunks != 0)
451                 return -EEXIST;
452
453         if (mp->flags & MEMPOOL_F_NO_PHYS_CONTIG)
454                 return rte_mempool_populate_phys(mp, vaddr, RTE_BAD_PHYS_ADDR,
455                         pg_num * pg_sz, free_cb, opaque);
456
457         for (i = 0; i < pg_num && mp->populated_size < mp->size; i += n) {
458
459                 /* populate with the largest group of contiguous pages */
460                 for (n = 1; (i + n) < pg_num &&
461                              paddr[i] + pg_sz == paddr[i+n]; n++)
462                         ;
463
464                 ret = rte_mempool_populate_phys(mp, vaddr + i * pg_sz,
465                         paddr[i], n * pg_sz, free_cb, opaque);
466                 if (ret < 0) {
467                         rte_mempool_free_memchunks(mp);
468                         return ret;
469                 }
470                 /* no need to call the free callback for next chunks */
471                 free_cb = NULL;
472                 cnt += ret;
473         }
474         return cnt;
475 }
476
477 /* Populate the mempool with a virtual area. Return the number of
478  * objects added, or a negative value on error.
479  */
480 int
481 rte_mempool_populate_virt(struct rte_mempool *mp, char *addr,
482         size_t len, size_t pg_sz, rte_mempool_memchunk_free_cb_t *free_cb,
483         void *opaque)
484 {
485         phys_addr_t paddr;
486         size_t off, phys_len;
487         int ret, cnt = 0;
488
489         /* mempool must not be populated */
490         if (mp->nb_mem_chunks != 0)
491                 return -EEXIST;
492         /* address and len must be page-aligned */
493         if (RTE_PTR_ALIGN_CEIL(addr, pg_sz) != addr)
494                 return -EINVAL;
495         if (RTE_ALIGN_CEIL(len, pg_sz) != len)
496                 return -EINVAL;
497
498         if (mp->flags & MEMPOOL_F_NO_PHYS_CONTIG)
499                 return rte_mempool_populate_phys(mp, addr, RTE_BAD_PHYS_ADDR,
500                         len, free_cb, opaque);
501
502         for (off = 0; off + pg_sz <= len &&
503                      mp->populated_size < mp->size; off += phys_len) {
504
505                 paddr = rte_mem_virt2phy(addr + off);
506                 /* required for xen_dom0 to get the machine address */
507                 paddr = rte_mem_phy2mch(-1, paddr);
508
509                 if (paddr == RTE_BAD_PHYS_ADDR) {
510                         ret = -EINVAL;
511                         goto fail;
512                 }
513
514                 /* populate with the largest group of contiguous pages */
515                 for (phys_len = pg_sz; off + phys_len < len; phys_len += pg_sz) {
516                         phys_addr_t paddr_tmp;
517
518                         paddr_tmp = rte_mem_virt2phy(addr + off + phys_len);
519                         paddr_tmp = rte_mem_phy2mch(-1, paddr_tmp);
520
521                         if (paddr_tmp != paddr + phys_len)
522                                 break;
523                 }
524
525                 ret = rte_mempool_populate_phys(mp, addr + off, paddr,
526                         phys_len, free_cb, opaque);
527                 if (ret < 0)
528                         goto fail;
529                 /* no need to call the free callback for next chunks */
530                 free_cb = NULL;
531                 cnt += ret;
532         }
533
534         return cnt;
535
536  fail:
537         rte_mempool_free_memchunks(mp);
538         return ret;
539 }
540
541 /* Default function to populate the mempool: allocate memory in memzones,
542  * and populate them. Return the number of objects added, or a negative
543  * value on error.
544  */
545 int
546 rte_mempool_populate_default(struct rte_mempool *mp)
547 {
548         int mz_flags = RTE_MEMZONE_1GB|RTE_MEMZONE_SIZE_HINT_ONLY;
549         char mz_name[RTE_MEMZONE_NAMESIZE];
550         const struct rte_memzone *mz;
551         size_t size, total_elt_sz, align, pg_sz, pg_shift;
552         phys_addr_t paddr;
553         unsigned mz_id, n;
554         int ret;
555
556         /* mempool must not be populated */
557         if (mp->nb_mem_chunks != 0)
558                 return -EEXIST;
559
560         if (rte_eal_has_hugepages()) {
561                 pg_shift = 0; /* not needed, zone is physically contiguous */
562                 pg_sz = 0;
563                 align = RTE_CACHE_LINE_SIZE;
564         } else {
565                 pg_sz = getpagesize();
566                 pg_shift = rte_bsf32(pg_sz);
567                 align = pg_sz;
568         }
569
570         total_elt_sz = mp->header_size + mp->elt_size + mp->trailer_size;
571         for (mz_id = 0, n = mp->size; n > 0; mz_id++, n -= ret) {
572                 size = rte_mempool_xmem_size(n, total_elt_sz, pg_shift);
573
574                 ret = snprintf(mz_name, sizeof(mz_name),
575                         RTE_MEMPOOL_MZ_FORMAT "_%d", mp->name, mz_id);
576                 if (ret < 0 || ret >= (int)sizeof(mz_name)) {
577                         ret = -ENAMETOOLONG;
578                         goto fail;
579                 }
580
581                 mz = rte_memzone_reserve_aligned(mz_name, size,
582                         mp->socket_id, mz_flags, align);
583                 /* not enough memory, retry with the biggest zone we have */
584                 if (mz == NULL)
585                         mz = rte_memzone_reserve_aligned(mz_name, 0,
586                                 mp->socket_id, mz_flags, align);
587                 if (mz == NULL) {
588                         ret = -rte_errno;
589                         goto fail;
590                 }
591
592                 if (mp->flags & MEMPOOL_F_NO_PHYS_CONTIG)
593                         paddr = RTE_BAD_PHYS_ADDR;
594                 else
595                         paddr = mz->phys_addr;
596
597                 if (rte_eal_has_hugepages() && !rte_xen_dom0_supported())
598                         ret = rte_mempool_populate_phys(mp, mz->addr,
599                                 paddr, mz->len,
600                                 rte_mempool_memchunk_mz_free,
601                                 (void *)(uintptr_t)mz);
602                 else
603                         ret = rte_mempool_populate_virt(mp, mz->addr,
604                                 mz->len, pg_sz,
605                                 rte_mempool_memchunk_mz_free,
606                                 (void *)(uintptr_t)mz);
607                 if (ret < 0)
608                         goto fail;
609         }
610
611         return mp->size;
612
613  fail:
614         rte_mempool_free_memchunks(mp);
615         return ret;
616 }
617
618 /* return the memory size required for mempool objects in anonymous mem */
619 static size_t
620 get_anon_size(const struct rte_mempool *mp)
621 {
622         size_t size, total_elt_sz, pg_sz, pg_shift;
623
624         pg_sz = getpagesize();
625         pg_shift = rte_bsf32(pg_sz);
626         total_elt_sz = mp->header_size + mp->elt_size + mp->trailer_size;
627         size = rte_mempool_xmem_size(mp->size, total_elt_sz, pg_shift);
628
629         return size;
630 }
631
632 /* unmap a memory zone mapped by rte_mempool_populate_anon() */
633 static void
634 rte_mempool_memchunk_anon_free(struct rte_mempool_memhdr *memhdr,
635         void *opaque)
636 {
637         munmap(opaque, get_anon_size(memhdr->mp));
638 }
639
640 /* populate the mempool with an anonymous mapping */
641 int
642 rte_mempool_populate_anon(struct rte_mempool *mp)
643 {
644         size_t size;
645         int ret;
646         char *addr;
647
648         /* mempool is already populated, error */
649         if (!STAILQ_EMPTY(&mp->mem_list)) {
650                 rte_errno = EINVAL;
651                 return 0;
652         }
653
654         /* get chunk of virtually continuous memory */
655         size = get_anon_size(mp);
656         addr = mmap(NULL, size, PROT_READ | PROT_WRITE,
657                 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
658         if (addr == MAP_FAILED) {
659                 rte_errno = errno;
660                 return 0;
661         }
662         /* can't use MMAP_LOCKED, it does not exist on BSD */
663         if (mlock(addr, size) < 0) {
664                 rte_errno = errno;
665                 munmap(addr, size);
666                 return 0;
667         }
668
669         ret = rte_mempool_populate_virt(mp, addr, size, getpagesize(),
670                 rte_mempool_memchunk_anon_free, addr);
671         if (ret == 0)
672                 goto fail;
673
674         return mp->populated_size;
675
676  fail:
677         rte_mempool_free_memchunks(mp);
678         return 0;
679 }
680
681 /* free a mempool */
682 void
683 rte_mempool_free(struct rte_mempool *mp)
684 {
685         struct rte_mempool_list *mempool_list = NULL;
686         struct rte_tailq_entry *te;
687
688         if (mp == NULL)
689                 return;
690
691         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
692         rte_rwlock_write_lock(RTE_EAL_TAILQ_RWLOCK);
693         /* find out tailq entry */
694         TAILQ_FOREACH(te, mempool_list, next) {
695                 if (te->data == (void *)mp)
696                         break;
697         }
698
699         if (te != NULL) {
700                 TAILQ_REMOVE(mempool_list, te, next);
701                 rte_free(te);
702         }
703         rte_rwlock_write_unlock(RTE_EAL_TAILQ_RWLOCK);
704
705         rte_mempool_free_memchunks(mp);
706         rte_ring_free(mp->ring);
707         rte_memzone_free(mp->mz);
708 }
709
710 /* create an empty mempool */
711 struct rte_mempool *
712 rte_mempool_create_empty(const char *name, unsigned n, unsigned elt_size,
713         unsigned cache_size, unsigned private_data_size,
714         int socket_id, unsigned flags)
715 {
716         char mz_name[RTE_MEMZONE_NAMESIZE];
717         struct rte_mempool_list *mempool_list;
718         struct rte_mempool *mp = NULL;
719         struct rte_tailq_entry *te = NULL;
720         const struct rte_memzone *mz = NULL;
721         size_t mempool_size;
722         int mz_flags = RTE_MEMZONE_1GB|RTE_MEMZONE_SIZE_HINT_ONLY;
723         struct rte_mempool_objsz objsz;
724         int ret;
725
726         /* compilation-time checks */
727         RTE_BUILD_BUG_ON((sizeof(struct rte_mempool) &
728                           RTE_CACHE_LINE_MASK) != 0);
729         RTE_BUILD_BUG_ON((sizeof(struct rte_mempool_cache) &
730                           RTE_CACHE_LINE_MASK) != 0);
731 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
732         RTE_BUILD_BUG_ON((sizeof(struct rte_mempool_debug_stats) &
733                           RTE_CACHE_LINE_MASK) != 0);
734         RTE_BUILD_BUG_ON((offsetof(struct rte_mempool, stats) &
735                           RTE_CACHE_LINE_MASK) != 0);
736 #endif
737
738         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
739
740         /* asked cache too big */
741         if (cache_size > RTE_MEMPOOL_CACHE_MAX_SIZE ||
742             CALC_CACHE_FLUSHTHRESH(cache_size) > n) {
743                 rte_errno = EINVAL;
744                 return NULL;
745         }
746
747         /* "no cache align" imply "no spread" */
748         if (flags & MEMPOOL_F_NO_CACHE_ALIGN)
749                 flags |= MEMPOOL_F_NO_SPREAD;
750
751         /* calculate mempool object sizes. */
752         if (!rte_mempool_calc_obj_size(elt_size, flags, &objsz)) {
753                 rte_errno = EINVAL;
754                 return NULL;
755         }
756
757         rte_rwlock_write_lock(RTE_EAL_MEMPOOL_RWLOCK);
758
759         /*
760          * reserve a memory zone for this mempool: private data is
761          * cache-aligned
762          */
763         private_data_size = (private_data_size +
764                              RTE_MEMPOOL_ALIGN_MASK) & (~RTE_MEMPOOL_ALIGN_MASK);
765
766
767         /* try to allocate tailq entry */
768         te = rte_zmalloc("MEMPOOL_TAILQ_ENTRY", sizeof(*te), 0);
769         if (te == NULL) {
770                 RTE_LOG(ERR, MEMPOOL, "Cannot allocate tailq entry!\n");
771                 goto exit_unlock;
772         }
773
774         mempool_size = MEMPOOL_HEADER_SIZE(mp, cache_size);
775         mempool_size += private_data_size;
776         mempool_size = RTE_ALIGN_CEIL(mempool_size, RTE_MEMPOOL_ALIGN);
777
778         ret = snprintf(mz_name, sizeof(mz_name), RTE_MEMPOOL_MZ_FORMAT, name);
779         if (ret < 0 || ret >= (int)sizeof(mz_name)) {
780                 rte_errno = ENAMETOOLONG;
781                 goto exit_unlock;
782         }
783
784         mz = rte_memzone_reserve(mz_name, mempool_size, socket_id, mz_flags);
785         if (mz == NULL)
786                 goto exit_unlock;
787
788         /* init the mempool structure */
789         mp = mz->addr;
790         memset(mp, 0, MEMPOOL_HEADER_SIZE(mp, cache_size));
791         ret = snprintf(mp->name, sizeof(mp->name), "%s", name);
792         if (ret < 0 || ret >= (int)sizeof(mp->name)) {
793                 rte_errno = ENAMETOOLONG;
794                 goto exit_unlock;
795         }
796         mp->mz = mz;
797         mp->socket_id = socket_id;
798         mp->size = n;
799         mp->flags = flags;
800         mp->socket_id = socket_id;
801         mp->elt_size = objsz.elt_size;
802         mp->header_size = objsz.header_size;
803         mp->trailer_size = objsz.trailer_size;
804         mp->cache_size = cache_size;
805         mp->cache_flushthresh = CALC_CACHE_FLUSHTHRESH(cache_size);
806         mp->private_data_size = private_data_size;
807         STAILQ_INIT(&mp->elt_list);
808         STAILQ_INIT(&mp->mem_list);
809
810         /*
811          * local_cache pointer is set even if cache_size is zero.
812          * The local_cache points to just past the elt_pa[] array.
813          */
814         mp->local_cache = (struct rte_mempool_cache *)
815                 RTE_PTR_ADD(mp, MEMPOOL_HEADER_SIZE(mp, 0));
816
817         te->data = mp;
818         rte_rwlock_write_lock(RTE_EAL_TAILQ_RWLOCK);
819         TAILQ_INSERT_TAIL(mempool_list, te, next);
820         rte_rwlock_write_unlock(RTE_EAL_TAILQ_RWLOCK);
821         rte_rwlock_write_unlock(RTE_EAL_MEMPOOL_RWLOCK);
822
823         return mp;
824
825 exit_unlock:
826         rte_rwlock_write_unlock(RTE_EAL_MEMPOOL_RWLOCK);
827         rte_free(te);
828         rte_mempool_free(mp);
829         return NULL;
830 }
831
832 /* create the mempool */
833 struct rte_mempool *
834 rte_mempool_create(const char *name, unsigned n, unsigned elt_size,
835         unsigned cache_size, unsigned private_data_size,
836         rte_mempool_ctor_t *mp_init, void *mp_init_arg,
837         rte_mempool_obj_cb_t *obj_init, void *obj_init_arg,
838         int socket_id, unsigned flags)
839 {
840         struct rte_mempool *mp;
841
842         mp = rte_mempool_create_empty(name, n, elt_size, cache_size,
843                 private_data_size, socket_id, flags);
844         if (mp == NULL)
845                 return NULL;
846
847         /* call the mempool priv initializer */
848         if (mp_init)
849                 mp_init(mp, mp_init_arg);
850
851         if (rte_mempool_populate_default(mp) < 0)
852                 goto fail;
853
854         /* call the object initializers */
855         if (obj_init)
856                 rte_mempool_obj_iter(mp, obj_init, obj_init_arg);
857
858         return mp;
859
860  fail:
861         rte_mempool_free(mp);
862         return NULL;
863 }
864
865 /*
866  * Create the mempool over already allocated chunk of memory.
867  * That external memory buffer can consists of physically disjoint pages.
868  * Setting vaddr to NULL, makes mempool to fallback to original behaviour
869  * and allocate space for mempool and it's elements as one big chunk of
870  * physically continuos memory.
871  */
872 struct rte_mempool *
873 rte_mempool_xmem_create(const char *name, unsigned n, unsigned elt_size,
874                 unsigned cache_size, unsigned private_data_size,
875                 rte_mempool_ctor_t *mp_init, void *mp_init_arg,
876                 rte_mempool_obj_cb_t *obj_init, void *obj_init_arg,
877                 int socket_id, unsigned flags, void *vaddr,
878                 const phys_addr_t paddr[], uint32_t pg_num, uint32_t pg_shift)
879 {
880         struct rte_mempool *mp = NULL;
881         int ret;
882
883         /* no virtual address supplied, use rte_mempool_create() */
884         if (vaddr == NULL)
885                 return rte_mempool_create(name, n, elt_size, cache_size,
886                         private_data_size, mp_init, mp_init_arg,
887                         obj_init, obj_init_arg, socket_id, flags);
888
889         /* check that we have both VA and PA */
890         if (paddr == NULL) {
891                 rte_errno = EINVAL;
892                 return NULL;
893         }
894
895         /* Check that pg_shift parameter is valid. */
896         if (pg_shift > MEMPOOL_PG_SHIFT_MAX) {
897                 rte_errno = EINVAL;
898                 return NULL;
899         }
900
901         mp = rte_mempool_create_empty(name, n, elt_size, cache_size,
902                 private_data_size, socket_id, flags);
903         if (mp == NULL)
904                 return NULL;
905
906         /* call the mempool priv initializer */
907         if (mp_init)
908                 mp_init(mp, mp_init_arg);
909
910         ret = rte_mempool_populate_phys_tab(mp, vaddr, paddr, pg_num, pg_shift,
911                 NULL, NULL);
912         if (ret < 0 || ret != (int)mp->size)
913                 goto fail;
914
915         /* call the object initializers */
916         if (obj_init)
917                 rte_mempool_obj_iter(mp, obj_init, obj_init_arg);
918
919         return mp;
920
921  fail:
922         rte_mempool_free(mp);
923         return NULL;
924 }
925
926 /* Return the number of entries in the mempool */
927 unsigned
928 rte_mempool_count(const struct rte_mempool *mp)
929 {
930         unsigned count;
931         unsigned lcore_id;
932
933         count = rte_ring_count(mp->ring);
934
935         if (mp->cache_size == 0)
936                 return count;
937
938         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++)
939                 count += mp->local_cache[lcore_id].len;
940
941         /*
942          * due to race condition (access to len is not locked), the
943          * total can be greater than size... so fix the result
944          */
945         if (count > mp->size)
946                 return mp->size;
947         return count;
948 }
949
950 /* dump the cache status */
951 static unsigned
952 rte_mempool_dump_cache(FILE *f, const struct rte_mempool *mp)
953 {
954         unsigned lcore_id;
955         unsigned count = 0;
956         unsigned cache_count;
957
958         fprintf(f, "  cache infos:\n");
959         fprintf(f, "    cache_size=%"PRIu32"\n", mp->cache_size);
960
961         if (mp->cache_size == 0)
962                 return count;
963
964         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
965                 cache_count = mp->local_cache[lcore_id].len;
966                 fprintf(f, "    cache_count[%u]=%u\n", lcore_id, cache_count);
967                 count += cache_count;
968         }
969         fprintf(f, "    total_cache_count=%u\n", count);
970         return count;
971 }
972
973 #ifndef __INTEL_COMPILER
974 #pragma GCC diagnostic ignored "-Wcast-qual"
975 #endif
976
977 /* check and update cookies or panic (internal) */
978 void rte_mempool_check_cookies(const struct rte_mempool *mp,
979         void * const *obj_table_const, unsigned n, int free)
980 {
981 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
982         struct rte_mempool_objhdr *hdr;
983         struct rte_mempool_objtlr *tlr;
984         uint64_t cookie;
985         void *tmp;
986         void *obj;
987         void **obj_table;
988
989         /* Force to drop the "const" attribute. This is done only when
990          * DEBUG is enabled */
991         tmp = (void *) obj_table_const;
992         obj_table = (void **) tmp;
993
994         while (n--) {
995                 obj = obj_table[n];
996
997                 if (rte_mempool_from_obj(obj) != mp)
998                         rte_panic("MEMPOOL: object is owned by another "
999                                   "mempool\n");
1000
1001                 hdr = __mempool_get_header(obj);
1002                 cookie = hdr->cookie;
1003
1004                 if (free == 0) {
1005                         if (cookie != RTE_MEMPOOL_HEADER_COOKIE1) {
1006                                 RTE_LOG(CRIT, MEMPOOL,
1007                                         "obj=%p, mempool=%p, cookie=%" PRIx64 "\n",
1008                                         obj, (const void *) mp, cookie);
1009                                 rte_panic("MEMPOOL: bad header cookie (put)\n");
1010                         }
1011                         hdr->cookie = RTE_MEMPOOL_HEADER_COOKIE2;
1012                 } else if (free == 1) {
1013                         if (cookie != RTE_MEMPOOL_HEADER_COOKIE2) {
1014                                 RTE_LOG(CRIT, MEMPOOL,
1015                                         "obj=%p, mempool=%p, cookie=%" PRIx64 "\n",
1016                                         obj, (const void *) mp, cookie);
1017                                 rte_panic("MEMPOOL: bad header cookie (get)\n");
1018                         }
1019                         hdr->cookie = RTE_MEMPOOL_HEADER_COOKIE1;
1020                 } else if (free == 2) {
1021                         if (cookie != RTE_MEMPOOL_HEADER_COOKIE1 &&
1022                             cookie != RTE_MEMPOOL_HEADER_COOKIE2) {
1023                                 RTE_LOG(CRIT, MEMPOOL,
1024                                         "obj=%p, mempool=%p, cookie=%" PRIx64 "\n",
1025                                         obj, (const void *) mp, cookie);
1026                                 rte_panic("MEMPOOL: bad header cookie (audit)\n");
1027                         }
1028                 }
1029                 tlr = __mempool_get_trailer(obj);
1030                 cookie = tlr->cookie;
1031                 if (cookie != RTE_MEMPOOL_TRAILER_COOKIE) {
1032                         RTE_LOG(CRIT, MEMPOOL,
1033                                 "obj=%p, mempool=%p, cookie=%" PRIx64 "\n",
1034                                 obj, (const void *) mp, cookie);
1035                         rte_panic("MEMPOOL: bad trailer cookie\n");
1036                 }
1037         }
1038 #else
1039         RTE_SET_USED(mp);
1040         RTE_SET_USED(obj_table_const);
1041         RTE_SET_USED(n);
1042         RTE_SET_USED(free);
1043 #endif
1044 }
1045
1046 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
1047 static void
1048 mempool_obj_audit(struct rte_mempool *mp, __rte_unused void *opaque,
1049         void *obj, __rte_unused unsigned idx)
1050 {
1051         __mempool_check_cookies(mp, &obj, 1, 2);
1052 }
1053
1054 static void
1055 mempool_audit_cookies(struct rte_mempool *mp)
1056 {
1057         unsigned num;
1058
1059         num = rte_mempool_obj_iter(mp, mempool_obj_audit, NULL);
1060         if (num != mp->size) {
1061                 rte_panic("rte_mempool_obj_iter(mempool=%p, size=%u) "
1062                         "iterated only over %u elements\n",
1063                         mp, mp->size, num);
1064         }
1065 }
1066 #else
1067 #define mempool_audit_cookies(mp) do {} while(0)
1068 #endif
1069
1070 #ifndef __INTEL_COMPILER
1071 #pragma GCC diagnostic error "-Wcast-qual"
1072 #endif
1073
1074 /* check cookies before and after objects */
1075 static void
1076 mempool_audit_cache(const struct rte_mempool *mp)
1077 {
1078         /* check cache size consistency */
1079         unsigned lcore_id;
1080
1081         if (mp->cache_size == 0)
1082                 return;
1083
1084         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
1085                 if (mp->local_cache[lcore_id].len > mp->cache_flushthresh) {
1086                         RTE_LOG(CRIT, MEMPOOL, "badness on cache[%u]\n",
1087                                 lcore_id);
1088                         rte_panic("MEMPOOL: invalid cache len\n");
1089                 }
1090         }
1091 }
1092
1093 /* check the consistency of mempool (size, cookies, ...) */
1094 void
1095 rte_mempool_audit(struct rte_mempool *mp)
1096 {
1097         mempool_audit_cache(mp);
1098         mempool_audit_cookies(mp);
1099
1100         /* For case where mempool DEBUG is not set, and cache size is 0 */
1101         RTE_SET_USED(mp);
1102 }
1103
1104 /* dump the status of the mempool on the console */
1105 void
1106 rte_mempool_dump(FILE *f, struct rte_mempool *mp)
1107 {
1108 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
1109         struct rte_mempool_debug_stats sum;
1110         unsigned lcore_id;
1111 #endif
1112         struct rte_mempool_memhdr *memhdr;
1113         unsigned common_count;
1114         unsigned cache_count;
1115         size_t mem_len = 0;
1116
1117         RTE_ASSERT(f != NULL);
1118         RTE_ASSERT(mp != NULL);
1119
1120         fprintf(f, "mempool <%s>@%p\n", mp->name, mp);
1121         fprintf(f, "  flags=%x\n", mp->flags);
1122         fprintf(f, "  ring=<%s>@%p\n", mp->ring->name, mp->ring);
1123         fprintf(f, "  phys_addr=0x%" PRIx64 "\n", mp->mz->phys_addr);
1124         fprintf(f, "  nb_mem_chunks=%u\n", mp->nb_mem_chunks);
1125         fprintf(f, "  size=%"PRIu32"\n", mp->size);
1126         fprintf(f, "  populated_size=%"PRIu32"\n", mp->populated_size);
1127         fprintf(f, "  header_size=%"PRIu32"\n", mp->header_size);
1128         fprintf(f, "  elt_size=%"PRIu32"\n", mp->elt_size);
1129         fprintf(f, "  trailer_size=%"PRIu32"\n", mp->trailer_size);
1130         fprintf(f, "  total_obj_size=%"PRIu32"\n",
1131                mp->header_size + mp->elt_size + mp->trailer_size);
1132
1133         fprintf(f, "  private_data_size=%"PRIu32"\n", mp->private_data_size);
1134
1135         STAILQ_FOREACH(memhdr, &mp->mem_list, next)
1136                 mem_len += memhdr->len;
1137         if (mem_len != 0) {
1138                 fprintf(f, "  avg bytes/object=%#Lf\n",
1139                         (long double)mem_len / mp->size);
1140         }
1141
1142         cache_count = rte_mempool_dump_cache(f, mp);
1143         common_count = rte_ring_count(mp->ring);
1144         if ((cache_count + common_count) > mp->size)
1145                 common_count = mp->size - cache_count;
1146         fprintf(f, "  common_pool_count=%u\n", common_count);
1147
1148         /* sum and dump statistics */
1149 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
1150         memset(&sum, 0, sizeof(sum));
1151         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
1152                 sum.put_bulk += mp->stats[lcore_id].put_bulk;
1153                 sum.put_objs += mp->stats[lcore_id].put_objs;
1154                 sum.get_success_bulk += mp->stats[lcore_id].get_success_bulk;
1155                 sum.get_success_objs += mp->stats[lcore_id].get_success_objs;
1156                 sum.get_fail_bulk += mp->stats[lcore_id].get_fail_bulk;
1157                 sum.get_fail_objs += mp->stats[lcore_id].get_fail_objs;
1158         }
1159         fprintf(f, "  stats:\n");
1160         fprintf(f, "    put_bulk=%"PRIu64"\n", sum.put_bulk);
1161         fprintf(f, "    put_objs=%"PRIu64"\n", sum.put_objs);
1162         fprintf(f, "    get_success_bulk=%"PRIu64"\n", sum.get_success_bulk);
1163         fprintf(f, "    get_success_objs=%"PRIu64"\n", sum.get_success_objs);
1164         fprintf(f, "    get_fail_bulk=%"PRIu64"\n", sum.get_fail_bulk);
1165         fprintf(f, "    get_fail_objs=%"PRIu64"\n", sum.get_fail_objs);
1166 #else
1167         fprintf(f, "  no statistics available\n");
1168 #endif
1169
1170         rte_mempool_audit(mp);
1171 }
1172
1173 /* dump the status of all mempools on the console */
1174 void
1175 rte_mempool_list_dump(FILE *f)
1176 {
1177         struct rte_mempool *mp = NULL;
1178         struct rte_tailq_entry *te;
1179         struct rte_mempool_list *mempool_list;
1180
1181         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
1182
1183         rte_rwlock_read_lock(RTE_EAL_MEMPOOL_RWLOCK);
1184
1185         TAILQ_FOREACH(te, mempool_list, next) {
1186                 mp = (struct rte_mempool *) te->data;
1187                 rte_mempool_dump(f, mp);
1188         }
1189
1190         rte_rwlock_read_unlock(RTE_EAL_MEMPOOL_RWLOCK);
1191 }
1192
1193 /* search a mempool from its name */
1194 struct rte_mempool *
1195 rte_mempool_lookup(const char *name)
1196 {
1197         struct rte_mempool *mp = NULL;
1198         struct rte_tailq_entry *te;
1199         struct rte_mempool_list *mempool_list;
1200
1201         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
1202
1203         rte_rwlock_read_lock(RTE_EAL_MEMPOOL_RWLOCK);
1204
1205         TAILQ_FOREACH(te, mempool_list, next) {
1206                 mp = (struct rte_mempool *) te->data;
1207                 if (strncmp(name, mp->name, RTE_MEMPOOL_NAMESIZE) == 0)
1208                         break;
1209         }
1210
1211         rte_rwlock_read_unlock(RTE_EAL_MEMPOOL_RWLOCK);
1212
1213         if (te == NULL) {
1214                 rte_errno = ENOENT;
1215                 return NULL;
1216         }
1217
1218         return mp;
1219 }
1220
1221 void rte_mempool_walk(void (*func)(struct rte_mempool *, void *),
1222                       void *arg)
1223 {
1224         struct rte_tailq_entry *te = NULL;
1225         struct rte_mempool_list *mempool_list;
1226
1227         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
1228
1229         rte_rwlock_read_lock(RTE_EAL_MEMPOOL_RWLOCK);
1230
1231         TAILQ_FOREACH(te, mempool_list, next) {
1232                 (*func)((struct rte_mempool *) te->data, arg);
1233         }
1234
1235         rte_rwlock_read_unlock(RTE_EAL_MEMPOOL_RWLOCK);
1236 }