1 /******************************************************************************
2 *
3 * Copyright (c) 2009 Citrix Systems, Inc. (Grzegorz Milos)
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; If not, see <http://www.gnu.org/licenses/>.
17 */
18 #include <pthread.h>
19 #include <inttypes.h>
20 #include <unistd.h>
21 #include <errno.h>
22
23 #include "bidir-hash.h"
24 #include "memshr-priv.h"
25
26 static struct blockshr_hash *blks_hash;
27
28 /* Callback in the iterator, remember this value, and leave */
find_one(vbdblk_t k,share_tuple_t v,void * priv)29 int find_one(vbdblk_t k, share_tuple_t v, void *priv)
30 {
31 share_tuple_t *rv = (share_tuple_t *) priv;
32 *rv = v;
33 /* Break out of iterator loop */
34 return 1;
35 }
36
bidir_daemon(void * unused)37 void* bidir_daemon(void *unused)
38 {
39 uint32_t nr_ent, max_nr_ent, tab_size, max_load, min_load;
40
41 while(1)
42 {
43 blockshr_hash_sizes( blks_hash,
44 &nr_ent,
45 &max_nr_ent,
46 &tab_size,
47 &max_load,
48 &min_load);
49 /* Remove some hints as soon as we get to 90% capacity */
50 if(10 * nr_ent > 9 * max_nr_ent)
51 {
52 share_tuple_t next_remove;
53 int to_remove;
54 int ret;
55
56 to_remove = 0.1 * max_nr_ent;
57 while(to_remove > 0)
58 {
59 /* We use the iterator to get one entry */
60 next_remove.handle = 0;
61 ret = blockshr_hash_iterator(blks_hash, find_one, &next_remove);
62
63 if ( !ret )
64 if ( next_remove.handle == 0 )
65 ret = -ESRCH;
66
67 if ( !ret )
68 ret = blockshr_shrhnd_remove(blks_hash, next_remove, NULL);
69
70 if(ret <= 0)
71 {
72 /* We failed to remove an entry, because of a serious hash
73 * table error */
74 DPRINTF("Could not remove handle %"PRId64", error: %d\n",
75 next_remove.handle, ret);
76 /* Force to exit the loop early */
77 to_remove = 0;
78 } else
79 if(ret > 0)
80 {
81 /* Managed to remove the entry. Note next_remove not
82 * incremented, in case there are duplicates */
83 to_remove--;
84 }
85 }
86 }
87
88 sleep(1);
89 }
90 }
91
bidir_daemon_launch(void)92 void bidir_daemon_launch(void)
93 {
94 pthread_t thread;
95
96 pthread_create(&thread, NULL, bidir_daemon, NULL);
97 }
98
bidir_daemon_initialize(struct blockshr_hash * blks)99 void bidir_daemon_initialize(struct blockshr_hash *blks)
100 {
101 blks_hash = blks;
102 bidir_daemon_launch();
103 }
104