buffer.c 1.5 KB

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