buffer.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include "ceph_debug.h"
  2. #include <linux/slab.h>
  3. #include "buffer.h"
  4. #include "decode.h"
  5. struct ceph_buffer *ceph_buffer_new(size_t len, gfp_t gfp)
  6. {
  7. struct ceph_buffer *b;
  8. b = kmalloc(sizeof(*b), gfp);
  9. if (!b)
  10. return NULL;
  11. b->vec.iov_base = kmalloc(len, gfp | __GFP_NOWARN);
  12. if (b->vec.iov_base) {
  13. b->is_vmalloc = false;
  14. } else {
  15. b->vec.iov_base = __vmalloc(len, gfp, PAGE_KERNEL);
  16. if (!b->vec.iov_base) {
  17. kfree(b);
  18. return NULL;
  19. }
  20. b->is_vmalloc = true;
  21. }
  22. kref_init(&b->kref);
  23. b->alloc_len = len;
  24. b->vec.iov_len = len;
  25. dout("buffer_new %p\n", b);
  26. return b;
  27. }
  28. void ceph_buffer_release(struct kref *kref)
  29. {
  30. struct ceph_buffer *b = container_of(kref, struct ceph_buffer, kref);
  31. dout("buffer_release %p\n", b);
  32. if (b->vec.iov_base) {
  33. if (b->is_vmalloc)
  34. vfree(b->vec.iov_base);
  35. else
  36. kfree(b->vec.iov_base);
  37. }
  38. kfree(b);
  39. }
  40. int ceph_buffer_alloc(struct ceph_buffer *b, int len, gfp_t gfp)
  41. {
  42. b->vec.iov_base = kmalloc(len, gfp | __GFP_NOWARN);
  43. if (b->vec.iov_base) {
  44. b->is_vmalloc = false;
  45. } else {
  46. b->vec.iov_base = __vmalloc(len, gfp, PAGE_KERNEL);
  47. b->is_vmalloc = true;
  48. }
  49. if (!b->vec.iov_base)
  50. return -ENOMEM;
  51. b->alloc_len = len;
  52. b->vec.iov_len = len;
  53. return 0;
  54. }
  55. int ceph_decode_buffer(struct ceph_buffer **b, void **p, void *end)
  56. {
  57. size_t len;
  58. ceph_decode_need(p, end, sizeof(u32), bad);
  59. len = ceph_decode_32(p);
  60. dout("decode_buffer len %d\n", (int)len);
  61. ceph_decode_need(p, end, len, bad);
  62. *b = ceph_buffer_new(len, GFP_NOFS);
  63. if (!*b)
  64. return -ENOMEM;
  65. ceph_decode_copy(p, (*b)->vec.iov_base, len);
  66. return 0;
  67. bad:
  68. return -EINVAL;
  69. }