qmemman_algo.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. #!/usr/bin/python2
  2. # -*- coding: utf-8 -*-
  3. #
  4. # The Qubes OS Project, http://www.qubes-os.org
  5. #
  6. # Copyright (C) 2010 Rafal Wojtczuk <rafal@invisiblethingslab.com>
  7. # Copyright (C) 2013 Marek Marczykowski <marmarek@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU General Public License
  11. # as published by the Free Software Foundation; either version 2
  12. # of the License, or (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with this program; if not, write to the Free Software
  21. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  22. #
  23. #
  24. import string
  25. # This are only defaults - can be overriden by QMemmanServer with values from
  26. # config file
  27. CACHE_FACTOR = 1.3
  28. MIN_PREFMEM = 200*1024*1024
  29. DOM0_MEM_BOOST = 350*1024*1024
  30. #untrusted meminfo size is taken from xenstore key, thus its size is limited
  31. #so splits do not require excessive memory
  32. def parse_meminfo(untrusted_meminfo):
  33. untrusted_dict = {}
  34. #split meminfo contents into lines
  35. untrusted_lines = string.split(untrusted_meminfo,"\n")
  36. for untrusted_lines_iterator in untrusted_lines:
  37. #split a single meminfo line into words
  38. untrusted_words = string.split(untrusted_lines_iterator)
  39. if len(untrusted_words) >= 2:
  40. untrusted_dict[string.rstrip(untrusted_words[0], ":")] = untrusted_words[1]
  41. return untrusted_dict
  42. def is_meminfo_suspicious(domain, untrusted_meminfo):
  43. ret = False
  44. #check whether the required keys exist and are not negative
  45. try:
  46. for i in ('MemTotal', 'MemFree', 'Buffers', 'Cached', 'SwapTotal', 'SwapFree'):
  47. val = int(untrusted_meminfo[i])*1024
  48. if (val < 0):
  49. ret = True
  50. untrusted_meminfo[i] = val
  51. except:
  52. ret = True
  53. if not ret and untrusted_meminfo['SwapTotal'] < untrusted_meminfo['SwapFree']:
  54. ret = True
  55. if not ret and untrusted_meminfo['MemTotal'] < untrusted_meminfo['MemFree'] + untrusted_meminfo['Cached'] + untrusted_meminfo['Buffers']:
  56. ret = True
  57. #we could also impose some limits on all the above values
  58. #but it has little purpose - all the domain can gain by passing e.g.
  59. #very large SwapTotal is that it will be assigned all free Xen memory
  60. #it can be achieved with legal values, too, and it will not allow to
  61. #starve existing domains, by design
  62. if ret:
  63. print 'suspicious meminfo for domain', domain.id, 'mem actual', domain.memory_actual, untrusted_meminfo
  64. return ret
  65. #called when a domain updates its 'meminfo' xenstore key
  66. def refresh_meminfo_for_domain(domain, untrusted_xenstore_key):
  67. untrusted_meminfo = parse_meminfo(untrusted_xenstore_key)
  68. if untrusted_meminfo is None:
  69. domain.meminfo = None
  70. return
  71. #sanitize start
  72. if is_meminfo_suspicious(domain, untrusted_meminfo):
  73. #sanitize end
  74. domain.meminfo = None
  75. domain.mem_used = None
  76. else:
  77. #sanitized, can assign
  78. domain.meminfo = untrusted_meminfo
  79. domain.mem_used = domain.meminfo['MemTotal'] - domain.meminfo['MemFree'] - domain.meminfo['Cached'] - domain.meminfo['Buffers'] + domain.meminfo['SwapTotal'] - domain.meminfo['SwapFree']
  80. def prefmem(domain):
  81. #dom0 is special, as it must have large cache, for vbds. Thus, give it a special boost
  82. if domain.id == '0':
  83. return min(domain.mem_used*CACHE_FACTOR + 350*1024*1024, domain.memory_maximum)
  84. return max(min(domain.mem_used*CACHE_FACTOR, domain.memory_maximum), MIN_PREFMEM)
  85. def memory_needed(domain):
  86. #do not change
  87. #in balance(), "distribute total_available_memory proportionally to mempref" relies on this exact formula
  88. ret = prefmem(domain) - domain.memory_actual
  89. return ret
  90. #prepare list of (domain, memory_target) pairs that need to be passed
  91. #to "xm memset" equivalent in order to obtain "memsize" of memory
  92. #return empty list when the request cannot be satisfied
  93. def balloon(memsize, domain_dictionary):
  94. REQ_SAFETY_NET_FACTOR = 1.05
  95. donors = list()
  96. request = list()
  97. available = 0
  98. for i in domain_dictionary.keys():
  99. if domain_dictionary[i].meminfo is None:
  100. continue
  101. if domain_dictionary[i].no_progress:
  102. continue
  103. need = memory_needed(domain_dictionary[i])
  104. if need < 0:
  105. print 'balloon: dom' , i, 'has actual memory', domain_dictionary[i].memory_actual
  106. donors.append((i,-need))
  107. available-=need
  108. print 'req=', memsize, 'avail=', available, 'donors', donors
  109. if available<memsize:
  110. return ()
  111. scale = 1.0*memsize/available
  112. for donors_iter in donors:
  113. id, mem = donors_iter
  114. memborrowed = mem*scale*REQ_SAFETY_NET_FACTOR
  115. print 'borrow' , memborrowed, 'from', id
  116. memtarget = int(domain_dictionary[id].memory_actual - memborrowed)
  117. request.append((id, memtarget))
  118. return request
  119. # REQ_SAFETY_NET_FACTOR is a bit greater that 1. So that if the domain yields a bit less than requested, due
  120. # to e.g. rounding errors, we will not get stuck. The surplus will return to the VM during "balance" call.
  121. #redistribute positive "total_available_memory" of memory between domains, proportionally to prefmem
  122. def balance_when_enough_memory(domain_dictionary, xen_free_memory, total_mem_pref, total_available_memory):
  123. print 'balance_when_enough_memory(', xen_free_memory, total_mem_pref, total_available_memory, ')'
  124. target_memory = {}
  125. # memory not assigned because of static max
  126. left_memory = 0
  127. acceptors_count = 0
  128. for i in domain_dictionary.keys():
  129. if domain_dictionary[i].meminfo is None:
  130. continue
  131. if domain_dictionary[i].no_progress:
  132. continue
  133. #distribute total_available_memory proportionally to mempref
  134. scale = 1.0*prefmem(domain_dictionary[i])/total_mem_pref
  135. target_nonint = prefmem(domain_dictionary[i]) + scale*total_available_memory
  136. #prevent rounding errors
  137. target = int(0.999*target_nonint)
  138. #do not try to give more memory than static max
  139. if target > domain_dictionary[i].memory_maximum:
  140. left_memory += target-domain_dictionary[i].memory_maximum
  141. target = domain_dictionary[i].memory_maximum
  142. else:
  143. # count domains which can accept more memory
  144. acceptors_count += 1
  145. target_memory[i] = target
  146. # distribute left memory across all acceptors
  147. while left_memory > 0 and acceptors_count > 0:
  148. print ' left_memory:', left_memory, 'acceptors_count:', acceptors_count
  149. new_left_memory = 0
  150. new_acceptors_count = acceptors_count
  151. for i in target_memory.keys():
  152. target = target_memory[i]
  153. if target < domain_dictionary[i].memory_maximum:
  154. memory_bonus = int(0.999*(left_memory/acceptors_count))
  155. if target+memory_bonus >= domain_dictionary[i].memory_maximum:
  156. new_left_memory += target+memory_bonus - domain_dictionary[i].memory_maximum
  157. target = domain_dictionary[i].memory_maximum
  158. new_acceptors_count -= 1
  159. else:
  160. target += memory_bonus
  161. target_memory[i] = target
  162. left_memory = new_left_memory
  163. acceptors_count = new_acceptors_count
  164. # split target_memory dictionary to donors and acceptors
  165. # this is needed to first get memory from donors and only then give it to acceptors
  166. donors_rq = list()
  167. acceptors_rq = list()
  168. for i in target_memory.keys():
  169. target = target_memory[i]
  170. if (target < domain_dictionary[i].memory_actual):
  171. donors_rq.append((i, target))
  172. else:
  173. acceptors_rq.append((i, target))
  174. # print 'balance(enough): xen_free_memory=', xen_free_memory, 'requests:', donors_rq + acceptors_rq
  175. return donors_rq + acceptors_rq
  176. #when not enough mem to make everyone be above prefmem, make donors be at prefmem, and
  177. #redistribute anything left between acceptors
  178. def balance_when_low_on_memory(domain_dictionary, xen_free_memory, total_mem_pref_acceptors, donors, acceptors):
  179. donors_rq = list()
  180. acceptors_rq = list()
  181. squeezed_mem = xen_free_memory
  182. for i in donors:
  183. avail = -memory_needed(domain_dictionary[i])
  184. if avail < 10*1024*1024:
  185. #probably we have already tried making it exactly at prefmem, give up
  186. continue
  187. squeezed_mem -= avail
  188. donors_rq.append((i, prefmem(domain_dictionary[i])))
  189. #the below can happen if initially xen free memory is below 50M
  190. if squeezed_mem < 0:
  191. return donors_rq
  192. for i in acceptors:
  193. scale = 1.0*prefmem(domain_dictionary[i])/total_mem_pref_acceptors
  194. target_nonint = domain_dictionary[i].memory_actual + scale*squeezed_mem
  195. #do not try to give more memory than static max
  196. target = min(int(0.999*target_nonint), domain_dictionary[i].memory_maximum)
  197. acceptors_rq.append((i, target))
  198. # print 'balance(low): xen_free_memory=', xen_free_memory, 'requests:', donors_rq + acceptors_rq
  199. return donors_rq + acceptors_rq
  200. #redistribute memory across domains
  201. #called when one of domains update its 'meminfo' xenstore key
  202. #return the list of (domain, memory_target) pairs to be passed to
  203. #"xm memset" equivalent
  204. def balance(xen_free_memory, domain_dictionary):
  205. #sum of all memory requirements - in other words, the difference between
  206. #memory required to be added to domains (acceptors) to make them be at their
  207. #preferred memory, and memory that can be taken from domains (donors) that
  208. #can provide memory. So, it can be negative when plenty of memory.
  209. total_memory_needed = 0
  210. #sum of memory preferences of all domains
  211. total_mem_pref = 0
  212. #sum of memory preferences of all domains that require more memory
  213. total_mem_pref_acceptors = 0
  214. donors = list() # domains that can yield memory
  215. acceptors = list() # domains that require more memory
  216. #pass 1: compute the above "total" values
  217. for i in domain_dictionary.keys():
  218. if domain_dictionary[i].meminfo is None:
  219. continue
  220. if domain_dictionary[i].no_progress:
  221. continue
  222. need = memory_needed(domain_dictionary[i])
  223. # print 'domain' , i, 'act/pref', domain_dictionary[i].memory_actual, prefmem(domain_dictionary[i]), 'need=', need
  224. if need < 0 or domain_dictionary[i].memory_actual >= domain_dictionary[i].memory_maximum:
  225. donors.append(i)
  226. else:
  227. acceptors.append(i)
  228. total_mem_pref_acceptors += prefmem(domain_dictionary[i])
  229. total_memory_needed += need
  230. total_mem_pref += prefmem(domain_dictionary[i])
  231. total_available_memory = xen_free_memory - total_memory_needed
  232. if total_available_memory > 0:
  233. return balance_when_enough_memory(domain_dictionary, xen_free_memory, total_mem_pref, total_available_memory)
  234. else:
  235. return balance_when_low_on_memory(domain_dictionary, xen_free_memory, total_mem_pref_acceptors, donors, acceptors)