EventRingBuffer.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // EventRingBuffer.cpp - 环形缓冲实现
  2. #include <ntddk.h>
  3. #include <wdf.h>
  4. #include "EventRingBuffer.h"
  5. namespace commkit_driver {
  6. NTSTATUS EventRingBuffer::Initialize() {
  7. // 分配非分页内存(可在 DISPATCH_LEVEL 访问)
  8. buffer_ = nullptr;
  9. head_ = tail_ = count_ = 0;
  10. KeInitializeSpinLock(&lock_);
  11. ULONG size = sizeof(COMMKIT_EVENT) * COMMKIT_RING_CAPACITY;
  12. buffer_ = (COMMKIT_EVENT*)ExAllocatePool2(
  13. POOL_FLAG_NON_PAGED, size, 'BCMK');
  14. if (!buffer_) {
  15. return STATUS_INSUFFICIENT_RESOURCES;
  16. }
  17. RtlZeroMemory(buffer_, size);
  18. head_ = tail_ = count_ = 0;
  19. return STATUS_SUCCESS;
  20. }
  21. void EventRingBuffer::Cleanup() {
  22. if (buffer_) {
  23. ExFreePoolWithTag(buffer_, 'BCMK');
  24. buffer_ = nullptr;
  25. }
  26. count_ = head_ = tail_ = 0;
  27. }
  28. void EventRingBuffer::Push(ULONG sequence, UINT64 timestamp,
  29. ULONG com_number, ULONG event_type,
  30. ULONG data_size, PVOID data) {
  31. KIRQL old_irql;
  32. KeAcquireSpinLock(&lock_, &old_irql);
  33. if (!buffer_) {
  34. KeReleaseSpinLock(&lock_, old_irql);
  35. return;
  36. }
  37. // 截断超长数据
  38. ULONG copy_size = data_size;
  39. if (copy_size > COMMKIT_MAX_DATA) {
  40. copy_size = COMMKIT_MAX_DATA;
  41. }
  42. // 写入 head 位置
  43. COMMKIT_EVENT* slot = &buffer_[head_];
  44. slot->Sequence = (INT32)sequence;
  45. slot->TimeStamp = timestamp;
  46. slot->ComNumber = com_number;
  47. slot->EventType = event_type;
  48. slot->DataSize = copy_size;
  49. if (copy_size > 0 && data) {
  50. RtlCopyMemory(slot->Data, data, copy_size);
  51. }
  52. // 推进 head
  53. head_ = (head_ + 1) % COMMKIT_RING_CAPACITY;
  54. if (count_ == COMMKIT_RING_CAPACITY) {
  55. // 满了,覆盖最旧:tail 跟随 head
  56. tail_ = head_;
  57. } else {
  58. count_++;
  59. }
  60. KeReleaseSpinLock(&lock_, old_irql);
  61. }
  62. LONG EventRingBuffer::PopBatch(PCOMMKIT_EVENT out_buf, LONG max_count) {
  63. if (!out_buf || max_count <= 0) return 0;
  64. KIRQL old_irql;
  65. KeAcquireSpinLock(&lock_, &old_irql);
  66. if (!buffer_) {
  67. KeReleaseSpinLock(&lock_, old_irql);
  68. return 0;
  69. }
  70. LONG to_pop = count_ < max_count ? count_ : max_count;
  71. for (LONG i = 0; i < to_pop; ++i) {
  72. RtlCopyMemory(&out_buf[i], &buffer_[tail_], sizeof(COMMKIT_EVENT));
  73. tail_ = (tail_ + 1) % COMMKIT_RING_CAPACITY;
  74. }
  75. count_ -= to_pop;
  76. KeReleaseSpinLock(&lock_, old_irql);
  77. return to_pop;
  78. }
  79. void EventRingBuffer::Clear() {
  80. KIRQL old_irql;
  81. KeAcquireSpinLock(&lock_, &old_irql);
  82. head_ = tail_ = count_ = 0;
  83. KeReleaseSpinLock(&lock_, old_irql);
  84. }
  85. } // namespace commkit_driver