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