mempool: fix slow allocation of large pools
[dpdk.git] / lib / librte_mempool / rte_mempool.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2014 Intel Corporation.
3  * Copyright(c) 2016 6WIND S.A.
4  */
5
6 #include <stdbool.h>
7 #include <stdio.h>
8 #include <string.h>
9 #include <stdint.h>
10 #include <stdarg.h>
11 #include <unistd.h>
12 #include <inttypes.h>
13 #include <errno.h>
14 #include <sys/queue.h>
15 #include <sys/mman.h>
16
17 #include <rte_common.h>
18 #include <rte_log.h>
19 #include <rte_debug.h>
20 #include <rte_memory.h>
21 #include <rte_memzone.h>
22 #include <rte_malloc.h>
23 #include <rte_atomic.h>
24 #include <rte_launch.h>
25 #include <rte_eal.h>
26 #include <rte_eal_memconfig.h>
27 #include <rte_per_lcore.h>
28 #include <rte_lcore.h>
29 #include <rte_branch_prediction.h>
30 #include <rte_errno.h>
31 #include <rte_string_fns.h>
32 #include <rte_spinlock.h>
33 #include <rte_tailq.h>
34
35 #include "rte_mempool.h"
36
37 TAILQ_HEAD(rte_mempool_list, rte_tailq_entry);
38
39 static struct rte_tailq_elem rte_mempool_tailq = {
40         .name = "RTE_MEMPOOL",
41 };
42 EAL_REGISTER_TAILQ(rte_mempool_tailq)
43
44 #define CACHE_FLUSHTHRESH_MULTIPLIER 1.5
45 #define CALC_CACHE_FLUSHTHRESH(c)       \
46         ((typeof(c))((c) * CACHE_FLUSHTHRESH_MULTIPLIER))
47
48 /*
49  * return the greatest common divisor between a and b (fast algorithm)
50  *
51  */
52 static unsigned get_gcd(unsigned a, unsigned b)
53 {
54         unsigned c;
55
56         if (0 == a)
57                 return b;
58         if (0 == b)
59                 return a;
60
61         if (a < b) {
62                 c = a;
63                 a = b;
64                 b = c;
65         }
66
67         while (b != 0) {
68                 c = a % b;
69                 a = b;
70                 b = c;
71         }
72
73         return a;
74 }
75
76 /*
77  * Depending on memory configuration, objects addresses are spread
78  * between channels and ranks in RAM: the pool allocator will add
79  * padding between objects. This function return the new size of the
80  * object.
81  */
82 static unsigned optimize_object_size(unsigned obj_size)
83 {
84         unsigned nrank, nchan;
85         unsigned new_obj_size;
86
87         /* get number of channels */
88         nchan = rte_memory_get_nchannel();
89         if (nchan == 0)
90                 nchan = 4;
91
92         nrank = rte_memory_get_nrank();
93         if (nrank == 0)
94                 nrank = 1;
95
96         /* process new object size */
97         new_obj_size = (obj_size + RTE_MEMPOOL_ALIGN_MASK) / RTE_MEMPOOL_ALIGN;
98         while (get_gcd(new_obj_size, nrank * nchan) != 1)
99                 new_obj_size++;
100         return new_obj_size * RTE_MEMPOOL_ALIGN;
101 }
102
103 struct pagesz_walk_arg {
104         int socket_id;
105         size_t min;
106 };
107
108 static int
109 find_min_pagesz(const struct rte_memseg_list *msl, void *arg)
110 {
111         struct pagesz_walk_arg *wa = arg;
112         bool valid;
113
114         /*
115          * we need to only look at page sizes available for a particular socket
116          * ID.  so, we either need an exact match on socket ID (can match both
117          * native and external memory), or, if SOCKET_ID_ANY was specified as a
118          * socket ID argument, we must only look at native memory and ignore any
119          * page sizes associated with external memory.
120          */
121         valid = msl->socket_id == wa->socket_id;
122         valid |= wa->socket_id == SOCKET_ID_ANY && msl->external == 0;
123
124         if (valid && msl->page_sz < wa->min)
125                 wa->min = msl->page_sz;
126
127         return 0;
128 }
129
130 static size_t
131 get_min_page_size(int socket_id)
132 {
133         struct pagesz_walk_arg wa;
134
135         wa.min = SIZE_MAX;
136         wa.socket_id = socket_id;
137
138         rte_memseg_list_walk(find_min_pagesz, &wa);
139
140         return wa.min == SIZE_MAX ? (size_t) getpagesize() : wa.min;
141 }
142
143
144 static void
145 mempool_add_elem(struct rte_mempool *mp, __rte_unused void *opaque,
146                  void *obj, rte_iova_t iova)
147 {
148         struct rte_mempool_objhdr *hdr;
149         struct rte_mempool_objtlr *tlr __rte_unused;
150
151         /* set mempool ptr in header */
152         hdr = RTE_PTR_SUB(obj, sizeof(*hdr));
153         hdr->mp = mp;
154         hdr->iova = iova;
155         STAILQ_INSERT_TAIL(&mp->elt_list, hdr, next);
156         mp->populated_size++;
157
158 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
159         hdr->cookie = RTE_MEMPOOL_HEADER_COOKIE2;
160         tlr = __mempool_get_trailer(obj);
161         tlr->cookie = RTE_MEMPOOL_TRAILER_COOKIE;
162 #endif
163 }
164
165 /* call obj_cb() for each mempool element */
166 uint32_t
167 rte_mempool_obj_iter(struct rte_mempool *mp,
168         rte_mempool_obj_cb_t *obj_cb, void *obj_cb_arg)
169 {
170         struct rte_mempool_objhdr *hdr;
171         void *obj;
172         unsigned n = 0;
173
174         STAILQ_FOREACH(hdr, &mp->elt_list, next) {
175                 obj = (char *)hdr + sizeof(*hdr);
176                 obj_cb(mp, obj_cb_arg, obj, n);
177                 n++;
178         }
179
180         return n;
181 }
182
183 /* call mem_cb() for each mempool memory chunk */
184 uint32_t
185 rte_mempool_mem_iter(struct rte_mempool *mp,
186         rte_mempool_mem_cb_t *mem_cb, void *mem_cb_arg)
187 {
188         struct rte_mempool_memhdr *hdr;
189         unsigned n = 0;
190
191         STAILQ_FOREACH(hdr, &mp->mem_list, next) {
192                 mem_cb(mp, mem_cb_arg, hdr, n);
193                 n++;
194         }
195
196         return n;
197 }
198
199 /* get the header, trailer and total size of a mempool element. */
200 uint32_t
201 rte_mempool_calc_obj_size(uint32_t elt_size, uint32_t flags,
202         struct rte_mempool_objsz *sz)
203 {
204         struct rte_mempool_objsz lsz;
205
206         sz = (sz != NULL) ? sz : &lsz;
207
208         sz->header_size = sizeof(struct rte_mempool_objhdr);
209         if ((flags & MEMPOOL_F_NO_CACHE_ALIGN) == 0)
210                 sz->header_size = RTE_ALIGN_CEIL(sz->header_size,
211                         RTE_MEMPOOL_ALIGN);
212
213 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
214         sz->trailer_size = sizeof(struct rte_mempool_objtlr);
215 #else
216         sz->trailer_size = 0;
217 #endif
218
219         /* element size is 8 bytes-aligned at least */
220         sz->elt_size = RTE_ALIGN_CEIL(elt_size, sizeof(uint64_t));
221
222         /* expand trailer to next cache line */
223         if ((flags & MEMPOOL_F_NO_CACHE_ALIGN) == 0) {
224                 sz->total_size = sz->header_size + sz->elt_size +
225                         sz->trailer_size;
226                 sz->trailer_size += ((RTE_MEMPOOL_ALIGN -
227                                   (sz->total_size & RTE_MEMPOOL_ALIGN_MASK)) &
228                                  RTE_MEMPOOL_ALIGN_MASK);
229         }
230
231         /*
232          * increase trailer to add padding between objects in order to
233          * spread them across memory channels/ranks
234          */
235         if ((flags & MEMPOOL_F_NO_SPREAD) == 0) {
236                 unsigned new_size;
237                 new_size = optimize_object_size(sz->header_size + sz->elt_size +
238                         sz->trailer_size);
239                 sz->trailer_size = new_size - sz->header_size - sz->elt_size;
240         }
241
242         /* this is the size of an object, including header and trailer */
243         sz->total_size = sz->header_size + sz->elt_size + sz->trailer_size;
244
245         return sz->total_size;
246 }
247
248 /* free a memchunk allocated with rte_memzone_reserve() */
249 static void
250 rte_mempool_memchunk_mz_free(__rte_unused struct rte_mempool_memhdr *memhdr,
251         void *opaque)
252 {
253         const struct rte_memzone *mz = opaque;
254         rte_memzone_free(mz);
255 }
256
257 /* Free memory chunks used by a mempool. Objects must be in pool */
258 static void
259 rte_mempool_free_memchunks(struct rte_mempool *mp)
260 {
261         struct rte_mempool_memhdr *memhdr;
262         void *elt;
263
264         while (!STAILQ_EMPTY(&mp->elt_list)) {
265                 rte_mempool_ops_dequeue_bulk(mp, &elt, 1);
266                 (void)elt;
267                 STAILQ_REMOVE_HEAD(&mp->elt_list, next);
268                 mp->populated_size--;
269         }
270
271         while (!STAILQ_EMPTY(&mp->mem_list)) {
272                 memhdr = STAILQ_FIRST(&mp->mem_list);
273                 STAILQ_REMOVE_HEAD(&mp->mem_list, next);
274                 if (memhdr->free_cb != NULL)
275                         memhdr->free_cb(memhdr, memhdr->opaque);
276                 rte_free(memhdr);
277                 mp->nb_mem_chunks--;
278         }
279 }
280
281 static int
282 mempool_ops_alloc_once(struct rte_mempool *mp)
283 {
284         int ret;
285
286         /* create the internal ring if not already done */
287         if ((mp->flags & MEMPOOL_F_POOL_CREATED) == 0) {
288                 ret = rte_mempool_ops_alloc(mp);
289                 if (ret != 0)
290                         return ret;
291                 mp->flags |= MEMPOOL_F_POOL_CREATED;
292         }
293         return 0;
294 }
295
296 /* Add objects in the pool, using a physically contiguous memory
297  * zone. Return the number of objects added, or a negative value
298  * on error.
299  */
300 int
301 rte_mempool_populate_iova(struct rte_mempool *mp, char *vaddr,
302         rte_iova_t iova, size_t len, rte_mempool_memchunk_free_cb_t *free_cb,
303         void *opaque)
304 {
305         unsigned i = 0;
306         size_t off;
307         struct rte_mempool_memhdr *memhdr;
308         int ret;
309
310         ret = mempool_ops_alloc_once(mp);
311         if (ret != 0)
312                 return ret;
313
314         /* mempool is already populated */
315         if (mp->populated_size >= mp->size)
316                 return -ENOSPC;
317
318         memhdr = rte_zmalloc("MEMPOOL_MEMHDR", sizeof(*memhdr), 0);
319         if (memhdr == NULL)
320                 return -ENOMEM;
321
322         memhdr->mp = mp;
323         memhdr->addr = vaddr;
324         memhdr->iova = iova;
325         memhdr->len = len;
326         memhdr->free_cb = free_cb;
327         memhdr->opaque = opaque;
328
329         if (mp->flags & MEMPOOL_F_NO_CACHE_ALIGN)
330                 off = RTE_PTR_ALIGN_CEIL(vaddr, 8) - vaddr;
331         else
332                 off = RTE_PTR_ALIGN_CEIL(vaddr, RTE_MEMPOOL_ALIGN) - vaddr;
333
334         if (off > len) {
335                 ret = -EINVAL;
336                 goto fail;
337         }
338
339         i = rte_mempool_ops_populate(mp, mp->size - mp->populated_size,
340                 (char *)vaddr + off,
341                 (iova == RTE_BAD_IOVA) ? RTE_BAD_IOVA : (iova + off),
342                 len - off, mempool_add_elem, NULL);
343
344         /* not enough room to store one object */
345         if (i == 0) {
346                 ret = -EINVAL;
347                 goto fail;
348         }
349
350         STAILQ_INSERT_TAIL(&mp->mem_list, memhdr, next);
351         mp->nb_mem_chunks++;
352         return i;
353
354 fail:
355         rte_free(memhdr);
356         return ret;
357 }
358
359 static rte_iova_t
360 get_iova(void *addr)
361 {
362         struct rte_memseg *ms;
363
364         /* try registered memory first */
365         ms = rte_mem_virt2memseg(addr, NULL);
366         if (ms == NULL || ms->iova == RTE_BAD_IOVA)
367                 /* fall back to actual physical address */
368                 return rte_mem_virt2iova(addr);
369         return ms->iova + RTE_PTR_DIFF(addr, ms->addr);
370 }
371
372 /* Populate the mempool with a virtual area. Return the number of
373  * objects added, or a negative value on error.
374  */
375 int
376 rte_mempool_populate_virt(struct rte_mempool *mp, char *addr,
377         size_t len, size_t pg_sz, rte_mempool_memchunk_free_cb_t *free_cb,
378         void *opaque)
379 {
380         rte_iova_t iova;
381         size_t off, phys_len;
382         int ret, cnt = 0;
383
384         if (mp->flags & MEMPOOL_F_NO_IOVA_CONTIG)
385                 return rte_mempool_populate_iova(mp, addr, RTE_BAD_IOVA,
386                         len, free_cb, opaque);
387
388         for (off = 0; off < len &&
389                      mp->populated_size < mp->size; off += phys_len) {
390
391                 iova = get_iova(addr + off);
392
393                 /* populate with the largest group of contiguous pages */
394                 for (phys_len = RTE_MIN(
395                         (size_t)(RTE_PTR_ALIGN_CEIL(addr + off + 1, pg_sz) -
396                                 (addr + off)),
397                         len - off);
398                      off + phys_len < len;
399                      phys_len = RTE_MIN(phys_len + pg_sz, len - off)) {
400                         rte_iova_t iova_tmp;
401
402                         iova_tmp = get_iova(addr + off + phys_len);
403
404                         if (iova_tmp == RTE_BAD_IOVA ||
405                                         iova_tmp != iova + phys_len)
406                                 break;
407                 }
408
409                 ret = rte_mempool_populate_iova(mp, addr + off, iova,
410                         phys_len, free_cb, opaque);
411                 if (ret < 0)
412                         goto fail;
413                 /* no need to call the free callback for next chunks */
414                 free_cb = NULL;
415                 cnt += ret;
416         }
417
418         return cnt;
419
420  fail:
421         rte_mempool_free_memchunks(mp);
422         return ret;
423 }
424
425 /* Get the minimal page size used in a mempool before populating it. */
426 int
427 rte_mempool_get_page_size(struct rte_mempool *mp, size_t *pg_sz)
428 {
429         bool need_iova_contig_obj;
430         bool alloc_in_ext_mem;
431         int ret;
432
433         /* check if we can retrieve a valid socket ID */
434         ret = rte_malloc_heap_socket_is_external(mp->socket_id);
435         if (ret < 0)
436                 return -EINVAL;
437         alloc_in_ext_mem = (ret == 1);
438         need_iova_contig_obj = !(mp->flags & MEMPOOL_F_NO_IOVA_CONTIG);
439
440         if (!need_iova_contig_obj)
441                 *pg_sz = 0;
442         else if (rte_eal_has_hugepages() || alloc_in_ext_mem)
443                 *pg_sz = get_min_page_size(mp->socket_id);
444         else
445                 *pg_sz = getpagesize();
446
447         return 0;
448 }
449
450 /* Default function to populate the mempool: allocate memory in memzones,
451  * and populate them. Return the number of objects added, or a negative
452  * value on error.
453  */
454 int
455 rte_mempool_populate_default(struct rte_mempool *mp)
456 {
457         unsigned int mz_flags = RTE_MEMZONE_1GB|RTE_MEMZONE_SIZE_HINT_ONLY;
458         char mz_name[RTE_MEMZONE_NAMESIZE];
459         const struct rte_memzone *mz;
460         ssize_t mem_size;
461         size_t align, pg_sz, pg_shift = 0;
462         rte_iova_t iova;
463         unsigned mz_id, n;
464         int ret;
465         bool need_iova_contig_obj;
466         size_t max_alloc_size = SIZE_MAX;
467
468         ret = mempool_ops_alloc_once(mp);
469         if (ret != 0)
470                 return ret;
471
472         /* mempool must not be populated */
473         if (mp->nb_mem_chunks != 0)
474                 return -EEXIST;
475
476         /*
477          * the following section calculates page shift and page size values.
478          *
479          * these values impact the result of calc_mem_size operation, which
480          * returns the amount of memory that should be allocated to store the
481          * desired number of objects. when not zero, it allocates more memory
482          * for the padding between objects, to ensure that an object does not
483          * cross a page boundary. in other words, page size/shift are to be set
484          * to zero if mempool elements won't care about page boundaries.
485          * there are several considerations for page size and page shift here.
486          *
487          * if we don't need our mempools to have physically contiguous objects,
488          * then just set page shift and page size to 0, because the user has
489          * indicated that there's no need to care about anything.
490          *
491          * if we do need contiguous objects (if a mempool driver has its
492          * own calc_size() method returning min_chunk_size = mem_size),
493          * there is also an option to reserve the entire mempool memory
494          * as one contiguous block of memory.
495          *
496          * if we require contiguous objects, but not necessarily the entire
497          * mempool reserved space to be contiguous, pg_sz will be != 0,
498          * and the default ops->populate() will take care of not placing
499          * objects across pages.
500          *
501          * if our IO addresses are physical, we may get memory from bigger
502          * pages, or we might get memory from smaller pages, and how much of it
503          * we require depends on whether we want bigger or smaller pages.
504          * However, requesting each and every memory size is too much work, so
505          * what we'll do instead is walk through the page sizes available, pick
506          * the smallest one and set up page shift to match that one. We will be
507          * wasting some space this way, but it's much nicer than looping around
508          * trying to reserve each and every page size.
509          *
510          * If we fail to get enough contiguous memory, then we'll go and
511          * reserve space in smaller chunks.
512          */
513
514         need_iova_contig_obj = !(mp->flags & MEMPOOL_F_NO_IOVA_CONTIG);
515         ret = rte_mempool_get_page_size(mp, &pg_sz);
516         if (ret < 0)
517                 return ret;
518
519         if (pg_sz != 0)
520                 pg_shift = rte_bsf32(pg_sz);
521
522         for (mz_id = 0, n = mp->size; n > 0; mz_id++, n -= ret) {
523                 size_t min_chunk_size;
524
525                 mem_size = rte_mempool_ops_calc_mem_size(
526                         mp, n, pg_shift, &min_chunk_size, &align);
527
528                 if (mem_size < 0) {
529                         ret = mem_size;
530                         goto fail;
531                 }
532
533                 ret = snprintf(mz_name, sizeof(mz_name),
534                         RTE_MEMPOOL_MZ_FORMAT "_%d", mp->name, mz_id);
535                 if (ret < 0 || ret >= (int)sizeof(mz_name)) {
536                         ret = -ENAMETOOLONG;
537                         goto fail;
538                 }
539
540                 /* if we're trying to reserve contiguous memory, add appropriate
541                  * memzone flag.
542                  */
543                 if (min_chunk_size == (size_t)mem_size)
544                         mz_flags |= RTE_MEMZONE_IOVA_CONTIG;
545
546                 /* Allocate a memzone, retrying with a smaller area on ENOMEM */
547                 do {
548                         mz = rte_memzone_reserve_aligned(mz_name,
549                                 RTE_MIN((size_t)mem_size, max_alloc_size),
550                                 mp->socket_id, mz_flags, align);
551
552                         if (mz == NULL && rte_errno != ENOMEM)
553                                 break;
554
555                         max_alloc_size = RTE_MIN(max_alloc_size,
556                                                 (size_t)mem_size) / 2;
557                 } while (mz == NULL && max_alloc_size >= min_chunk_size);
558
559                 if (mz == NULL) {
560                         ret = -rte_errno;
561                         goto fail;
562                 }
563
564                 if (need_iova_contig_obj)
565                         iova = mz->iova;
566                 else
567                         iova = RTE_BAD_IOVA;
568
569                 if (pg_sz == 0 || (mz_flags & RTE_MEMZONE_IOVA_CONTIG))
570                         ret = rte_mempool_populate_iova(mp, mz->addr,
571                                 iova, mz->len,
572                                 rte_mempool_memchunk_mz_free,
573                                 (void *)(uintptr_t)mz);
574                 else
575                         ret = rte_mempool_populate_virt(mp, mz->addr,
576                                 mz->len, pg_sz,
577                                 rte_mempool_memchunk_mz_free,
578                                 (void *)(uintptr_t)mz);
579                 if (ret < 0) {
580                         rte_memzone_free(mz);
581                         goto fail;
582                 }
583         }
584
585         return mp->size;
586
587  fail:
588         rte_mempool_free_memchunks(mp);
589         return ret;
590 }
591
592 /* return the memory size required for mempool objects in anonymous mem */
593 static ssize_t
594 get_anon_size(const struct rte_mempool *mp)
595 {
596         ssize_t size;
597         size_t pg_sz, pg_shift;
598         size_t min_chunk_size;
599         size_t align;
600
601         pg_sz = getpagesize();
602         pg_shift = rte_bsf32(pg_sz);
603         size = rte_mempool_ops_calc_mem_size(mp, mp->size, pg_shift,
604                                              &min_chunk_size, &align);
605
606         return size;
607 }
608
609 /* unmap a memory zone mapped by rte_mempool_populate_anon() */
610 static void
611 rte_mempool_memchunk_anon_free(struct rte_mempool_memhdr *memhdr,
612         void *opaque)
613 {
614         ssize_t size;
615
616         /*
617          * Calculate size since memhdr->len has contiguous chunk length
618          * which may be smaller if anon map is split into many contiguous
619          * chunks. Result must be the same as we calculated on populate.
620          */
621         size = get_anon_size(memhdr->mp);
622         if (size < 0)
623                 return;
624
625         munmap(opaque, size);
626 }
627
628 /* populate the mempool with an anonymous mapping */
629 int
630 rte_mempool_populate_anon(struct rte_mempool *mp)
631 {
632         ssize_t size;
633         int ret;
634         char *addr;
635
636         /* mempool is already populated, error */
637         if ((!STAILQ_EMPTY(&mp->mem_list)) || mp->nb_mem_chunks != 0) {
638                 rte_errno = EINVAL;
639                 return 0;
640         }
641
642         ret = mempool_ops_alloc_once(mp);
643         if (ret < 0) {
644                 rte_errno = -ret;
645                 return 0;
646         }
647
648         size = get_anon_size(mp);
649         if (size < 0) {
650                 rte_errno = -size;
651                 return 0;
652         }
653
654         /* get chunk of virtually continuous memory */
655         addr = mmap(NULL, size, PROT_READ | PROT_WRITE,
656                 MAP_SHARED | MAP_ANONYMOUS, -1, 0);
657         if (addr == MAP_FAILED) {
658                 rte_errno = errno;
659                 return 0;
660         }
661         /* can't use MMAP_LOCKED, it does not exist on BSD */
662         if (mlock(addr, size) < 0) {
663                 rte_errno = errno;
664                 munmap(addr, size);
665                 return 0;
666         }
667
668         ret = rte_mempool_populate_virt(mp, addr, size, getpagesize(),
669                 rte_mempool_memchunk_anon_free, addr);
670         if (ret < 0) {
671                 rte_errno = -ret;
672                 goto fail;
673         }
674
675         return mp->populated_size;
676
677  fail:
678         rte_mempool_free_memchunks(mp);
679         return 0;
680 }
681
682 /* free a mempool */
683 void
684 rte_mempool_free(struct rte_mempool *mp)
685 {
686         struct rte_mempool_list *mempool_list = NULL;
687         struct rte_tailq_entry *te;
688
689         if (mp == NULL)
690                 return;
691
692         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
693         rte_mcfg_tailq_write_lock();
694         /* find out tailq entry */
695         TAILQ_FOREACH(te, mempool_list, next) {
696                 if (te->data == (void *)mp)
697                         break;
698         }
699
700         if (te != NULL) {
701                 TAILQ_REMOVE(mempool_list, te, next);
702                 rte_free(te);
703         }
704         rte_mcfg_tailq_write_unlock();
705
706         rte_mempool_free_memchunks(mp);
707         rte_mempool_ops_free(mp);
708         rte_memzone_free(mp->mz);
709 }
710
711 static void
712 mempool_cache_init(struct rte_mempool_cache *cache, uint32_t size)
713 {
714         cache->size = size;
715         cache->flushthresh = CALC_CACHE_FLUSHTHRESH(size);
716         cache->len = 0;
717 }
718
719 /*
720  * Create and initialize a cache for objects that are retrieved from and
721  * returned to an underlying mempool. This structure is identical to the
722  * local_cache[lcore_id] pointed to by the mempool structure.
723  */
724 struct rte_mempool_cache *
725 rte_mempool_cache_create(uint32_t size, int socket_id)
726 {
727         struct rte_mempool_cache *cache;
728
729         if (size == 0 || size > RTE_MEMPOOL_CACHE_MAX_SIZE) {
730                 rte_errno = EINVAL;
731                 return NULL;
732         }
733
734         cache = rte_zmalloc_socket("MEMPOOL_CACHE", sizeof(*cache),
735                                   RTE_CACHE_LINE_SIZE, socket_id);
736         if (cache == NULL) {
737                 RTE_LOG(ERR, MEMPOOL, "Cannot allocate mempool cache.\n");
738                 rte_errno = ENOMEM;
739                 return NULL;
740         }
741
742         mempool_cache_init(cache, size);
743
744         return cache;
745 }
746
747 /*
748  * Free a cache. It's the responsibility of the user to make sure that any
749  * remaining objects in the cache are flushed to the corresponding
750  * mempool.
751  */
752 void
753 rte_mempool_cache_free(struct rte_mempool_cache *cache)
754 {
755         rte_free(cache);
756 }
757
758 /* create an empty mempool */
759 struct rte_mempool *
760 rte_mempool_create_empty(const char *name, unsigned n, unsigned elt_size,
761         unsigned cache_size, unsigned private_data_size,
762         int socket_id, unsigned flags)
763 {
764         char mz_name[RTE_MEMZONE_NAMESIZE];
765         struct rte_mempool_list *mempool_list;
766         struct rte_mempool *mp = NULL;
767         struct rte_tailq_entry *te = NULL;
768         const struct rte_memzone *mz = NULL;
769         size_t mempool_size;
770         unsigned int mz_flags = RTE_MEMZONE_1GB|RTE_MEMZONE_SIZE_HINT_ONLY;
771         struct rte_mempool_objsz objsz;
772         unsigned lcore_id;
773         int ret;
774
775         /* compilation-time checks */
776         RTE_BUILD_BUG_ON((sizeof(struct rte_mempool) &
777                           RTE_CACHE_LINE_MASK) != 0);
778         RTE_BUILD_BUG_ON((sizeof(struct rte_mempool_cache) &
779                           RTE_CACHE_LINE_MASK) != 0);
780 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
781         RTE_BUILD_BUG_ON((sizeof(struct rte_mempool_debug_stats) &
782                           RTE_CACHE_LINE_MASK) != 0);
783         RTE_BUILD_BUG_ON((offsetof(struct rte_mempool, stats) &
784                           RTE_CACHE_LINE_MASK) != 0);
785 #endif
786
787         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
788
789         /* asked for zero items */
790         if (n == 0) {
791                 rte_errno = EINVAL;
792                 return NULL;
793         }
794
795         /* asked cache too big */
796         if (cache_size > RTE_MEMPOOL_CACHE_MAX_SIZE ||
797             CALC_CACHE_FLUSHTHRESH(cache_size) > n) {
798                 rte_errno = EINVAL;
799                 return NULL;
800         }
801
802         /* "no cache align" imply "no spread" */
803         if (flags & MEMPOOL_F_NO_CACHE_ALIGN)
804                 flags |= MEMPOOL_F_NO_SPREAD;
805
806         /* calculate mempool object sizes. */
807         if (!rte_mempool_calc_obj_size(elt_size, flags, &objsz)) {
808                 rte_errno = EINVAL;
809                 return NULL;
810         }
811
812         rte_mcfg_mempool_write_lock();
813
814         /*
815          * reserve a memory zone for this mempool: private data is
816          * cache-aligned
817          */
818         private_data_size = (private_data_size +
819                              RTE_MEMPOOL_ALIGN_MASK) & (~RTE_MEMPOOL_ALIGN_MASK);
820
821
822         /* try to allocate tailq entry */
823         te = rte_zmalloc("MEMPOOL_TAILQ_ENTRY", sizeof(*te), 0);
824         if (te == NULL) {
825                 RTE_LOG(ERR, MEMPOOL, "Cannot allocate tailq entry!\n");
826                 goto exit_unlock;
827         }
828
829         mempool_size = MEMPOOL_HEADER_SIZE(mp, cache_size);
830         mempool_size += private_data_size;
831         mempool_size = RTE_ALIGN_CEIL(mempool_size, RTE_MEMPOOL_ALIGN);
832
833         ret = snprintf(mz_name, sizeof(mz_name), RTE_MEMPOOL_MZ_FORMAT, name);
834         if (ret < 0 || ret >= (int)sizeof(mz_name)) {
835                 rte_errno = ENAMETOOLONG;
836                 goto exit_unlock;
837         }
838
839         mz = rte_memzone_reserve(mz_name, mempool_size, socket_id, mz_flags);
840         if (mz == NULL)
841                 goto exit_unlock;
842
843         /* init the mempool structure */
844         mp = mz->addr;
845         memset(mp, 0, MEMPOOL_HEADER_SIZE(mp, cache_size));
846         ret = strlcpy(mp->name, name, sizeof(mp->name));
847         if (ret < 0 || ret >= (int)sizeof(mp->name)) {
848                 rte_errno = ENAMETOOLONG;
849                 goto exit_unlock;
850         }
851         mp->mz = mz;
852         mp->size = n;
853         mp->flags = flags;
854         mp->socket_id = socket_id;
855         mp->elt_size = objsz.elt_size;
856         mp->header_size = objsz.header_size;
857         mp->trailer_size = objsz.trailer_size;
858         /* Size of default caches, zero means disabled. */
859         mp->cache_size = cache_size;
860         mp->private_data_size = private_data_size;
861         STAILQ_INIT(&mp->elt_list);
862         STAILQ_INIT(&mp->mem_list);
863
864         /*
865          * local_cache pointer is set even if cache_size is zero.
866          * The local_cache points to just past the elt_pa[] array.
867          */
868         mp->local_cache = (struct rte_mempool_cache *)
869                 RTE_PTR_ADD(mp, MEMPOOL_HEADER_SIZE(mp, 0));
870
871         /* Init all default caches. */
872         if (cache_size != 0) {
873                 for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++)
874                         mempool_cache_init(&mp->local_cache[lcore_id],
875                                            cache_size);
876         }
877
878         te->data = mp;
879
880         rte_mcfg_tailq_write_lock();
881         TAILQ_INSERT_TAIL(mempool_list, te, next);
882         rte_mcfg_tailq_write_unlock();
883         rte_mcfg_mempool_write_unlock();
884
885         return mp;
886
887 exit_unlock:
888         rte_mcfg_mempool_write_unlock();
889         rte_free(te);
890         rte_mempool_free(mp);
891         return NULL;
892 }
893
894 /* create the mempool */
895 struct rte_mempool *
896 rte_mempool_create(const char *name, unsigned n, unsigned elt_size,
897         unsigned cache_size, unsigned private_data_size,
898         rte_mempool_ctor_t *mp_init, void *mp_init_arg,
899         rte_mempool_obj_cb_t *obj_init, void *obj_init_arg,
900         int socket_id, unsigned flags)
901 {
902         int ret;
903         struct rte_mempool *mp;
904
905         mp = rte_mempool_create_empty(name, n, elt_size, cache_size,
906                 private_data_size, socket_id, flags);
907         if (mp == NULL)
908                 return NULL;
909
910         /*
911          * Since we have 4 combinations of the SP/SC/MP/MC examine the flags to
912          * set the correct index into the table of ops structs.
913          */
914         if ((flags & MEMPOOL_F_SP_PUT) && (flags & MEMPOOL_F_SC_GET))
915                 ret = rte_mempool_set_ops_byname(mp, "ring_sp_sc", NULL);
916         else if (flags & MEMPOOL_F_SP_PUT)
917                 ret = rte_mempool_set_ops_byname(mp, "ring_sp_mc", NULL);
918         else if (flags & MEMPOOL_F_SC_GET)
919                 ret = rte_mempool_set_ops_byname(mp, "ring_mp_sc", NULL);
920         else
921                 ret = rte_mempool_set_ops_byname(mp, "ring_mp_mc", NULL);
922
923         if (ret)
924                 goto fail;
925
926         /* call the mempool priv initializer */
927         if (mp_init)
928                 mp_init(mp, mp_init_arg);
929
930         if (rte_mempool_populate_default(mp) < 0)
931                 goto fail;
932
933         /* call the object initializers */
934         if (obj_init)
935                 rte_mempool_obj_iter(mp, obj_init, obj_init_arg);
936
937         return mp;
938
939  fail:
940         rte_mempool_free(mp);
941         return NULL;
942 }
943
944 /* Return the number of entries in the mempool */
945 unsigned int
946 rte_mempool_avail_count(const struct rte_mempool *mp)
947 {
948         unsigned count;
949         unsigned lcore_id;
950
951         count = rte_mempool_ops_get_count(mp);
952
953         if (mp->cache_size == 0)
954                 return count;
955
956         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++)
957                 count += mp->local_cache[lcore_id].len;
958
959         /*
960          * due to race condition (access to len is not locked), the
961          * total can be greater than size... so fix the result
962          */
963         if (count > mp->size)
964                 return mp->size;
965         return count;
966 }
967
968 /* return the number of entries allocated from the mempool */
969 unsigned int
970 rte_mempool_in_use_count(const struct rte_mempool *mp)
971 {
972         return mp->size - rte_mempool_avail_count(mp);
973 }
974
975 /* dump the cache status */
976 static unsigned
977 rte_mempool_dump_cache(FILE *f, const struct rte_mempool *mp)
978 {
979         unsigned lcore_id;
980         unsigned count = 0;
981         unsigned cache_count;
982
983         fprintf(f, "  internal cache infos:\n");
984         fprintf(f, "    cache_size=%"PRIu32"\n", mp->cache_size);
985
986         if (mp->cache_size == 0)
987                 return count;
988
989         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
990                 cache_count = mp->local_cache[lcore_id].len;
991                 fprintf(f, "    cache_count[%u]=%"PRIu32"\n",
992                         lcore_id, cache_count);
993                 count += cache_count;
994         }
995         fprintf(f, "    total_cache_count=%u\n", count);
996         return count;
997 }
998
999 #ifndef __INTEL_COMPILER
1000 #pragma GCC diagnostic ignored "-Wcast-qual"
1001 #endif
1002
1003 /* check and update cookies or panic (internal) */
1004 void rte_mempool_check_cookies(const struct rte_mempool *mp,
1005         void * const *obj_table_const, unsigned n, int free)
1006 {
1007 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
1008         struct rte_mempool_objhdr *hdr;
1009         struct rte_mempool_objtlr *tlr;
1010         uint64_t cookie;
1011         void *tmp;
1012         void *obj;
1013         void **obj_table;
1014
1015         /* Force to drop the "const" attribute. This is done only when
1016          * DEBUG is enabled */
1017         tmp = (void *) obj_table_const;
1018         obj_table = tmp;
1019
1020         while (n--) {
1021                 obj = obj_table[n];
1022
1023                 if (rte_mempool_from_obj(obj) != mp)
1024                         rte_panic("MEMPOOL: object is owned by another "
1025                                   "mempool\n");
1026
1027                 hdr = __mempool_get_header(obj);
1028                 cookie = hdr->cookie;
1029
1030                 if (free == 0) {
1031                         if (cookie != RTE_MEMPOOL_HEADER_COOKIE1) {
1032                                 RTE_LOG(CRIT, MEMPOOL,
1033                                         "obj=%p, mempool=%p, cookie=%" PRIx64 "\n",
1034                                         obj, (const void *) mp, cookie);
1035                                 rte_panic("MEMPOOL: bad header cookie (put)\n");
1036                         }
1037                         hdr->cookie = RTE_MEMPOOL_HEADER_COOKIE2;
1038                 } else if (free == 1) {
1039                         if (cookie != RTE_MEMPOOL_HEADER_COOKIE2) {
1040                                 RTE_LOG(CRIT, MEMPOOL,
1041                                         "obj=%p, mempool=%p, cookie=%" PRIx64 "\n",
1042                                         obj, (const void *) mp, cookie);
1043                                 rte_panic("MEMPOOL: bad header cookie (get)\n");
1044                         }
1045                         hdr->cookie = RTE_MEMPOOL_HEADER_COOKIE1;
1046                 } else if (free == 2) {
1047                         if (cookie != RTE_MEMPOOL_HEADER_COOKIE1 &&
1048                             cookie != RTE_MEMPOOL_HEADER_COOKIE2) {
1049                                 RTE_LOG(CRIT, MEMPOOL,
1050                                         "obj=%p, mempool=%p, cookie=%" PRIx64 "\n",
1051                                         obj, (const void *) mp, cookie);
1052                                 rte_panic("MEMPOOL: bad header cookie (audit)\n");
1053                         }
1054                 }
1055                 tlr = __mempool_get_trailer(obj);
1056                 cookie = tlr->cookie;
1057                 if (cookie != RTE_MEMPOOL_TRAILER_COOKIE) {
1058                         RTE_LOG(CRIT, MEMPOOL,
1059                                 "obj=%p, mempool=%p, cookie=%" PRIx64 "\n",
1060                                 obj, (const void *) mp, cookie);
1061                         rte_panic("MEMPOOL: bad trailer cookie\n");
1062                 }
1063         }
1064 #else
1065         RTE_SET_USED(mp);
1066         RTE_SET_USED(obj_table_const);
1067         RTE_SET_USED(n);
1068         RTE_SET_USED(free);
1069 #endif
1070 }
1071
1072 void
1073 rte_mempool_contig_blocks_check_cookies(const struct rte_mempool *mp,
1074         void * const *first_obj_table_const, unsigned int n, int free)
1075 {
1076 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
1077         struct rte_mempool_info info;
1078         const size_t total_elt_sz =
1079                 mp->header_size + mp->elt_size + mp->trailer_size;
1080         unsigned int i, j;
1081
1082         rte_mempool_ops_get_info(mp, &info);
1083
1084         for (i = 0; i < n; ++i) {
1085                 void *first_obj = first_obj_table_const[i];
1086
1087                 for (j = 0; j < info.contig_block_size; ++j) {
1088                         void *obj;
1089
1090                         obj = (void *)((uintptr_t)first_obj + j * total_elt_sz);
1091                         rte_mempool_check_cookies(mp, &obj, 1, free);
1092                 }
1093         }
1094 #else
1095         RTE_SET_USED(mp);
1096         RTE_SET_USED(first_obj_table_const);
1097         RTE_SET_USED(n);
1098         RTE_SET_USED(free);
1099 #endif
1100 }
1101
1102 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
1103 static void
1104 mempool_obj_audit(struct rte_mempool *mp, __rte_unused void *opaque,
1105         void *obj, __rte_unused unsigned idx)
1106 {
1107         __mempool_check_cookies(mp, &obj, 1, 2);
1108 }
1109
1110 static void
1111 mempool_audit_cookies(struct rte_mempool *mp)
1112 {
1113         unsigned num;
1114
1115         num = rte_mempool_obj_iter(mp, mempool_obj_audit, NULL);
1116         if (num != mp->size) {
1117                 rte_panic("rte_mempool_obj_iter(mempool=%p, size=%u) "
1118                         "iterated only over %u elements\n",
1119                         mp, mp->size, num);
1120         }
1121 }
1122 #else
1123 #define mempool_audit_cookies(mp) do {} while(0)
1124 #endif
1125
1126 #ifndef __INTEL_COMPILER
1127 #pragma GCC diagnostic error "-Wcast-qual"
1128 #endif
1129
1130 /* check cookies before and after objects */
1131 static void
1132 mempool_audit_cache(const struct rte_mempool *mp)
1133 {
1134         /* check cache size consistency */
1135         unsigned lcore_id;
1136
1137         if (mp->cache_size == 0)
1138                 return;
1139
1140         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
1141                 const struct rte_mempool_cache *cache;
1142                 cache = &mp->local_cache[lcore_id];
1143                 if (cache->len > cache->flushthresh) {
1144                         RTE_LOG(CRIT, MEMPOOL, "badness on cache[%u]\n",
1145                                 lcore_id);
1146                         rte_panic("MEMPOOL: invalid cache len\n");
1147                 }
1148         }
1149 }
1150
1151 /* check the consistency of mempool (size, cookies, ...) */
1152 void
1153 rte_mempool_audit(struct rte_mempool *mp)
1154 {
1155         mempool_audit_cache(mp);
1156         mempool_audit_cookies(mp);
1157
1158         /* For case where mempool DEBUG is not set, and cache size is 0 */
1159         RTE_SET_USED(mp);
1160 }
1161
1162 /* dump the status of the mempool on the console */
1163 void
1164 rte_mempool_dump(FILE *f, struct rte_mempool *mp)
1165 {
1166 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
1167         struct rte_mempool_info info;
1168         struct rte_mempool_debug_stats sum;
1169         unsigned lcore_id;
1170 #endif
1171         struct rte_mempool_memhdr *memhdr;
1172         unsigned common_count;
1173         unsigned cache_count;
1174         size_t mem_len = 0;
1175
1176         RTE_ASSERT(f != NULL);
1177         RTE_ASSERT(mp != NULL);
1178
1179         fprintf(f, "mempool <%s>@%p\n", mp->name, mp);
1180         fprintf(f, "  flags=%x\n", mp->flags);
1181         fprintf(f, "  pool=%p\n", mp->pool_data);
1182         fprintf(f, "  iova=0x%" PRIx64 "\n", mp->mz->iova);
1183         fprintf(f, "  nb_mem_chunks=%u\n", mp->nb_mem_chunks);
1184         fprintf(f, "  size=%"PRIu32"\n", mp->size);
1185         fprintf(f, "  populated_size=%"PRIu32"\n", mp->populated_size);
1186         fprintf(f, "  header_size=%"PRIu32"\n", mp->header_size);
1187         fprintf(f, "  elt_size=%"PRIu32"\n", mp->elt_size);
1188         fprintf(f, "  trailer_size=%"PRIu32"\n", mp->trailer_size);
1189         fprintf(f, "  total_obj_size=%"PRIu32"\n",
1190                mp->header_size + mp->elt_size + mp->trailer_size);
1191
1192         fprintf(f, "  private_data_size=%"PRIu32"\n", mp->private_data_size);
1193
1194         STAILQ_FOREACH(memhdr, &mp->mem_list, next)
1195                 mem_len += memhdr->len;
1196         if (mem_len != 0) {
1197                 fprintf(f, "  avg bytes/object=%#Lf\n",
1198                         (long double)mem_len / mp->size);
1199         }
1200
1201         cache_count = rte_mempool_dump_cache(f, mp);
1202         common_count = rte_mempool_ops_get_count(mp);
1203         if ((cache_count + common_count) > mp->size)
1204                 common_count = mp->size - cache_count;
1205         fprintf(f, "  common_pool_count=%u\n", common_count);
1206
1207         /* sum and dump statistics */
1208 #ifdef RTE_LIBRTE_MEMPOOL_DEBUG
1209         rte_mempool_ops_get_info(mp, &info);
1210         memset(&sum, 0, sizeof(sum));
1211         for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
1212                 sum.put_bulk += mp->stats[lcore_id].put_bulk;
1213                 sum.put_objs += mp->stats[lcore_id].put_objs;
1214                 sum.get_success_bulk += mp->stats[lcore_id].get_success_bulk;
1215                 sum.get_success_objs += mp->stats[lcore_id].get_success_objs;
1216                 sum.get_fail_bulk += mp->stats[lcore_id].get_fail_bulk;
1217                 sum.get_fail_objs += mp->stats[lcore_id].get_fail_objs;
1218                 sum.get_success_blks += mp->stats[lcore_id].get_success_blks;
1219                 sum.get_fail_blks += mp->stats[lcore_id].get_fail_blks;
1220         }
1221         fprintf(f, "  stats:\n");
1222         fprintf(f, "    put_bulk=%"PRIu64"\n", sum.put_bulk);
1223         fprintf(f, "    put_objs=%"PRIu64"\n", sum.put_objs);
1224         fprintf(f, "    get_success_bulk=%"PRIu64"\n", sum.get_success_bulk);
1225         fprintf(f, "    get_success_objs=%"PRIu64"\n", sum.get_success_objs);
1226         fprintf(f, "    get_fail_bulk=%"PRIu64"\n", sum.get_fail_bulk);
1227         fprintf(f, "    get_fail_objs=%"PRIu64"\n", sum.get_fail_objs);
1228         if (info.contig_block_size > 0) {
1229                 fprintf(f, "    get_success_blks=%"PRIu64"\n",
1230                         sum.get_success_blks);
1231                 fprintf(f, "    get_fail_blks=%"PRIu64"\n", sum.get_fail_blks);
1232         }
1233 #else
1234         fprintf(f, "  no statistics available\n");
1235 #endif
1236
1237         rte_mempool_audit(mp);
1238 }
1239
1240 /* dump the status of all mempools on the console */
1241 void
1242 rte_mempool_list_dump(FILE *f)
1243 {
1244         struct rte_mempool *mp = NULL;
1245         struct rte_tailq_entry *te;
1246         struct rte_mempool_list *mempool_list;
1247
1248         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
1249
1250         rte_mcfg_mempool_read_lock();
1251
1252         TAILQ_FOREACH(te, mempool_list, next) {
1253                 mp = (struct rte_mempool *) te->data;
1254                 rte_mempool_dump(f, mp);
1255         }
1256
1257         rte_mcfg_mempool_read_unlock();
1258 }
1259
1260 /* search a mempool from its name */
1261 struct rte_mempool *
1262 rte_mempool_lookup(const char *name)
1263 {
1264         struct rte_mempool *mp = NULL;
1265         struct rte_tailq_entry *te;
1266         struct rte_mempool_list *mempool_list;
1267
1268         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
1269
1270         rte_mcfg_mempool_read_lock();
1271
1272         TAILQ_FOREACH(te, mempool_list, next) {
1273                 mp = (struct rte_mempool *) te->data;
1274                 if (strncmp(name, mp->name, RTE_MEMPOOL_NAMESIZE) == 0)
1275                         break;
1276         }
1277
1278         rte_mcfg_mempool_read_unlock();
1279
1280         if (te == NULL) {
1281                 rte_errno = ENOENT;
1282                 return NULL;
1283         }
1284
1285         return mp;
1286 }
1287
1288 void rte_mempool_walk(void (*func)(struct rte_mempool *, void *),
1289                       void *arg)
1290 {
1291         struct rte_tailq_entry *te = NULL;
1292         struct rte_mempool_list *mempool_list;
1293         void *tmp_te;
1294
1295         mempool_list = RTE_TAILQ_CAST(rte_mempool_tailq.head, rte_mempool_list);
1296
1297         rte_mcfg_mempool_read_lock();
1298
1299         TAILQ_FOREACH_SAFE(te, mempool_list, next, tmp_te) {
1300                 (*func)((struct rte_mempool *) te->data, arg);
1301         }
1302
1303         rte_mcfg_mempool_read_unlock();
1304 }