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