2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2011 Daniel Borkmann.
4 * Subject to the GPL, version 2.
21 struct map_entry
*next
;
24 static struct hash_table mapper
;
26 static unsigned int *cpu_assigned
= NULL
;
28 static unsigned int cpu_len
= 0;
30 static struct rwlock map_lock
;
32 void init_cpusched(unsigned int cpus
)
34 rwlock_init(&map_lock
);
35 rwlock_wr_lock(&map_lock
);
38 cpu_assigned
= xzmalloc(cpus
* sizeof(*cpu_assigned
));
40 memset(&mapper
, 0, sizeof(mapper
));
43 rwlock_unlock(&map_lock
);
46 static int get_appropriate_cpu(void)
51 for (i
= 0; i
< cpu_len
; ++i
) {
52 if (cpu_assigned
[i
] < work
) {
53 work
= cpu_assigned
[i
];
61 unsigned int socket_to_cpu(int fd
)
64 struct map_entry
*entry
;
68 rwlock_rd_lock(&map_lock
);
70 entry
= lookup_hash(fd
, &mapper
);
71 while (entry
&& fd
!= entry
->fd
)
73 if (entry
&& fd
== entry
->fd
)
78 rwlock_unlock(&map_lock
);
83 unsigned int register_socket(int fd
)
86 struct map_entry
*entry
;
88 rwlock_wr_lock(&map_lock
);
90 entry
= xzmalloc(sizeof(*entry
));
92 entry
->cpu
= get_appropriate_cpu();
94 cpu_assigned
[entry
->cpu
]++;
96 pos
= insert_hash(entry
->fd
, entry
, &mapper
);
102 rwlock_unlock(&map_lock
);
107 static struct map_entry
*socket_to_map_entry(int fd
)
109 struct map_entry
*entry
, *ret
= NULL
;
113 rwlock_rd_lock(&map_lock
);
115 entry
= lookup_hash(fd
, &mapper
);
116 while (entry
&& fd
!= entry
->fd
)
118 if (entry
&& fd
== entry
->fd
)
123 rwlock_unlock(&map_lock
);
128 void unregister_socket(int fd
)
130 struct map_entry
*pos
;
131 struct map_entry
*entry
= socket_to_map_entry(fd
);
133 if (!entry
== 0 && errno
== ENOENT
)
136 rwlock_wr_lock(&map_lock
);
138 cpu_assigned
[entry
->cpu
]--;
140 pos
= remove_hash(entry
->fd
, entry
, entry
->next
, &mapper
);
141 while (pos
&& pos
->next
&& pos
->next
!= entry
)
143 if (pos
&& pos
->next
&& pos
->next
== entry
)
144 pos
->next
= entry
->next
;
149 rwlock_unlock(&map_lock
);
152 static int cleanup_batch(void *ptr
)
154 struct map_entry
*next
;
155 struct map_entry
*e
= ptr
;
159 while ((next
= e
->next
)) {
169 void destroy_cpusched(void)
171 rwlock_wr_lock(&map_lock
);
175 for_each_hash(&mapper
, cleanup_batch
);
178 rwlock_unlock(&map_lock
);
179 rwlock_destroy(&map_lock
);