linux.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #include <stdlib.h>
  2. #include <string.h>
  3. #include <malloc.h>
  4. #include <pthread.h>
  5. #include <unistd.h>
  6. #include <assert.h>
  7. #include <linux/gfp.h>
  8. #include <linux/poison.h>
  9. #include <linux/slab.h>
  10. #include <linux/radix-tree.h>
  11. #include <urcu/uatomic.h>
  12. int nr_allocated;
  13. int preempt_count;
  14. int kmalloc_verbose;
  15. struct kmem_cache {
  16. pthread_mutex_t lock;
  17. int size;
  18. int nr_objs;
  19. void *objs;
  20. void (*ctor)(void *);
  21. };
  22. void *kmem_cache_alloc(struct kmem_cache *cachep, int flags)
  23. {
  24. struct radix_tree_node *node;
  25. if (flags & __GFP_NOWARN)
  26. return NULL;
  27. pthread_mutex_lock(&cachep->lock);
  28. if (cachep->nr_objs) {
  29. cachep->nr_objs--;
  30. node = cachep->objs;
  31. cachep->objs = node->private_data;
  32. pthread_mutex_unlock(&cachep->lock);
  33. node->private_data = NULL;
  34. } else {
  35. pthread_mutex_unlock(&cachep->lock);
  36. node = malloc(cachep->size);
  37. if (cachep->ctor)
  38. cachep->ctor(node);
  39. }
  40. uatomic_inc(&nr_allocated);
  41. if (kmalloc_verbose)
  42. printf("Allocating %p from slab\n", node);
  43. return node;
  44. }
  45. void kmem_cache_free(struct kmem_cache *cachep, void *objp)
  46. {
  47. assert(objp);
  48. uatomic_dec(&nr_allocated);
  49. if (kmalloc_verbose)
  50. printf("Freeing %p to slab\n", objp);
  51. pthread_mutex_lock(&cachep->lock);
  52. if (cachep->nr_objs > 10) {
  53. memset(objp, POISON_FREE, cachep->size);
  54. free(objp);
  55. } else {
  56. struct radix_tree_node *node = objp;
  57. cachep->nr_objs++;
  58. node->private_data = cachep->objs;
  59. cachep->objs = node;
  60. }
  61. pthread_mutex_unlock(&cachep->lock);
  62. }
  63. void *kmalloc(size_t size, gfp_t gfp)
  64. {
  65. void *ret = malloc(size);
  66. uatomic_inc(&nr_allocated);
  67. if (kmalloc_verbose)
  68. printf("Allocating %p from malloc\n", ret);
  69. return ret;
  70. }
  71. void kfree(void *p)
  72. {
  73. if (!p)
  74. return;
  75. uatomic_dec(&nr_allocated);
  76. if (kmalloc_verbose)
  77. printf("Freeing %p to malloc\n", p);
  78. free(p);
  79. }
  80. struct kmem_cache *
  81. kmem_cache_create(const char *name, size_t size, size_t offset,
  82. unsigned long flags, void (*ctor)(void *))
  83. {
  84. struct kmem_cache *ret = malloc(sizeof(*ret));
  85. pthread_mutex_init(&ret->lock, NULL);
  86. ret->size = size;
  87. ret->nr_objs = 0;
  88. ret->objs = NULL;
  89. ret->ctor = ctor;
  90. return ret;
  91. }