1 /* Copyright (c) 2011-2018 Dovecot authors, see the included COPYING file */
2 
3 #include "lib.h"
4 #include "mail-command.h"
5 #include "mail-session.h"
6 #include "mail-user.h"
7 #include "mail-domain.h"
8 #include "mail-ip.h"
9 #include "stats-settings.h"
10 #include "global-memory.h"
11 
12 size_t global_used_memory = 0;
13 
global_memory_free_something(void)14 static bool global_memory_free_something(void)
15 {
16 	size_t orig_used_memory = global_used_memory;
17 
18 	mail_commands_free_memory();
19 	if (global_used_memory > stats_settings->memory_limit)
20 		mail_sessions_free_memory();
21 	if (global_used_memory > stats_settings->memory_limit)
22 		mail_users_free_memory();
23 	if (global_used_memory > stats_settings->memory_limit)
24 		mail_ips_free_memory();
25 	if (global_used_memory > stats_settings->memory_limit)
26 		mail_domains_free_memory();
27 
28 	return global_used_memory < orig_used_memory;
29 }
30 
global_memory_alloc(size_t size)31 void global_memory_alloc(size_t size)
32 {
33 	i_assert(size < SIZE_MAX - global_used_memory);
34 	global_used_memory += size;
35 
36 	while (global_used_memory > stats_settings->memory_limit) {
37 		if (!global_memory_free_something())
38 			break;
39 	}
40 }
41 
global_memory_free(size_t size)42 void global_memory_free(size_t size)
43 {
44 	i_assert(size <= global_used_memory);
45 	global_used_memory -= size;
46 }
47